'use strict';

var app = require('@firebase/app');
var util = require('@firebase/util');
var bloomBlob = require('@firebase/webchannel-wrapper/bloom-blob');
var logger = require('@firebase/logger');
var webchannelBlob = require('@firebase/webchannel-wrapper/webchannel-blob');
var re2js = require('re2js');

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** The semver (www.semver.org) version of the SDK. */
let ve = "12.17.0";

function __PRIVATE_setSDKVersion(e) {
    ve = e;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Formats an object as a JSON string, suitable for logging. */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const Se = new logger.Logger("@firebase/firestore");

// Helper methods are needed because variables can't be exported as read/write
function __PRIVATE_getLogLevel() {
    return Se.logLevel;
}

/**
 * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
 *
 * @param logLevel - The verbosity you set for activity and error logging. Can
 *   be any of the following values:
 *
 *   <ul>
 *     <li>`debug` for the most verbose logging level, primarily for
 *     debugging.</li>
 *     <li>`error` to log errors only.</li>
 *     <li><code>`silent` to turn off logging.</li>
 *   </ul>
 */ function setLogLevel(e) {
    Se.setLogLevel(e);
}

function __PRIVATE_logDebug(e, ...t) {
    if (Se.logLevel <= logger.LogLevel.DEBUG) {
        const n = t.map(__PRIVATE_argToString);
        Se.debug(`Firestore (${ve}): ${e}`, ...n);
    }
}

function __PRIVATE_logError(e, ...t) {
    if (Se.logLevel <= logger.LogLevel.ERROR) {
        const n = t.map(__PRIVATE_argToString);
        Se.error(`Firestore (${ve}): ${e}`, ...n);
    }
}

/**
 * @internal
 */ function __PRIVATE_logWarn(e, ...t) {
    if (Se.logLevel <= logger.LogLevel.WARN) {
        const n = t.map(__PRIVATE_argToString);
        Se.warn(`Firestore (${ve}): ${e}`, ...n);
    }
}

/**
 * Converts an additional log parameter to a string representation.
 */ function __PRIVATE_argToString(e) {
    if ("string" == typeof e) return e;
    try {
        return function __PRIVATE_formatJSON(e) {
            return JSON.stringify(e);
        }(e);
    } catch (t) {
        // Converting to JSON failed, just log the object directly
        return e;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function l(e, t, n) {
    let r = "Unexpected state";
    "string" == typeof t ? r = t : n = t, __PRIVATE__fail(e, r, n);
}

function __PRIVATE__fail(e, t, n) {
    // Log the failure in addition to throw an exception, just in case the
    // exception is swallowed.
    let r = `FIRESTORE (${ve}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`;
    if (void 0 !== n) try {
        r += " CONTEXT: " + JSON.stringify(n);
    } catch (e) {
        r += " CONTEXT: " + n;
    }
    // NOTE: We don't use FirestoreError here because these are internal failures
    // that cannot be handled by the user. (Also it would create a circular
    // dependency between the error and assert modules which doesn't work.)
    throw __PRIVATE_logError(r), new Error(r);
}

function __PRIVATE_hardAssert(e, t, n, r) {
    let i = "Unexpected state";
    "string" == typeof n ? i = n : r = n, e || __PRIVATE__fail(t, i, r);
}

/**
 * Fails if the given assertion condition is false, throwing an Error with the
 * given message if it did.
 *
 * The code of callsites invoking this function are stripped out in production
 * builds. Any side-effects of code within the debugAssert() invocation will not
 * happen in this case.
 *
 * @internal
 */ function __PRIVATE_debugAssert(e, t) {
    e || l(57014, t);
}

/**
 * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
 * instance of `T` before casting.
 */ function __PRIVATE_debugCast(e, 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
t) {
    return e;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Generates `nBytes` of random bytes.
 *
 * If `nBytes < 0` , an error will be thrown.
 */ function __PRIVATE_randomBytes(e) {
    // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
    const t = 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(e);
    if (t && "function" == typeof t.getRandomValues) t.getRandomValues(n); else 
    // Falls back to Math.random
    for (let t = 0; t < e; t++) n[t] = Math.floor(256 * Math.random());
    return n;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A utility class for generating unique alphanumeric IDs of a specified length.
 *
 * @internal
 * Exported internally for testing purposes.
 */ class __PRIVATE_AutoId {
    static newId() {
        // Alphanumeric characters
        const e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", t = 62 * Math.floor(256 / 62);
        // The largest byte value that is a multiple of `char.length`.
                let n = "";
        for (;n.length < 20; ) {
            const r = __PRIVATE_randomBytes(40);
            for (let i = 0; i < r.length; ++i) 
            // Only accept values that are [0, maxMultiple), this ensures they can
            // be evenly mapped to indices of `chars` via a modulo operation.
            n.length < 20 && r[i] < t && (n += e.charAt(r[i] % 62));
        }
        return n;
    }
}

function __PRIVATE_primitiveComparator(e, t) {
    return e < t ? -1 : e > t ? 1 : 0;
}

/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(e, t) {
    // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and,
    // if found, use that character to determine the relative ordering of the two strings as a
    // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by
    // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8
    // and UTF-16 happen to represent Unicode code points.
    // After finding the first pair of differing characters, there are two cases:
    // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or
    // both are surrogates from a surrogate pair (that collectively represent code points greater
    // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the
    // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is
    // sufficient.
    // Case 2: One character is a surrogate and the other is not. In this case the surrogate-
    // containing string is always ordered after the non-surrogate. This is because surrogates are
    // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations
    // and are lexicographically greater than the 1, 2, or 3-byte representations of code points
    // less than or equal to 0xFFFF.
    // An example of why Case 2 is required is comparing the following two Unicode code points:
    // |-----------------------|------------|---------------------|-----------------|
    // | Name                  | Code Point | UTF-8 Encoding      | UTF-16 Encoding |
    // |-----------------------|------------|---------------------|-----------------|
    // | Replacement Character | U+FFFD     | 0xEF 0xBF 0xBD      | 0xFFFD          |
    // | Grinning Face         | U+1F600    | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00   |
    // |-----------------------|------------|---------------------|-----------------|
    // A lexicographical comparison of the UTF-8 encodings of these code points would order
    // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a
    // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously
    // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,
    // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate
    // pair with those that do not.
    const n = Math.min(e.length, t.length);
    for (let r = 0; r < n; r++) {
        const n = e.charAt(r), i = t.charAt(r);
        if (n !== i) return __PRIVATE_isSurrogate(n) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(n, i) : __PRIVATE_isSurrogate(n) ? 1 : -1;
    }
    // Use the lengths of the strings to determine the overall comparison result since either the
    // strings were equal or one is a prefix of the other.
        return __PRIVATE_primitiveComparator(e.length, t.length);
}

const De = 55296, xe = 57343;

function __PRIVATE_isSurrogate(e) {
    const t = e.charCodeAt(0);
    return t >= De && t <= xe;
}

/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(e, t, n) {
    return e.length === t.length && e.every(((e, r) => n(e, t[r])));
}

/**
 * Verifies equality for an optional value.
 */ function na(e, t, n) {
    return void 0 === e && void 0 === t || void 0 !== e && void 0 !== t && n(e, t);
}

/**
 * Returns the immediate lexicographically-following string. This is useful to
 * construct an inclusive range for indexeddb iterators.
 */ function __PRIVATE_immediateSuccessor(e) {
    // Return the input string, with an additional NUL byte appended.
    return e + "\0";
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// An immutable sorted map implementation, based on a Left-leaning Red-Black
// tree.
class SortedMap {
    constructor(e, t) {
        this.comparator = e, this.root = t || LLRBNode.EMPTY;
    }
    // Returns a copy of the map, with the specified key/value added or replaced.
    insert(e, t) {
        return new SortedMap(this.comparator, this.root.insert(e, t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));
    }
    // Returns a copy of the map, with the specified key removed.
    remove(e) {
        return new SortedMap(this.comparator, this.root.remove(e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));
    }
    // Returns the value of the node with the given key, or null.
    get(e) {
        let t = this.root;
        for (;!t.isEmpty(); ) {
            const n = this.comparator(e, t.key);
            if (0 === n) return t.value;
            n < 0 ? t = t.left : n > 0 && (t = t.right);
        }
        return null;
    }
    // Returns the index of the element in this sorted map, or -1 if it doesn't
    // exist.
    indexOf(e) {
        // Number of nodes that were pruned when descending right
        let t = 0, n = this.root;
        for (;!n.isEmpty(); ) {
            const r = this.comparator(e, n.key);
            if (0 === r) return t + n.left.size;
            r < 0 ? n = n.left : (
            // Count all nodes left of the node plus the node itself
            t += n.left.size + 1, n = n.right);
        }
        // Node not found
                return -1;
    }
    isEmpty() {
        return this.root.isEmpty();
    }
    // Returns the total number of nodes in the map.
    get size() {
        return this.root.size;
    }
    // Returns the minimum key in the map.
    minKey() {
        return this.root.minKey();
    }
    // Returns the maximum key in the map.
    maxKey() {
        return this.root.maxKey();
    }
    // Traverses the map in key order and calls the specified action function
    // for each key/value pair. If action returns true, traversal is aborted.
    // Returns the first truthy value returned by action, or the last falsey
    // value returned by action.
    inorderTraversal(e) {
        return this.root.inorderTraversal(e);
    }
    forEach(e) {
        this.inorderTraversal(((t, n) => (e(t, n), false)));
    }
    toString() {
        const e = [];
        return this.inorderTraversal(((t, n) => (e.push(`${t}:${n}`), false))), `{${e.join(", ")}}`;
    }
    // Traverses the map in reverse key order and calls the specified action
    // function for each key/value pair. If action returns true, traversal is
    // aborted.
    // Returns the first truthy value returned by action, or the last falsey
    // value returned by action.
    reverseTraversal(e) {
        return this.root.reverseTraversal(e);
    }
    // Returns an iterator over the SortedMap.
    getIterator() {
        return new SortedMapIterator(this.root, null, this.comparator, false);
    }
    getIteratorFrom(e) {
        return new SortedMapIterator(this.root, e, this.comparator, false);
    }
    getReverseIterator() {
        return new SortedMapIterator(this.root, null, this.comparator, true);
    }
    getReverseIteratorFrom(e) {
        return new SortedMapIterator(this.root, e, this.comparator, true);
    }
}

 // end SortedMap
// An iterator over an LLRBNode.
class SortedMapIterator {
    constructor(e, t, n, r) {
        this.isReverse = r, this.nodeStack = [];
        let i = 1;
        for (;!e.isEmpty(); ) if (i = t ? n(e.key, t) : 1, 
        // flip the comparison if we're going in reverse
        t && r && (i *= -1), i < 0) 
        // This node is less than our start key. ignore it
        e = this.isReverse ? e.left : e.right; else {
            if (0 === i) {
                // This node is exactly equal to our start key. Push it on the stack,
                // but stop iterating;
                this.nodeStack.push(e);
                break;
            }
            // This node is greater than our start key, add it to the stack and move
            // to the next one
            this.nodeStack.push(e), e = this.isReverse ? e.right : e.left;
        }
    }
    getNext() {
        let e = this.nodeStack.pop();
        const t = {
            key: e.key,
            value: e.value
        };
        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), 
        e = e.left;
        return t;
    }
    hasNext() {
        return this.nodeStack.length > 0;
    }
    peek() {
        if (0 === this.nodeStack.length) return null;
        const e = this.nodeStack[this.nodeStack.length - 1];
        return {
            key: e.key,
            value: e.value
        };
    }
}

 // end SortedMapIterator
// Represents a node in a Left-leaning Red-Black tree.
class LLRBNode {
    constructor(e, t, n, r, i) {
        this.key = e, this.value = t, this.color = null != n ? n : LLRBNode.RED, this.left = null != r ? r : LLRBNode.EMPTY, 
        this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size;
    }
    // Returns a copy of the current node, optionally replacing pieces of it.
    copy(e, t, n, r, i) {
        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);
    }
    isEmpty() {
        return false;
    }
    // Traverses the tree in key order and calls the specified action function
    // for each node. If action returns true, traversal is aborted.
    // Returns the first truthy value returned by action, or the last falsey
    // value returned by action.
    inorderTraversal(e) {
        return this.left.inorderTraversal(e) || e(this.key, this.value) || this.right.inorderTraversal(e);
    }
    // Traverses the tree in reverse key order and calls the specified action
    // function for each node. If action returns true, traversal is aborted.
    // Returns the first truthy value returned by action, or the last falsey
    // value returned by action.
    reverseTraversal(e) {
        return this.right.reverseTraversal(e) || e(this.key, this.value) || this.left.reverseTraversal(e);
    }
    // Returns the minimum node in the tree.
    min() {
        return this.left.isEmpty() ? this : this.left.min();
    }
    // Returns the maximum key in the tree.
    minKey() {
        return this.min().key;
    }
    // Returns the maximum key in the tree.
    maxKey() {
        return this.right.isEmpty() ? this.key : this.right.maxKey();
    }
    // Returns new tree, with the key/value added.
    insert(e, t, n) {
        let r = this;
        const i = n(e, r.key);
        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)), 
        r.fixUp();
    }
    removeMin() {
        if (this.left.isEmpty()) return LLRBNode.EMPTY;
        let e = this;
        return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), e = e.copy(null, null, null, e.left.removeMin(), null), 
        e.fixUp();
    }
    // Returns new tree, with the specified item removed.
    remove(e, t) {
        let n, r = this;
        if (t(e, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()), 
        r = r.copy(null, null, null, r.left.remove(e, t), null); else {
            if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()), 
            0 === t(e, r.key)) {
                if (r.right.isEmpty()) return LLRBNode.EMPTY;
                n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin());
            }
            r = r.copy(null, null, null, null, r.right.remove(e, t));
        }
        return r.fixUp();
    }
    isRed() {
        return this.color;
    }
    // Returns new tree after performing any needed rotations.
    fixUp() {
        let e = this;
        return e.right.isRed() && !e.left.isRed() && (e = e.rotateLeft()), e.left.isRed() && e.left.left.isRed() && (e = e.rotateRight()), 
        e.left.isRed() && e.right.isRed() && (e = e.colorFlip()), e;
    }
    moveRedLeft() {
        let e = this.colorFlip();
        return e.right.left.isRed() && (e = e.copy(null, null, null, null, e.right.rotateRight()), 
        e = e.rotateLeft(), e = e.colorFlip()), e;
    }
    moveRedRight() {
        let e = this.colorFlip();
        return e.left.left.isRed() && (e = e.rotateRight(), e = e.colorFlip()), e;
    }
    rotateLeft() {
        const e = this.copy(null, null, LLRBNode.RED, null, this.right.left);
        return this.right.copy(null, null, this.color, e, null);
    }
    rotateRight() {
        const e = this.copy(null, null, LLRBNode.RED, this.left.right, null);
        return this.left.copy(null, null, this.color, null, e);
    }
    colorFlip() {
        const e = this.left.copy(null, null, !this.left.color, null, null), t = this.right.copy(null, null, !this.right.color, null, null);
        return this.copy(null, null, !this.color, e, t);
    }
    // For testing.
    checkMaxDepth() {
        const e = this.check();
        return Math.pow(2, e) <= this.size + 1;
    }
    // In a balanced RB tree, the black-depth (number of black nodes) from root to
    // leaves is equal on both sides.  This function verifies that or asserts.
    check() {
        if (this.isRed() && this.left.isRed()) throw l(43730, {
            key: this.key,
            value: this.value
        });
        if (this.right.isRed()) throw l(14113, {
            key: this.key,
            value: this.value
        });
        const e = this.left.check();
        if (e !== this.right.check()) throw l(27949);
        return e + (this.isRed() ? 0 : 1);
    }
}

 // end LLRBNode
// Empty node is shared between all LLRB trees.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
LLRBNode.EMPTY = null, LLRBNode.RED = true, LLRBNode.BLACK = false;

// end LLRBEmptyNode
LLRBNode.EMPTY = new 
// Represents an empty node (a leaf node in the Red-Black Tree).
class LLRBEmptyNode {
    constructor() {
        this.size = 0;
    }
    get key() {
        throw l(57766);
    }
    get value() {
        throw l(16141);
    }
    get color() {
        throw l(16727);
    }
    get left() {
        throw l(29726);
    }
    get right() {
        throw l(36894);
    }
    // Returns a copy of the current node.
    copy(e, t, n, r, i) {
        return this;
    }
    // Returns a copy of the tree, with the specified key/value added.
    insert(e, t, n) {
        return new LLRBNode(e, t);
    }
    // Returns a copy of the tree, with the specified key removed.
    remove(e, t) {
        return this;
    }
    isEmpty() {
        return true;
    }
    inorderTraversal(e) {
        return false;
    }
    reverseTraversal(e) {
        return false;
    }
    minKey() {
        return null;
    }
    maxKey() {
        return null;
    }
    isRed() {
        return false;
    }
    // For testing.
    checkMaxDepth() {
        return true;
    }
    check() {
        return 0;
    }
};

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * SortedSet is an immutable (copy-on-write) collection that holds elements
 * in order specified by the provided comparator.
 *
 * NOTE: if provided comparator returns 0 for two elements, we consider them to
 * be equal!
 */
class SortedSet {
    constructor(e) {
        this.comparator = e, this.data = new SortedMap(this.comparator);
    }
    has(e) {
        return null !== this.data.get(e);
    }
    first() {
        return this.data.minKey();
    }
    last() {
        return this.data.maxKey();
    }
    get size() {
        return this.data.size;
    }
    indexOf(e) {
        return this.data.indexOf(e);
    }
    /** Iterates elements in order defined by "comparator" */    forEach(e) {
        this.data.inorderTraversal(((t, n) => (e(t), false)));
    }
    /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */    forEachInRange(e, t) {
        const n = this.data.getIteratorFrom(e[0]);
        for (;n.hasNext(); ) {
            const r = n.getNext();
            if (this.comparator(r.key, e[1]) >= 0) return;
            t(r.key);
        }
    }
    /**
     * Iterates over `elem`s such that: start &lt;= elem until false is returned.
     */    forEachWhile(e, t) {
        let n;
        for (n = void 0 !== t ? this.data.getIteratorFrom(t) : this.data.getIterator(); n.hasNext(); ) {
            if (!e(n.getNext().key)) return;
        }
    }
    /** Finds the least element greater than or equal to `elem`. */    firstAfterOrEqual(e) {
        const t = this.data.getIteratorFrom(e);
        return t.hasNext() ? t.getNext().key : null;
    }
    getIterator() {
        return new SortedSetIterator(this.data.getIterator());
    }
    getIteratorFrom(e) {
        return new SortedSetIterator(this.data.getIteratorFrom(e));
    }
    /** Inserts or updates an element */    add(e) {
        return this.copy(this.data.remove(e).insert(e, true));
    }
    /** Deletes an element */    delete(e) {
        return this.has(e) ? this.copy(this.data.remove(e)) : this;
    }
    isEmpty() {
        return this.data.isEmpty();
    }
    unionWith(e) {
        let t = this;
        // Make sure `result` always refers to the larger one of the two sets.
                return t.size < e.size && (t = e, e = this), e.forEach((e => {
            t = t.add(e);
        })), t;
    }
    isEqual(e) {
        if (!(e instanceof SortedSet)) return false;
        if (this.size !== e.size) return false;
        const t = this.data.getIterator(), n = e.data.getIterator();
        for (;t.hasNext(); ) {
            const e = t.getNext().key, r = n.getNext().key;
            if (0 !== this.comparator(e, r)) return false;
        }
        return true;
    }
    toArray() {
        const e = [];
        return this.forEach((t => {
            e.push(t);
        })), e;
    }
    toString() {
        const e = [];
        return this.forEach((t => e.push(t))), "SortedSet(" + e.toString() + ")";
    }
    copy(e) {
        const t = new SortedSet(this.comparator);
        return t.data = e, t;
    }
}

class SortedSetIterator {
    constructor(e) {
        this.iter = e;
    }
    getNext() {
        return this.iter.getNext().key;
    }
    hasNext() {
        return this.iter.hasNext();
    }
}

/**
 * Compares two sorted sets for equality using their natural ordering. The
 * method computes the intersection and invokes `onAdd` for every element that
 * is in `after` but not `before`. `onRemove` is invoked for every element in
 * `before` but missing from `after`.
 *
 * The method creates a copy of both `before` and `after` and runs in O(n log
 * n), where n is the size of the two lists.
 *
 * @param before - The elements that exist in the original set.
 * @param after - The elements to diff against the original set.
 * @param comparator - The comparator for the elements in before and after.
 * @param onAdd - A function to invoke for every element that is part of `
 * after` but not `before`.
 * @param onRemove - A function to invoke for every element that is part of
 * `before` but not `after`.
 */
/**
 * Returns the next element from the iterator or `undefined` if none available.
 */
function __PRIVATE_advanceIterator(e) {
    return e.hasNext() ? e.getNext() : void 0;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const aa = {
    // Causes are copied from:
    // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
    /** Not an error; returned on success. */
    OK: "ok",
    /** The operation was cancelled (typically by the caller). */
    CANCELLED: "cancelled",
    /** Unknown error or an error from a different error domain. */
    UNKNOWN: "unknown",
    /**
     * Client specified an invalid argument. Note that this differs from
     * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are
     * problematic regardless of the state of the system (e.g., a malformed file
     * name).
     */
    INVALID_ARGUMENT: "invalid-argument",
    /**
     * Deadline expired before operation could complete. For operations that
     * change the state of the system, this error may be returned even if the
     * operation has completed successfully. For example, a successful response
     * from a server could have been delayed long enough for the deadline to
     * expire.
     */
    DEADLINE_EXCEEDED: "deadline-exceeded",
    /** Some requested entity (e.g., file or directory) was not found. */
    NOT_FOUND: "not-found",
    /**
     * Some entity that we attempted to create (e.g., file or directory) already
     * exists.
     */
    ALREADY_EXISTS: "already-exists",
    /**
     * The caller does not have permission to execute the specified operation.
     * PERMISSION_DENIED must not be used for rejections caused by exhausting
     * some resource (use RESOURCE_EXHAUSTED instead for those errors).
     * PERMISSION_DENIED must not be used if the caller cannot be identified
     * (use UNAUTHENTICATED instead for those errors).
     */
    PERMISSION_DENIED: "permission-denied",
    /**
     * The request does not have valid authentication credentials for the
     * operation.
     */
    UNAUTHENTICATED: "unauthenticated",
    /**
     * Some resource has been exhausted, perhaps a per-user quota, or perhaps the
     * entire file system is out of space.
     */
    RESOURCE_EXHAUSTED: "resource-exhausted",
    /**
     * Operation was rejected because the system is not in a state required for
     * the operation's execution. For example, directory to be deleted may be
     * non-empty, an rmdir operation is applied to a non-directory, etc.
     *
     * A litmus test that may help a service implementor in deciding
     * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:
     *  (a) Use UNAVAILABLE if the client can retry just the failing call.
     *  (b) Use ABORTED if the client should retry at a higher-level
     *      (e.g., restarting a read-modify-write sequence).
     *  (c) Use FAILED_PRECONDITION if the client should not retry until
     *      the system state has been explicitly fixed. E.g., if an "rmdir"
     *      fails because the directory is non-empty, FAILED_PRECONDITION
     *      should be returned since the client should not retry unless
     *      they have first fixed up the directory by deleting files from it.
     *  (d) Use FAILED_PRECONDITION if the client performs conditional
     *      REST Get/Update/Delete on a resource and the resource on the
     *      server does not match the condition. E.g., conflicting
     *      read-modify-write on the same resource.
     */
    FAILED_PRECONDITION: "failed-precondition",
    /**
     * The operation was aborted, typically due to a concurrency issue like
     * sequencer check failures, transaction aborts, etc.
     *
     * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
     * and UNAVAILABLE.
     */
    ABORTED: "aborted",
    /**
     * Operation was attempted past the valid range. E.g., seeking or reading
     * past end of file.
     *
     * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed
     * if the system state changes. For example, a 32-bit file system will
     * generate INVALID_ARGUMENT if asked to read at an offset that is not in the
     * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from
     * an offset past the current file size.
     *
     * There is a fair bit of overlap between FAILED_PRECONDITION and
     * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)
     * when it applies so that callers who are iterating through a space can
     * easily look for an OUT_OF_RANGE error to detect when they are done.
     */
    OUT_OF_RANGE: "out-of-range",
    /** Operation is not implemented or not supported/enabled in this service. */
    UNIMPLEMENTED: "unimplemented",
    /**
     * Internal errors. Means some invariants expected by underlying System has
     * been broken. If you see one of these errors, Something is very broken.
     */
    INTERNAL: "internal",
    /**
     * The service is currently unavailable. This is a most likely a transient
     * condition and may be corrected by retrying with a backoff.
     *
     * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,
     * and UNAVAILABLE.
     */
    UNAVAILABLE: "unavailable",
    /** Unrecoverable data loss or corruption. */
    DATA_LOSS: "data-loss"
};

/** An error returned by a Firestore operation. */ class s extends util.FirebaseError {
    /** @hideconstructor */
    constructor(
    /**
     * The backend error code associated with this error.
     */
    e, 
    /**
     * A custom error description.
     */
    t) {
        super(e, t), this.code = e, this.message = t, 
        // HACK: We write a toString property directly because Error is not a real
        // class and so inheritance does not work correctly. We could alternatively
        // do the same "back-door inheritance" trick that FirebaseError does.
        this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const Ce = "__name__";

/**
 * Path represents an ordered sequence of string segments.
 */
class BasePath {
    constructor(e, t, n) {
        void 0 === t ? t = 0 : t > e.length && l(637, {
            offset: t,
            range: e.length
        }), void 0 === n ? n = e.length - t : n > e.length - t && l(1746, {
            length: n,
            range: e.length - t
        }), this.segments = e, this.offset = t, this.len = n;
    }
    get length() {
        return this.len;
    }
    isEqual(e) {
        return 0 === BasePath.comparator(this, e);
    }
    child(e) {
        const t = this.segments.slice(this.offset, this.limit());
        return e instanceof BasePath ? e.forEach((e => {
            t.push(e);
        })) : t.push(e), this.construct(t);
    }
    /** The index of one past the last segment of the path. */    limit() {
        return this.offset + this.length;
    }
    popFirst(e) {
        return e = void 0 === e ? 1 : e, this.construct(this.segments, this.offset + e, this.length - e);
    }
    popLast() {
        return this.construct(this.segments, this.offset, this.length - 1);
    }
    firstSegment() {
        return this.segments[this.offset];
    }
    lastSegment() {
        return this.get(this.length - 1);
    }
    get(e) {
        return this.segments[this.offset + e];
    }
    isEmpty() {
        return 0 === this.length;
    }
    isPrefixOf(e) {
        if (e.length < this.length) return false;
        for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return false;
        return true;
    }
    isImmediateParentOf(e) {
        if (this.length + 1 !== e.length) return false;
        for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return false;
        return true;
    }
    forEach(e) {
        for (let t = this.offset, n = this.limit(); t < n; t++) e(this.segments[t]);
    }
    toArray() {
        return this.segments.slice(this.offset, this.limit());
    }
    /**
     * Compare 2 paths segment by segment, prioritizing numeric IDs
     * (e.g., "__id123__") in numeric ascending order, followed by string
     * segments in lexicographical order.
     */    static comparator(e, t) {
        const n = Math.min(e.length, t.length);
        for (let r = 0; r < n; r++) {
            const n = BasePath.compareSegments(e.get(r), t.get(r));
            if (0 !== n) return n;
        }
        return __PRIVATE_primitiveComparator(e.length, t.length);
    }
    static compareSegments(e, t) {
        const n = BasePath.isNumericId(e), r = BasePath.isNumericId(t);
        return n && !r ? -1 : !n && r ? 1 : n && r ? BasePath.extractNumericId(e).compare(BasePath.extractNumericId(t)) : __PRIVATE_compareUtf8Strings(e, t);
    }
    // Checks if a segment is a numeric ID (starts with "__id" and ends with "__").
    static isNumericId(e) {
        return e.startsWith("__id") && e.endsWith("__");
    }
    static extractNumericId(e) {
        return bloomBlob.Integer.fromString(e.substring(4, e.length - 2));
    }
}

/**
 * A slash-separated path for navigating resources (documents and collections)
 * within Firestore.
 *
 * @internal
 */ class ResourcePath extends BasePath {
    construct(e, t, n) {
        return new ResourcePath(e, t, n);
    }
    canonicalString() {
        // NOTE: The client is ignorant of any path segments containing escape
        // sequences (e.g. __id123__) and just passes them through raw (they exist
        // for legacy reasons and should not be used frequently).
        return this.toArray().join("/");
    }
    toString() {
        return this.canonicalString();
    }
    toStringWithLeadingSlash() {
        return `/${this.canonicalString()}`;
    }
    /**
     * Returns a string representation of this path
     * where each path segment has been encoded with
     * `encodeURIComponent`.
     */    toUriEncodedString() {
        return this.toArray().map(encodeURIComponent).join("/");
    }
    /**
     * Creates a resource path from the given slash-delimited string. If multiple
     * arguments are provided, all components are combined. Leading and trailing
     * slashes from all components are ignored.
     */    static fromString(...e) {
        // NOTE: The client is ignorant of any path segments containing escape
        // sequences (e.g. __id123__) and just passes them through raw (they exist
        // for legacy reasons and should not be used frequently).
        const t = [];
        for (const n of e) {
            if (n.indexOf("//") >= 0) throw new s(aa.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);
            // Strip leading and trailing slashed.
                        t.push(...n.split("/").filter((e => e.length > 0)));
        }
        return new ResourcePath(t);
    }
    static emptyPath() {
        return new ResourcePath([]);
    }
}

const Fe = /^[_a-zA-Z][_a-zA-Z0-9]*$/;

/**
 * A dot-separated path for navigating sub-objects within a document.
 * @internal
 */ let Oe = class FieldPath extends BasePath {
    construct(e, t, n) {
        return new FieldPath(e, t, n);
    }
    /**
     * Returns true if the string could be used as a segment in a field path
     * without escaping.
     */    static isValidIdentifier(e) {
        return Fe.test(e);
    }
    canonicalString() {
        return this.toArray().map((e => (e = e.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), 
        FieldPath.isValidIdentifier(e) || (e = "`" + e + "`"), e))).join(".");
    }
    toString() {
        return this.canonicalString();
    }
    /**
     * Returns true if this field references the key of a document.
     */    isKeyField() {
        return 1 === this.length && this.get(0) === Ce;
    }
    /**
     * The field designating the key of a document.
     */    static keyField() {
        return new FieldPath([ Ce ]);
    }
    /**
     * Parses a field string from the given server-formatted string.
     *
     * - Splitting the empty string is not allowed (for now at least).
     * - Empty segments within the string (e.g. if there are two consecutive
     *   separators) are not allowed.
     *
     * TODO(b/37244157): we should make this more strict. Right now, it allows
     * non-identifier path components, even if they aren't escaped.
     */    static fromServerFormat(e) {
        const t = [];
        let n = "", r = 0;
        const __PRIVATE_addCurrentSegment = () => {
            if (0 === n.length) throw new s(aa.INVALID_ARGUMENT, `Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);
            t.push(n), n = "";
        };
        let i = false;
        for (;r < e.length; ) {
            const t = e[r];
            if ("\\" === t) {
                if (r + 1 === e.length) throw new s(aa.INVALID_ARGUMENT, "Path has trailing escape character: " + e);
                const t = e[r + 1];
                if ("\\" !== t && "." !== t && "`" !== t) throw new s(aa.INVALID_ARGUMENT, "Path has invalid escape sequence: " + e);
                n += t, r += 2;
            } else "`" === t ? (i = !i, r++) : "." !== t || i ? (n += t, r++) : (__PRIVATE_addCurrentSegment(), 
            r++);
        }
        if (__PRIVATE_addCurrentSegment(), i) throw new s(aa.INVALID_ARGUMENT, "Unterminated ` in path: " + e);
        return new FieldPath(t);
    }
    static emptyPath() {
        return new FieldPath([]);
    }
};

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Provides a set of fields that can be used to partially patch a document.
 * FieldMask is used in conjunction with ObjectValue.
 * Examples:
 *   foo - Overwrites foo entirely with the provided value. If foo is not
 *         present in the companion ObjectValue, the field is deleted.
 *   foo.bar - Overwrites only the field bar of the object foo.
 *             If foo is not an object, foo is replaced with an object
 *             containing foo
 */ class FieldMask {
    constructor(e) {
        this.fields = e, 
        // TODO(dimond): validation of FieldMask
        // Sort the field mask to support `FieldMask.isEqual()` and assert below.
        e.sort(Oe.comparator);
    }
    static empty() {
        return new FieldMask([]);
    }
    /**
     * Returns a new FieldMask object that is the result of adding all the given
     * fields paths to this field mask.
     */    unionWith(e) {
        let t = new SortedSet(Oe.comparator);
        for (const e of this.fields) t = t.add(e);
        for (const n of e) t = t.add(n);
        return new FieldMask(t.toArray());
    }
    /**
     * Verifies that `fieldPath` is included by at least one field in this field
     * mask.
     *
     * This is an O(n) operation, where `n` is the size of the field mask.
     */    covers(e) {
        for (const t of this.fields) if (t.isPrefixOf(e)) return true;
        return false;
    }
    isEqual(e) {
        return __PRIVATE_arrayEquals(this.fields, e.fields, ((e, t) => e.isEqual(t)));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function __PRIVATE_objectSize(e) {
    let t = 0;
    for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t++;
    return t;
}

function forEach(e, t) {
    for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t(n, e[n]);
}

function __PRIVATE_mapToArray(e, t) {
    const n = [];
    for (const r in e) Object.prototype.hasOwnProperty.call(e, r) && n.push(t(e[r], r, e));
    return n;
}

function isEmpty(e) {
    for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return false;
    return true;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @internal
 */ class DocumentKey {
    constructor(e) {
        this.path = e;
    }
    static fromPath(e) {
        return new DocumentKey(ResourcePath.fromString(e));
    }
    static fromName(e) {
        return new DocumentKey(ResourcePath.fromString(e).popFirst(5));
    }
    static empty() {
        return new DocumentKey(ResourcePath.emptyPath());
    }
    get collectionGroup() {
        return this.path.popLast().lastSegment();
    }
    /** Returns true if the document is in the specified collectionId. */    hasCollectionId(e) {
        return this.path.length >= 2 && this.path.get(this.path.length - 2) === e;
    }
    /** Returns the collection group (i.e. the name of the parent collection) for this key. */    getCollectionGroup() {
        return this.path.get(this.path.length - 2);
    }
    /** Returns the fully qualified path to the parent collection. */    getCollectionPath() {
        return this.path.popLast();
    }
    isEqual(e) {
        return null !== e && 0 === ResourcePath.comparator(this.path, e.path);
    }
    toString() {
        return this.path.toString();
    }
    static comparator(e, t) {
        return ResourcePath.comparator(e.path, t.path);
    }
    static isDocumentKey(e) {
        return e.length % 2 == 0;
    }
    /**
     * Creates and returns a new document key with the given segments.
     *
     * @param segments - The segments of the path to the document
     * @returns A new instance of DocumentKey
     */    static fromSegments(e) {
        return new DocumentKey(new ResourcePath(e.slice()));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function __PRIVATE_validateNonEmptyArgument(e, t, n) {
    if (!n) throw new s(aa.INVALID_ARGUMENT, `Function ${e}() cannot be called with an empty ${t}.`);
}

/**
 * Validates that two boolean options are not set at the same time.
 * @internal
 */ function __PRIVATE_validateIsNotUsedTogether(e, t, n, r) {
    if (true === t && true === r) throw new s(aa.INVALID_ARGUMENT, `${e} and ${n} cannot be used together.`);
}

/**
 * Validates that `path` refers to a document (indicated by the fact it contains
 * an even numbers of segments).
 */ function __PRIVATE_validateDocumentPath(e) {
    if (!DocumentKey.isDocumentKey(e)) throw new s(aa.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`);
}

/**
 * Validates that `path` refers to a collection (indicated by the fact it
 * contains an odd numbers of segments).
 */ function __PRIVATE_validateCollectionPath(e) {
    if (DocumentKey.isDocumentKey(e)) throw new s(aa.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`);
}

/**
 * Returns true if it's a non-null object without a custom prototype
 * (i.e. excludes Array, Date, etc.).
 */ function p(e) {
    return "object" == typeof e && null !== e && (Object.getPrototypeOf(e) === Object.prototype || null === Object.getPrototypeOf(e));
}

/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(e) {
    if (void 0 === e) return "undefined";
    if (null === e) return "null";
    if ("string" == typeof e) return e.length > 20 && (e = `${e.substring(0, 20)}...`), 
    JSON.stringify(e);
    if ("number" == typeof e || "boolean" == typeof e) return "" + e;
    if ("object" == typeof e) {
        if (e instanceof Array) return "an array";
        {
            const t = 
            /** try to get the constructor name for an object. */
            function __PRIVATE_tryGetCustomObjectType(e) {
                if (e.constructor) return e.constructor.name;
                return null;
            }
            /**
 * Casts `obj` to `T`, optionally unwrapping Compat types to expose the
 * underlying instance. Throws if  `obj` is not an instance of `T`.
 *
 * This cast is used in the Lite and Full SDK to verify instance types for
 * arguments passed to the public API.
 * @internal
 */ (e);
            return t ? `a custom ${t} object` : "an object";
        }
    }
    return "function" == typeof e ? "a function" : l(12329, {
        type: typeof e
    });
}

function ra(e, 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
t) {
    if ("_delegate" in e && (
    // Unwrap Compat types
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    e = e._delegate), !(e instanceof t)) {
        if (t.name === e.constructor.name) throw new s(aa.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
        {
            const n = __PRIVATE_valueDescription(e);
            throw new s(aa.INVALID_ARGUMENT, `Expected type '${t.name}', but it was: ${n}`);
        }
    }
    return e;
}

function __PRIVATE_validatePositiveNumber(e, t) {
    if (t <= 0) throw new s(aa.INVALID_ARGUMENT, `Function ${e}() requires a positive number, but it was: ${t}.`);
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Helper function to define a JSON schema {@link Property}.
 * @private
 * @internal
 */ function property(e, t) {
    const n = {
        typeString: e
    };
    return t && (n.value = t), n;
}

/**
 * Validates the JSON object based on the provided schema, and narrows the type to the provided
 * JSON schema.
 * @private
 * @internal
 *
 * @param json - A JSON object to validate.
 * @param scheme - a {@link JsonSchema} that defines the properties to validate.
 * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.
 */ function __PRIVATE_validateJSON(e, t) {
    if (!p(e)) throw new s(aa.INVALID_ARGUMENT, "JSON must be an object");
    let n;
    for (const r in t) if (t[r]) {
        const i = t[r].typeString, s = "value" in t[r] ? {
            value: t[r].value
        } : void 0;
        if (!(r in e)) {
            n = `JSON missing required field: '${r}'`;
            break;
        }
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const _ = e[r];
        if (i && typeof _ !== i) {
            n = `JSON field '${r}' must be a ${i}.`;
            break;
        }
        if (void 0 !== s && _ !== s.value) {
            n = `Expected '${r}' field to equal '${s.value}'`;
            break;
        }
    }
    if (n) throw new s(aa.INVALID_ARGUMENT, n);
    return true;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
const Me = -62135596800, Ne = 1e6;

// Number of nanoseconds in a millisecond.
/**
 * A `Timestamp` represents a point in time independent of any time zone or
 * calendar, represented as seconds and fractions of seconds at nanosecond
 * resolution in UTC Epoch time.
 *
 * It is encoded using the Proleptic Gregorian Calendar which extends the
 * Gregorian calendar backwards to year one. It is encoded assuming all minutes
 * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
 * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
 * 9999-12-31T23:59:59.999999999Z.
 *
 * For examples and further specifications, refer to the
 * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
 */
class Timestamp {
    /**
     * Creates a new timestamp with the current date, with millisecond precision.
     *
     * @returns a new timestamp representing the current date.
     */
    static now() {
        return Timestamp.fromMillis(Date.now());
    }
    /**
     * Creates a new timestamp from the given date.
     *
     * @param date - The date to initialize the `Timestamp` from.
     * @returns A new `Timestamp` representing the same point in time as the given
     *     date.
     */    static fromDate(e) {
        return Timestamp.fromMillis(e.getTime());
    }
    /**
     * Creates a new timestamp from the given number of milliseconds.
     *
     * @param milliseconds - Number of milliseconds since Unix epoch
     *     1970-01-01T00:00:00Z.
     * @returns A new `Timestamp` representing the same point in time as the given
     *     number of milliseconds.
     */    static fromMillis(e) {
        const t = Math.floor(e / 1e3), n = Math.floor((e - 1e3 * t) * Ne);
        return new Timestamp(t, n);
    }
    /**
     * Creates a new timestamp.
     *
     * @param seconds - The number of seconds of UTC time since Unix epoch
     *     1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
     *     9999-12-31T23:59:59Z inclusive.
     * @param nanoseconds - The non-negative fractions of a second at nanosecond
     *     resolution. Negative second values with fractions must still have
     *     non-negative nanoseconds values that count forward in time. Must be
     *     from 0 to 999,999,999 inclusive.
     */    constructor(
    /**
     * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
     */
    e, 
    /**
     * The fractions of a second at nanosecond resolution.*
     */
    t) {
        if (this.seconds = e, this.nanoseconds = t, t < 0) throw new s(aa.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t);
        if (t >= 1e9) throw new s(aa.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t);
        if (e < Me) throw new s(aa.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e);
        // This will break in the year 10,000.
                if (e >= 253402300800) throw new s(aa.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e);
    }
    /**
     * Converts a `Timestamp` to a JavaScript `Date` object. This conversion
     * causes a loss of precision since `Date` objects only support millisecond
     * precision.
     *
     * @returns JavaScript `Date` object representing the same point in time as
     *     this `Timestamp`, with millisecond precision.
     */    toDate() {
        return new Date(this.toMillis());
    }
    /**
     * Converts a `Timestamp` to a numeric timestamp (in milliseconds since
     * epoch). This operation causes a loss of precision.
     *
     * @returns The point in time corresponding to this timestamp, represented as
     *     the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
     */    toMillis() {
        return 1e3 * this.seconds + this.nanoseconds / Ne;
    }
    _compareTo(e) {
        return this.seconds === e.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e.seconds);
    }
    /**
     * Returns true if this `Timestamp` is equal to the provided one.
     *
     * @param other - The `Timestamp` to compare against.
     * @returns true if this `Timestamp` is equal to the provided one.
     */    isEqual(e) {
        return e.seconds === this.seconds && e.nanoseconds === this.nanoseconds;
    }
    /** Returns a textual representation of this `Timestamp`. */    toString() {
        return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
    }
    /**
     * Returns a JSON-serializable representation of this `Timestamp`.
     */    toJSON() {
        return {
            type: Timestamp._jsonSchemaVersion,
            seconds: this.seconds,
            nanoseconds: this.nanoseconds
        };
    }
    /**
     * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.
     */    static fromJSON(e) {
        if (__PRIVATE_validateJSON(e, Timestamp._jsonSchema)) return new Timestamp(e.seconds, e.nanoseconds);
    }
    /**
     * Converts this object to a primitive string, which allows `Timestamp` objects
     * to be compared using the `>`, `<=`, `>=` and `>` operators.
     */    valueOf() {
        // This method returns a string of the form <seconds>.<nanoseconds> where
        // <seconds> is translated to have a non-negative value and both <seconds>
        // and <nanoseconds> are left-padded with zeroes to be a consistent length.
        // Strings with this format then have a lexicographical ordering that matches
        // the expected ordering. The <seconds> translation is done to avoid having
        // a leading negative sign (i.e. a leading '-' character) in its string
        // representation, which would affect its lexicographical ordering.
        const e = this.seconds - Me;
        // Note: Up to 12 decimal digits are required to represent all valid
        // 'seconds' values.
                return String(e).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0");
    }
}

Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = {
    type: property("string", Timestamp._jsonSchemaVersion),
    seconds: property("number"),
    nanoseconds: property("number")
};

/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An error encountered while decoding base64 string.
 */
class __PRIVATE_Base64DecodeError extends Error {
    constructor() {
        super(...arguments), this.name = "Base64DecodeError";
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Converts a Base64 encoded string to a binary string. */
/** True if and only if the Base64 conversion functions are available. */
function __PRIVATE_isBase64Available() {
    return "undefined" != typeof atob;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Immutable class that represents a "proto" byte string.
 *
 * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when
 * sent on the wire. This class abstracts away this differentiation by holding
 * the proto byte string in a common class that must be converted into a string
 * before being sent as a proto.
 * @internal
 */ class ByteString {
    constructor(e) {
        this.binaryString = e;
    }
    static fromBase64String(e) {
        const t = function __PRIVATE_decodeBase64(e) {
            try {
                return atob(e);
            } catch (e) {
                // Check that `DOMException` is defined before using it to avoid
                // "ReferenceError: Property 'DOMException' doesn't exist" in react-native.
                // (https://github.com/firebase/firebase-js-sdk/issues/7115)
                throw "undefined" != typeof DOMException && e instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + e) : e;
            }
        }
        /** Converts a binary string to a Base64 encoded string. */ (e);
        return new ByteString(t);
    }
    static fromUint8Array(e) {
        // TODO(indexing); Remove the copy of the byte string here as this method
        // is frequently called during indexing.
        const t = 
        /**
 * Helper function to convert an Uint8array to a binary string.
 */
        function __PRIVATE_binaryStringFromUint8Array(e) {
            let t = "";
            for (let n = 0; n < e.length; ++n) t += String.fromCharCode(e[n]);
            return t;
        }
        /**
 * Helper function to convert a binary string to an Uint8Array.
 */ (e);
        return new ByteString(t);
    }
    [Symbol.iterator]() {
        let e = 0;
        return {
            next: () => e < this.binaryString.length ? {
                value: this.binaryString.charCodeAt(e++),
                done: false
            } : {
                value: void 0,
                done: true
            }
        };
    }
    toBase64() {
        return function __PRIVATE_encodeBase64(e) {
            return btoa(e);
        }(this.binaryString);
    }
    toUint8Array() {
        return function __PRIVATE_uint8ArrayFromBinaryString(e) {
            const t = new Uint8Array(e.length);
            for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n);
            return t;
        }
        /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
        // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
        (this.binaryString);
    }
    approximateByteSize() {
        return 2 * this.binaryString.length;
    }
    compareTo(e) {
        return __PRIVATE_primitiveComparator(this.binaryString, e.binaryString);
    }
    isEqual(e) {
        return this.binaryString === e.binaryString;
    }
}

ByteString.EMPTY_BYTE_STRING = new ByteString("");

const Le = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);

/**
 * Converts the possible Proto values for a timestamp value into a "seconds and
 * nanos" representation.
 */ function __PRIVATE_normalizeTimestamp(e) {
    // The json interface (for the browser) will return an iso timestamp string,
    // while the proto js library (for node) will return a
    // google.protobuf.Timestamp instance.
    if (__PRIVATE_hardAssert(!!e, 39018), "string" == typeof e) {
        // The date string can have higher precision (nanos) than the Date class
        // (millis), so we do some custom parsing here.
        // Parse the nanos right out of the string.
        let t = 0;
        const n = Le.exec(e);
        if (__PRIVATE_hardAssert(!!n, 46558, {
            timestamp: e
        }), n[1]) {
            // Pad the fraction out to 9 digits (nanos).
            let e = n[1];
            e = (e + "000000000").substr(0, 9), t = Number(e);
        }
        // Parse the date to get the seconds.
                const r = new Date(e);
        return {
            seconds: Math.floor(r.getTime() / 1e3),
            nanos: t
        };
    }
    return {
        seconds: __PRIVATE_normalizeNumber(e.seconds),
        nanos: __PRIVATE_normalizeNumber(e.nanos)
    };
}

/**
 * Converts the possible Proto types for numbers into a JavaScript number.
 * Returns 0 if the value is not numeric.
 */ function __PRIVATE_normalizeNumber(e) {
    // TODO(bjornick): Handle int64 greater than 53 bits.
    return "number" == typeof e ? e : "string" == typeof e ? Number(e) : 0;
}

/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(e) {
    return "string" == typeof e ? ByteString.fromBase64String(e) : ByteString.fromUint8Array(e);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents a locally-applied ServerTimestamp.
 *
 * Server Timestamps are backed by MapValues that contain an internal field
 * `__type__` with a value of `server_timestamp`. The previous value and local
 * write time are stored in its `__previous_value__` and `__local_write_time__`
 * fields respectively.
 *
 * Notes:
 * - ServerTimestampValue instances are created as the result of applying a
 *   transform. They can only exist in the local view of a document. Therefore
 *   they do not need to be parsed or serialized.
 * - When evaluated locally (e.g. for snapshot.data()), they by default
 *   evaluate to `null`. This behavior can be configured by passing custom
 *   FieldValueOptions to value().
 * - With respect to other ServerTimestampValues, they sort by their
 *   localWriteTime.
 */ const Be = "server_timestamp", Ue = "__type__", ke = "__previous_value__", qe = "__local_write_time__";

function __PRIVATE_isServerTimestamp(e) {
    const t = (e?.mapValue?.fields || {})[Ue]?.stringValue;
    return t === Be;
}

/**
 * Creates a new ServerTimestamp proto value (using the internal format).
 */
/**
 * Returns the value of the field before this ServerTimestamp was set.
 *
 * Preserving the previous values allows the user to display the last resoled
 * value until the backend responds with the timestamp.
 */
function __PRIVATE_getPreviousValue(e) {
    const t = e.mapValue.fields[ke];
    return __PRIVATE_isServerTimestamp(t) ? __PRIVATE_getPreviousValue(t) : t;
}

/**
 * Returns the local time at which this timestamp was first set.
 */ function __PRIVATE_getLocalWriteTime(e) {
    const t = __PRIVATE_normalizeTimestamp(e.mapValue.fields[qe].timestampValue);
    return new Timestamp(t.seconds, t.nanos);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class DatabaseInfo {
    /**
     * Constructs a DatabaseInfo using the provided host, databaseId and
     * persistenceKey.
     *
     * @param databaseId - The database to use.
     * @param appId - The Firebase App Id.
     * @param persistenceKey - A unique identifier for this Firestore's local
     * storage (used in conjunction with the databaseId).
     * @param host - The Firestore backend host to connect to.
     * @param ssl - Whether to use SSL when connecting.
     * @param forceLongPolling - Whether to use the forceLongPolling option
     * when using WebChannel as the network transport.
     * @param autoDetectLongPolling - Whether to use the detectBufferingProxy
     * option when using WebChannel as the network transport.
     * @param longPollingOptions - Options that configure long-polling.
     * @param useFetchStreams - Whether to use the Fetch API instead of
     * XMLHTTPRequest
     */
    constructor(e, t, n, r, i, s, _, o, a, u, c, l, E) {
        this.databaseId = e, this.appId = t, this.persistenceKey = n, this.host = r, this.ssl = i, 
        this.forceLongPolling = s, this.autoDetectLongPolling = _, this.longPollingOptions = o, 
        this.useFetchStreams = a, this.isUsingEmulator = u, this.apiKey = c, this._customHeaders = l, 
        this.grpcFlowControlWindow = E;
    }
}

/** The default database name for a project. */ const $e = "(default)";

/**
 * Represents the database ID a Firestore client is associated with.
 * @internal
 */ class DatabaseId {
    constructor(e, t) {
        this.projectId = e, this.database = t || $e;
    }
    static empty() {
        return new DatabaseId("", "");
    }
    get isDefaultDatabase() {
        return this.database === $e;
    }
    isEqual(e) {
        return e instanceof DatabaseId && e.projectId === this.projectId && e.database === this.database;
    }
}

function __PRIVATE_databaseIdFromApp(e, t) {
    if (!Object.prototype.hasOwnProperty.apply(e.options, [ "projectId" ])) throw new s(aa.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
    return new DatabaseId(e.options.projectId, t);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Sentinel value that sorts before any Mutation Batch ID. */ const Ke = -1;

/**
 * Returns whether a variable is either undefined or null.
 */ function __PRIVATE_isNullOrUndefined(e) {
    return null == e;
}

/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(e) {
    // Detect if the value is -0.0. Based on polyfill from
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
    return 0 === e && 1 / e == -1 / 0;
}

function __PRIVATE_isNumber$1(e) {
    return "number" == typeof e;
}

/**
 * Returns whether a value is an integer and in the safe integer range
 * @param value - The value to test for being an integer and in the safe range
 */ function isSafeInteger(e) {
    return "number" == typeof e && Number.isInteger(e) && !__PRIVATE_isNegativeZero(e) && e <= Number.MAX_SAFE_INTEGER && e >= Number.MIN_SAFE_INTEGER;
}

function __PRIVATE_isString$1(e) {
    return "string" == typeof e;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const We = "__type__", Qe = "__max__", Ge = {
    mapValue: {
        fields: {
            __type__: {
                stringValue: Qe
            }
        }
    }
}, ze = "__vector__", je = "value", He = {
    nullValue: "NULL_VALUE"
}, Je = {
    booleanValue: true
}, Ye = {
    booleanValue: false
};

/** Extracts the backend's type order for the provided value. */
function __PRIVATE_typeOrder(e) {
    return "nullValue" in e ? 0 /* TypeOrder.NullValue */ : "booleanValue" in e ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in e || "doubleValue" in e ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in e ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in e ? 5 /* TypeOrder.StringValue */ : "bytesValue" in e ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in e ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in e ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in e ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in e ? __PRIVATE_isServerTimestamp(e) ? 4 /* TypeOrder.ServerTimestampValue */ : __PRIVATE_isMaxValue(e) ? 9007199254740991 /* TypeOrder.MaxValue */ : __PRIVATE_isVectorValue(e) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : l(28295, {
        value: e
    });
}

/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals$1(e, t, n) {
    if (e === t) return true;
    const r = __PRIVATE_typeOrder(e);
    if (r !== __PRIVATE_typeOrder(t)) return false;
    switch (r) {
      case 0 /* TypeOrder.NullValue */ :
      case 9007199254740991 /* TypeOrder.MaxValue */ :
        return true;

      case 1 /* TypeOrder.BooleanValue */ :
        return e.booleanValue === t.booleanValue;

      case 4 /* TypeOrder.ServerTimestampValue */ :
        return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t));

      case 3 /* TypeOrder.TimestampValue */ :
        return function __PRIVATE_timestampEquals(e, t) {
            if ("string" == typeof e.timestampValue && "string" == typeof t.timestampValue && e.timestampValue.length === t.timestampValue.length) 
            // Use string equality for ISO 8601 timestamps
            return e.timestampValue === t.timestampValue;
            const n = __PRIVATE_normalizeTimestamp(e.timestampValue), r = __PRIVATE_normalizeTimestamp(t.timestampValue);
            return n.seconds === r.seconds && n.nanos === r.nanos;
        }(e, t);

      case 5 /* TypeOrder.StringValue */ :
        return e.stringValue === t.stringValue;

      case 6 /* TypeOrder.BlobValue */ :
        return function __PRIVATE_blobEquals(e, t) {
            return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(t.bytesValue));
        }(e, t);

      case 7 /* TypeOrder.RefValue */ :
        return e.referenceValue === t.referenceValue;

      case 8 /* TypeOrder.GeoPointValue */ :
        return function __PRIVATE_geoPointEquals(e, t) {
            return __PRIVATE_normalizeNumber(e.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t.geoPointValue.longitude);
        }(e, t);

      case 2 /* TypeOrder.NumberValue */ :
        return function __PRIVATE_numberEquals(e, t, n) {
            if ("integerValue" in e && "integerValue" in t) return __PRIVATE_normalizeNumber(e.integerValue) === __PRIVATE_normalizeNumber(t.integerValue);
            let r, i;
            if ("doubleValue" in e && "doubleValue" in t) r = __PRIVATE_normalizeNumber(e.doubleValue), 
            i = __PRIVATE_normalizeNumber(t.doubleValue); else {
                if (!n?.t) return false;
                r = __PRIVATE_normalizeNumber(e.integerValue ?? e.doubleValue), i = __PRIVATE_normalizeNumber(t.integerValue ?? t.doubleValue);
            }
            if (r === i) return !!n?.i || __PRIVATE_isNegativeZero(r) === __PRIVATE_isNegativeZero(i);
            return !!(void 0 === n || n.o) && (isNaN(r) && isNaN(i));
        }(e, t, n);

      case 9 /* TypeOrder.ArrayValue */ :
        return __PRIVATE_arrayEquals(e.arrayValue.values || [], t.arrayValue.values || [], ((e, t) => __PRIVATE_valueEquals$1(e, t, n)));

      case 10 /* TypeOrder.VectorValue */ :
      case 11 /* TypeOrder.ObjectValue */ :
        return function __PRIVATE_objectEquals(e, t, n) {
            const r = e.mapValue.fields || {}, i = t.mapValue.fields || {};
            if (__PRIVATE_objectSize(r) !== __PRIVATE_objectSize(i)) return false;
            for (const e in r) if (r.hasOwnProperty(e) && (void 0 === i[e] || !__PRIVATE_valueEquals$1(r[e], i[e], n))) return false;
            return true;
        }
        /** Returns true if the ArrayValue contains the specified element. */ (e, t, n);

      default:
        return l(52216, {
            left: e
        });
    }
}

function __PRIVATE_arrayValueContains(e, t) {
    return void 0 !== (e.values || []).find((e => __PRIVATE_valueEquals$1(e, t)));
}

function __PRIVATE_valueCompare(e, t) {
    if (e === t) return 0;
    const n = __PRIVATE_typeOrder(e), r = __PRIVATE_typeOrder(t);
    if (n !== r) return __PRIVATE_primitiveComparator(n, r);
    switch (n) {
      case 0 /* TypeOrder.NullValue */ :
      case 9007199254740991 /* TypeOrder.MaxValue */ :
        return 0;

      case 1 /* TypeOrder.BooleanValue */ :
        return __PRIVATE_primitiveComparator(e.booleanValue, t.booleanValue);

      case 2 /* TypeOrder.NumberValue */ :
        return function __PRIVATE_compareNumbers(e, t) {
            const n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue), r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue);
            return n < r ? -1 : n > r ? 1 : n === r ? 0 : 
            // one or both are NaN.
            isNaN(n) ? isNaN(r) ? 0 : -1 : 1;
        }(e, t);

      case 3 /* TypeOrder.TimestampValue */ :
        return __PRIVATE_compareTimestamps(e.timestampValue, t.timestampValue);

      case 4 /* TypeOrder.ServerTimestampValue */ :
        return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e), __PRIVATE_getLocalWriteTime(t));

      case 5 /* TypeOrder.StringValue */ :
        return __PRIVATE_compareUtf8Strings(e.stringValue, t.stringValue);

      case 6 /* TypeOrder.BlobValue */ :
        return function __PRIVATE_compareBlobs(e, t) {
            const n = __PRIVATE_normalizeByteString(e), r = __PRIVATE_normalizeByteString(t);
            return n.compareTo(r);
        }(e.bytesValue, t.bytesValue);

      case 7 /* TypeOrder.RefValue */ :
        return function __PRIVATE_compareReferences(e, t) {
            const n = e.split("/"), r = t.split("/");
            for (let e = 0; e < n.length && e < r.length; e++) {
                const t = __PRIVATE_primitiveComparator(n[e], r[e]);
                if (0 !== t) return t;
            }
            return __PRIVATE_primitiveComparator(n.length, r.length);
        }(e.referenceValue, t.referenceValue);

      case 8 /* TypeOrder.GeoPointValue */ :
        return function __PRIVATE_compareGeoPoints(e, t) {
            const n = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(t.latitude));
            if (0 !== n) return n;
            return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude), __PRIVATE_normalizeNumber(t.longitude));
        }(e.geoPointValue, t.geoPointValue);

      case 9 /* TypeOrder.ArrayValue */ :
        return __PRIVATE_compareArrays(e.arrayValue, t.arrayValue);

      case 10 /* TypeOrder.VectorValue */ :
        return function __PRIVATE_compareVectors(e, t) {
            const n = e.fields || {}, r = t.fields || {}, i = n[je]?.arrayValue, s = r[je]?.arrayValue, _ = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0);
            if (0 !== _) return _;
            return __PRIVATE_compareArrays(i, s);
        }(e.mapValue, t.mapValue);

      case 11 /* TypeOrder.ObjectValue */ :
        return function __PRIVATE_compareMaps(e, t) {
            if (e === Ge.mapValue && t === Ge.mapValue) return 0;
            if (e === Ge.mapValue) return 1;
            if (t === Ge.mapValue) return -1;
            const n = e.fields || {}, r = Object.keys(n), i = t.fields || {}, s = Object.keys(i);
            // Even though MapValues are likely sorted correctly based on their insertion
            // order (e.g. when received from the backend), local modifications can bring
            // elements out of order. We need to re-sort the elements to ensure that
            // canonical IDs are independent of insertion order.
            r.sort(), s.sort();
            for (let e = 0; e < r.length && e < s.length; ++e) {
                const t = __PRIVATE_compareUtf8Strings(r[e], s[e]);
                if (0 !== t) return t;
                const _ = __PRIVATE_valueCompare(n[r[e]], i[s[e]]);
                if (0 !== _) return _;
            }
            return __PRIVATE_primitiveComparator(r.length, s.length);
        }
        /**
 * Generates the canonical ID for the provided field value (as used in Target
 * serialization).
 */ (e.mapValue, t.mapValue);

      default:
        throw l(23264, {
            u: n
        });
    }
}

function __PRIVATE_compareTimestamps(e, t) {
    if ("string" == typeof e && "string" == typeof t && e.length === t.length) return __PRIVATE_primitiveComparator(e, t);
    const n = __PRIVATE_normalizeTimestamp(e), r = __PRIVATE_normalizeTimestamp(t), i = __PRIVATE_primitiveComparator(n.seconds, r.seconds);
    return 0 !== i ? i : __PRIVATE_primitiveComparator(n.nanos, r.nanos);
}

function __PRIVATE_compareArrays(e, t) {
    const n = e.values || [], r = t.values || [];
    for (let e = 0; e < n.length && e < r.length; ++e) {
        const t = __PRIVATE_valueCompare(n[e], r[e]);
        if (void 0 !== t && 0 !== t) return t;
    }
    return __PRIVATE_primitiveComparator(n.length, r.length);
}

function canonicalId(e) {
    return __PRIVATE_canonifyValue(e);
}

function __PRIVATE_canonifyValue(e) {
    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) {
        const t = __PRIVATE_normalizeTimestamp(e);
        return `time(${t.seconds},${t.nanos})`;
    }(e.timestampValue) : "stringValue" in e ? e.stringValue : "bytesValue" in e ? function __PRIVATE_canonifyByteString(e) {
        return __PRIVATE_normalizeByteString(e).toBase64();
    }(e.bytesValue) : "referenceValue" in e ? function __PRIVATE_canonifyReference(e) {
        return DocumentKey.fromName(e).toString();
    }(e.referenceValue) : "geoPointValue" in e ? function __PRIVATE_canonifyGeoPoint(e) {
        return `geo(${e.latitude},${e.longitude})`;
    }(e.geoPointValue) : "arrayValue" in e ? function __PRIVATE_canonifyArray(e) {
        let t = "[", n = true;
        for (const r of e.values || []) n ? n = false : t += ",", t += __PRIVATE_canonifyValue(r);
        return t + "]";
    }
    /**
 * Returns an approximate (and wildly inaccurate) in-memory size for the field
 * value.
 *
 * The memory size takes into account only the actual user data as it resides
 * in memory and ignores object overhead.
 */ (e.arrayValue) : "mapValue" in e ? function __PRIVATE_canonifyMap(e) {
        // Iteration order in JavaScript is not guaranteed. To ensure that we generate
        // matching canonical IDs for identical maps, we need to sort the keys.
        const t = Object.keys(e.fields || {}).sort();
        let n = "{", r = true;
        for (const i of t) r ? r = false : n += ",", n += `${i}:${__PRIVATE_canonifyValue(e.fields[i])}`;
        return n + "}";
    }(e.mapValue) : l(61005, {
        value: e
    });
}

function __PRIVATE_estimateByteSize(e) {
    switch (__PRIVATE_typeOrder(e)) {
      case 0 /* TypeOrder.NullValue */ :
      case 1 /* TypeOrder.BooleanValue */ :
        return 4;

      case 2 /* TypeOrder.NumberValue */ :
        return 8;

      case 3 /* TypeOrder.TimestampValue */ :
      case 8 /* TypeOrder.GeoPointValue */ :
        // GeoPoints are made up of two distinct numbers (latitude + longitude)
        return 16;

      case 4 /* TypeOrder.ServerTimestampValue */ :
        const t = __PRIVATE_getPreviousValue(e);
        return t ? 16 + __PRIVATE_estimateByteSize(t) : 16;

      case 5 /* TypeOrder.StringValue */ :
        // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures:
        // "JavaScript's String type is [...] a set of elements of 16-bit unsigned
        // integer values"
        return 2 * e.stringValue.length;

      case 6 /* TypeOrder.BlobValue */ :
        return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize();

      case 7 /* TypeOrder.RefValue */ :
        return e.referenceValue.length;

      case 9 /* TypeOrder.ArrayValue */ :
        return function __PRIVATE_estimateArrayByteSize(e) {
            return (e.values || []).reduce(((e, t) => e + __PRIVATE_estimateByteSize(t)), 0);
        }
        /** Returns a reference value for the provided database and key. */ (e.arrayValue);

      case 10 /* TypeOrder.VectorValue */ :
      case 11 /* TypeOrder.ObjectValue */ :
        return function __PRIVATE_estimateMapByteSize(e) {
            let t = 0;
            return forEach(e.fields, ((e, n) => {
                t += e.length + __PRIVATE_estimateByteSize(n);
            })), t;
        }(e.mapValue);

      default:
        throw l(13486, {
            value: e
        });
    }
}

function __PRIVATE_refValue(e, t) {
    return {
        referenceValue: `projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}`
    };
}

/** Returns true if `value` is an BooleanValue . */
/** Returns true if `value` is an IntegerValue . */
function isInteger(e) {
    return !!e && "integerValue" in e;
}

/** Returns true if `value` is a DoubleValue. */ function __PRIVATE_isDouble(e) {
    return !!e && "doubleValue" in e;
}

/** Returns true if `value` is either an IntegerValue or a DoubleValue. */ function R(e) {
    return isInteger(e) || __PRIVATE_isDouble(e);
}

/** Returns true if `value` is an ArrayValue. */ function isArray(e) {
    return !!e && "arrayValue" in e;
}

/** Returns true if `value` is an ArrayValue. */
/** Returns true if `value` is a NullValue. */
function __PRIVATE_isNullValue(e) {
    return !!e && "nullValue" in e;
}

/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(e) {
    return !!e && "doubleValue" in e && isNaN(Number(e.doubleValue));
}

/** Returns true if `value` is Timestamp. */
/** Returns true if `value` is a MapValue. */
function __PRIVATE_isMapValue(e) {
    return !!e && "mapValue" in e;
}

/** Returns true if `value` is a VetorValue. */ function __PRIVATE_isVectorValue(e) {
    const t = (e?.mapValue?.fields || {})[We]?.stringValue;
    return t === ze;
}

/** Returns true if `value` is a VetorValue. */ function __PRIVATE_getVectorValue(e) {
    return (e?.mapValue?.fields || {})[je]?.arrayValue;
}

/** Creates a deep copy of `source`. */ function __PRIVATE_deepClone(e) {
    if (e.geoPointValue) return {
        geoPointValue: {
            ...e.geoPointValue
        }
    };
    if (e.timestampValue && "object" == typeof e.timestampValue) return {
        timestampValue: {
            ...e.timestampValue
        }
    };
    if (e.mapValue) {
        const t = {
            mapValue: {
                fields: {}
            }
        };
        return forEach(e.mapValue.fields, ((e, n) => t.mapValue.fields[e] = __PRIVATE_deepClone(n))), 
        t;
    }
    if (e.arrayValue) {
        const t = {
            arrayValue: {
                values: []
            }
        };
        for (let n = 0; n < (e.arrayValue.values || []).length; ++n) t.arrayValue.values[n] = __PRIVATE_deepClone(e.arrayValue.values[n]);
        return t;
    }
    return {
        ...e
    };
}

/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function __PRIVATE_isMaxValue(e) {
    return (((e.mapValue || {}).fields || {}).__type__ || {}).stringValue === Qe;
}

const Ze = {
    mapValue: {
        fields: {
            [We]: {
                stringValue: ze
            },
            [je]: {
                arrayValue: {}
            }
        }
    }
};

/** Returns the lowest value for the given value type (inclusive). */ function __PRIVATE_valuesGetLowerBound(e) {
    return "nullValue" in e ? He : "booleanValue" in e ? {
        booleanValue: false
    } : "integerValue" in e || "doubleValue" in e ? {
        doubleValue: NaN
    } : "timestampValue" in e ? {
        timestampValue: {
            seconds: Number.MIN_SAFE_INTEGER
        }
    } : "stringValue" in e ? {
        stringValue: ""
    } : "bytesValue" in e ? {
        bytesValue: ""
    } : "referenceValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "geoPointValue" in e ? {
        geoPointValue: {
            latitude: -90,
            longitude: -180
        }
    } : "arrayValue" in e ? {
        arrayValue: {}
    } : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? Ze : {
        mapValue: {}
    } : l(35942, {
        value: e
    });
}

/** Returns the largest value for the given value type (exclusive). */ function __PRIVATE_valuesGetUpperBound(e) {
    return "nullValue" in e ? {
        booleanValue: false
    } : "booleanValue" in e ? {
        doubleValue: NaN
    } : "integerValue" in e || "doubleValue" in e ? {
        timestampValue: {
            seconds: Number.MIN_SAFE_INTEGER
        }
    } : "timestampValue" in e ? {
        stringValue: ""
    } : "stringValue" in e ? {
        bytesValue: ""
    } : "bytesValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "referenceValue" in e ? {
        geoPointValue: {
            latitude: -90,
            longitude: -180
        }
    } : "geoPointValue" in e ? {
        arrayValue: {}
    } : "arrayValue" in e ? Ze : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? {
        mapValue: {}
    } : Ge : l(61959, {
        value: e
    });
}

function __PRIVATE_lowerBoundCompare(e, t) {
    const n = __PRIVATE_valueCompare(e.value, t.value);
    return 0 !== n ? n : e.inclusive && !t.inclusive ? -1 : !e.inclusive && t.inclusive ? 1 : 0;
}

function __PRIVATE_upperBoundCompare(e, t) {
    const n = __PRIVATE_valueCompare(e.value, t.value);
    return 0 !== n ? n : e.inclusive && !t.inclusive ? 1 : !e.inclusive && t.inclusive ? -1 : 0;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An ObjectValue represents a MapValue in the Firestore Proto and offers the
 * ability to add and remove fields (via the ObjectValueBuilder).
 */ class ObjectValue {
    constructor(e) {
        this.value = e;
    }
    static empty() {
        return new ObjectValue({
            mapValue: {}
        });
    }
    /**
     * Returns the value at the given path or null.
     *
     * @param path - the path to search
     * @returns The value at the path or null if the path is not set.
     */    field(e) {
        if (e.isEmpty()) return this.value;
        {
            let t = this.value;
            for (let n = 0; n < e.length - 1; ++n) if (t = (t.mapValue.fields || {})[e.get(n)], 
            !__PRIVATE_isMapValue(t)) return null;
            return t = (t.mapValue.fields || {})[e.lastSegment()], t || null;
        }
    }
    /**
     * Sets the field to the provided value.
     *
     * @param path - The field path to set.
     * @param value - The value to set.
     */    set(e, t) {
        this.getFieldsMap(e.popLast())[e.lastSegment()] = __PRIVATE_deepClone(t);
    }
    /**
     * Sets the provided fields to the provided values.
     *
     * @param data - A map of fields to values (or null for deletes).
     */    setAll(e) {
        let t = Oe.emptyPath(), n = {}, r = [];
        e.forEach(((e, i) => {
            if (!t.isImmediateParentOf(i)) {
                // Insert the accumulated changes at this parent location
                const e = this.getFieldsMap(t);
                this.applyChanges(e, n, r), n = {}, r = [], t = i.popLast();
            }
            e ? n[i.lastSegment()] = __PRIVATE_deepClone(e) : r.push(i.lastSegment());
        }));
        const i = this.getFieldsMap(t);
        this.applyChanges(i, n, r);
    }
    /**
     * Removes the field at the specified path. If there is no field at the
     * specified path, nothing is changed.
     *
     * @param path - The field path to remove.
     */    delete(e) {
        const t = this.field(e.popLast());
        __PRIVATE_isMapValue(t) && t.mapValue.fields && delete t.mapValue.fields[e.lastSegment()];
    }
    isEqual(e) {
        return __PRIVATE_valueEquals$1(this.value, e.value);
    }
    /**
     * Returns the map that contains the leaf element of `path`. If the parent
     * entry does not yet exist, or if it is not a map, a new map will be created.
     */    getFieldsMap(e) {
        let t = this.value;
        t.mapValue.fields || (t.mapValue = {
            fields: {}
        });
        for (let n = 0; n < e.length; ++n) {
            let r = t.mapValue.fields[e.get(n)];
            __PRIVATE_isMapValue(r) && r.mapValue.fields || (r = {
                mapValue: {
                    fields: {}
                }
            }, t.mapValue.fields[e.get(n)] = r), t = r;
        }
        return t.mapValue.fields;
    }
    /**
     * Modifies `fieldsMap` by adding, replacing or deleting the specified
     * entries.
     */    applyChanges(e, t, n) {
        forEach(t, ((t, n) => e[t] = n));
        for (const t of n) delete e[t];
    }
    clone() {
        return new ObjectValue(__PRIVATE_deepClone(this.value));
    }
}

/**
 * Returns a FieldMask built from all fields in a MapValue.
 */ function __PRIVATE_extractFieldMask(e) {
    const t = [];
    return forEach(e.fields, ((e, n) => {
        const r = new Oe([ e ]);
        if (__PRIVATE_isMapValue(n)) {
            const e = __PRIVATE_extractFieldMask(n.mapValue).fields;
            if (0 === e.length) 
            // Preserve the empty map by adding it to the FieldMask.
            t.push(r); else 
            // For nested and non-empty ObjectValues, add the FieldPath of the
            // leaf nodes.
            for (const n of e) t.push(r.child(n));
        } else 
        // For nested and non-empty ObjectValues, add the FieldPath of the leaf
        // nodes.
        t.push(r);
    })), new FieldMask(t);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Returns an DoubleValue for `value` that is encoded based the serializer's
 * `useProto3Json` setting.
 */ function __PRIVATE_toDouble(e, t) {
    if (e.useProto3Json) {
        if (isNaN(t)) return {
            doubleValue: "NaN"
        };
        if (t === 1 / 0) return {
            doubleValue: "Infinity"
        };
        if (t === -1 / 0) return {
            doubleValue: "-Infinity"
        };
    }
    return {
        doubleValue: __PRIVATE_isNegativeZero(t) ? "-0" : t
    };
}

/**
 * Returns an IntegerValue for `value`.
 */ function __PRIVATE_toInteger(e) {
    return {
        integerValue: "" + e
    };
}

/**
 * Returns a value for a number that's appropriate to put into a proto.
 * The return value is an IntegerValue if it can safely represent the value,
 * otherwise a DoubleValue is returned.
 */ function toNumber(e, t, n) {
    return isSafeInteger(t) ? __PRIVATE_toInteger(t) : __PRIVATE_toDouble(e, t);
}

/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Used to represent a field transform on a mutation. */ class TransformOperation {
    constructor() {
        // Make sure that the structural type of `TransformOperation` is unique.
        // See https://github.com/microsoft/TypeScript/issues/5451
        this._ = void 0;
    }
}

/**
 * Computes the local transform result against the provided `previousValue`,
 * optionally using the provided localWriteTime.
 */ function __PRIVATE_applyTransformOperationToLocalView(e, t, n) {
    return e instanceof __PRIVATE_ServerTimestampTransform ? function serverTimestamp$1(e, t) {
        const n = {
            fields: {
                [Ue]: {
                    stringValue: Be
                },
                [qe]: {
                    timestampValue: {
                        seconds: e.seconds,
                        nanos: e.nanoseconds
                    }
                }
            }
        };
        // We should avoid storing deeply nested server timestamp map values
        // because we never use the intermediate "previous values".
        // For example:
        // previous: 42L, add: t1, result: t1 -> 42L
        // previous: t1,  add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L)
        // previous: t2,  add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L)
        // `getPreviousValue` recursively traverses server timestamps to find the
        // least recent Value.
                return t && __PRIVATE_isServerTimestamp(t) && (t = __PRIVATE_getPreviousValue(t)), 
        t && (n.fields[ke] = t), {
            mapValue: n
        };
    }(n, t) : e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : e instanceof __PRIVATE_NumericIncrementTransformOperation ? function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e, t) {
        // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit
        // precision and resolves overflows by reducing precision, we do not
        // manually cap overflows at 2^63.
        const n = __PRIVATE_computeTransformOperationBaseValue(e, t), r = asNumber(n) + asNumber(e.l);
        return isInteger(n) && isInteger(e.l) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e.serializer, r);
    }(e, t) : e instanceof __PRIVATE_NumericMinimumTransformOperation ? function __PRIVATE_applyNumericMinimumTransformOperationToLocalView(e, t) {
        return __PRIVATE_applyNumericTransformOperationToLocalView(e, t, Math.min);
    }(e, t) : e instanceof __PRIVATE_NumericMaximumTransformOperation ? function __PRIVATE_applyNumericMaximumTransformOperationToLocalView(e, t) {
        return __PRIVATE_applyNumericTransformOperationToLocalView(e, t, Math.max);
    }(e, t) : void 0;
}

/**
 * Computes a final transform result after the transform has been acknowledged
 * by the server, potentially using the server-provided transformResult.
 */ function __PRIVATE_applyTransformOperationToRemoteDocument(e, t, n) {
    // The server just sends null as the transform result for array operations,
    // so we have to calculate a result the same as we do for local
    // applications.
    return e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : n;
}

/**
 * If this transform operation is not idempotent, returns the base value to
 * persist for this transform. If a base value is returned, the transform
 * operation is always applied to this base value, even if document has
 * already been updated.
 *
 * Base values provide consistent behavior for non-idempotent transforms and
 * allow us to return the same latency-compensated value even if the backend
 * has already applied the transform operation. The base value is null for
 * idempotent transforms, as they can be re-played even if the backend has
 * already applied them.
 *
 * @returns a base value to store along with the mutation, or null for
 * idempotent transforms.
 */ function __PRIVATE_computeTransformOperationBaseValue(e, t) {
    return e instanceof __PRIVATE_NumericIncrementTransformOperation ? R(t) ? t : {
        integerValue: 0
    } : null;
}

/** Transforms a value into a server-generated timestamp. */
class __PRIVATE_ServerTimestampTransform extends TransformOperation {}

/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation {
    constructor(e) {
        super(), this.elements = e;
    }
}

function __PRIVATE_applyArrayUnionTransformOperation(e, t) {
    const n = __PRIVATE_coercedFieldValuesArray(t);
    for (const t of e.elements) n.some((e => __PRIVATE_valueEquals$1(e, t))) || n.push(t);
    return {
        arrayValue: {
            values: n
        }
    };
}

/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation {
    constructor(e) {
        super(), this.elements = e;
    }
}

function __PRIVATE_applyArrayRemoveTransformOperation(e, t) {
    let n = __PRIVATE_coercedFieldValuesArray(t);
    for (const t of e.elements) n = n.filter((e => !__PRIVATE_valueEquals$1(e, t)));
    return {
        arrayValue: {
            values: n
        }
    };
}

/**
 * Implements the backend semantics for locally computed NUMERIC_ADD (increment)
 * transforms. Converts all field values to integers or doubles, but unlike the
 * backend does not cap integer values at 2^63. Instead, JavaScript number
 * arithmetic is used and precision loss can occur for values greater than 2^53.
 */ class __PRIVATE_NumericTransformOperation extends TransformOperation {
    constructor(e, t) {
        super(), this.serializer = e, this.l = t;
    }
}

class __PRIVATE_NumericIncrementTransformOperation extends __PRIVATE_NumericTransformOperation {}

class __PRIVATE_NumericMinimumTransformOperation extends __PRIVATE_NumericTransformOperation {}

class __PRIVATE_NumericMaximumTransformOperation extends __PRIVATE_NumericTransformOperation {}

function __PRIVATE_applyNumericTransformOperationToLocalView(e, t, n) {
    if (!R(t)) return e.l;
    const r = n(asNumber(t), asNumber(e.l));
    return isInteger(t) && isInteger(e.l) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e.serializer, r);
}

function asNumber(e) {
    return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);
}

function __PRIVATE_coercedFieldValuesArray(e) {
    return isArray(e) && e.arrayValue.values ? e.arrayValue.values.slice() : [];
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** A field path and the TransformOperation to perform upon it. */ class FieldTransform {
    constructor(e, t) {
        this.field = e, this.transform = t;
    }
}

function __PRIVATE_fieldTransformEquals(e, t) {
    return e.field.isEqual(t.field) && function __PRIVATE_transformOperationEquals(e, t) {
        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$1) : e instanceof __PRIVATE_NumericIncrementTransformOperation && t instanceof __PRIVATE_NumericIncrementTransformOperation || e instanceof __PRIVATE_NumericMinimumTransformOperation && t instanceof __PRIVATE_NumericMinimumTransformOperation || e instanceof __PRIVATE_NumericMaximumTransformOperation && t instanceof __PRIVATE_NumericMaximumTransformOperation ? __PRIVATE_valueEquals$1(e.l, t.l) : e instanceof __PRIVATE_ServerTimestampTransform && t instanceof __PRIVATE_ServerTimestampTransform;
    }(e.transform, t.transform);
}

/** The result of successfully applying a mutation to the backend. */
class MutationResult {
    constructor(
    /**
     * The version at which the mutation was committed:
     *
     * - For most operations, this is the updateTime in the WriteResult.
     * - For deletes, the commitTime of the WriteResponse (because deletes are
     *   not stored and have no updateTime).
     *
     * Note that these versions can be different: No-op writes will not change
     * the updateTime even though the commitTime advances.
     */
    e, 
    /**
     * The resulting fields returned from the backend after a mutation
     * containing field transforms has been committed. Contains one FieldValue
     * for each FieldTransform that was in the mutation.
     *
     * Will be empty if the mutation did not contain any field transforms.
     */
    t) {
        this.version = e, this.transformResults = t;
    }
}

/**
 * Encodes a precondition for a mutation. This follows the model that the
 * backend accepts with the special case of an explicit "empty" precondition
 * (meaning no precondition).
 */ class Precondition {
    constructor(e, t) {
        this.updateTime = e, this.exists = t;
    }
    /** Creates a new empty Precondition. */    static none() {
        return new Precondition;
    }
    /** Creates a new Precondition with an exists flag. */    static exists(e) {
        return new Precondition(void 0, e);
    }
    /** Creates a new Precondition based on a version a document exists at. */    static updateTime(e) {
        return new Precondition(e);
    }
    /** Returns whether this Precondition is empty. */    get isNone() {
        return void 0 === this.updateTime && void 0 === this.exists;
    }
    isEqual(e) {
        return this.exists === e.exists && (this.updateTime ? !!e.updateTime && this.updateTime.isEqual(e.updateTime) : !e.updateTime);
    }
}

/** Returns true if the preconditions is valid for the given document. */ function __PRIVATE_preconditionIsValidForDocument(e, t) {
    return void 0 !== e.updateTime ? t.isFoundDocument() && t.version.isEqual(e.updateTime) : void 0 === e.exists || e.exists === t.isFoundDocument();
}

/**
 * A mutation describes a self-contained change to a document. Mutations can
 * create, replace, delete, and update subsets of documents.
 *
 * Mutations not only act on the value of the document but also its version.
 *
 * For local mutations (mutations that haven't been committed yet), we preserve
 * the existing version for Set and Patch mutations. For Delete mutations, we
 * reset the version to 0.
 *
 * Here's the expected transition table.
 *
 * MUTATION           APPLIED TO            RESULTS IN
 *
 * SetMutation        Document(v3)          Document(v3)
 * SetMutation        NoDocument(v3)        Document(v0)
 * SetMutation        InvalidDocument(v0)   Document(v0)
 * PatchMutation      Document(v3)          Document(v3)
 * PatchMutation      NoDocument(v3)        NoDocument(v3)
 * PatchMutation      InvalidDocument(v0)   UnknownDocument(v3)
 * DeleteMutation     Document(v3)          NoDocument(v0)
 * DeleteMutation     NoDocument(v3)        NoDocument(v0)
 * DeleteMutation     InvalidDocument(v0)   NoDocument(v0)
 *
 * For acknowledged mutations, we use the updateTime of the WriteResponse as
 * the resulting version for Set and Patch mutations. As deletes have no
 * explicit update time, we use the commitTime of the WriteResponse for
 * Delete mutations.
 *
 * If a mutation is acknowledged by the backend but fails the precondition check
 * locally, we transition to an `UnknownDocument` and rely on Watch to send us
 * the updated version.
 *
 * Field transforms are used only with Patch and Set Mutations. We use the
 * `updateTransforms` message to store transforms, rather than the `transforms`s
 * messages.
 *
 * ## Subclassing Notes
 *
 * Every type of mutation needs to implement its own applyToRemoteDocument() and
 * applyToLocalView() to implement the actual behavior of applying the mutation
 * to some source document (see `setMutationApplyToRemoteDocument()` for an
 * example).
 */ class Mutation {}

/**
 * A utility method to calculate a `Mutation` representing the overlay from the
 * final state of the document, and a `FieldMask` representing the fields that
 * are mutated by the local mutations.
 */ function __PRIVATE_calculateOverlayMutation(e, t) {
    if (!e.hasLocalMutations || t && 0 === t.fields.length) return null;
    // mask is null when sets or deletes are applied to the current document.
        if (null === t) return e.isNoDocument() ? new __PRIVATE_DeleteMutation(e.key, Precondition.none()) : new __PRIVATE_SetMutation(e.key, e.data, Precondition.none());
    {
        const n = e.data, r = ObjectValue.empty();
        let i = new SortedSet(Oe.comparator);
        for (let e of t.fields) if (!i.has(e)) {
            let t = n.field(e);
            // If we are deleting a nested field, we take the immediate parent as
            // the mask used to construct the resulting mutation.
            // Justification: Nested fields can create parent fields implicitly. If
            // only a leaf entry is deleted in later mutations, the parent field
            // should still remain, but we may have lost this information.
            // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).
            // This leaves the final result (foo, {}). Despite the fact that `doc`
            // has the correct result, `foo` is not in `mask`, and the resulting
            // mutation would miss `foo`.
                        null === t && e.length > 1 && (e = e.popLast(), t = n.field(e)), null === t ? r.delete(e) : r.set(e, t), 
            i = i.add(e);
        }
        return new __PRIVATE_PatchMutation(e.key, r, new FieldMask(i.toArray()), Precondition.none());
    }
}

/**
 * Applies this mutation to the given document for the purposes of computing a
 * new remote document. If the input document doesn't match the expected state
 * (e.g. it is invalid or outdated), the document type may transition to
 * unknown.
 *
 * @param mutation - The mutation to apply.
 * @param document - The document to mutate. The input document can be an
 *     invalid document if the client has no knowledge of the pre-mutation state
 *     of the document.
 * @param mutationResult - The result of applying the mutation from the backend.
 */ function __PRIVATE_mutationApplyToRemoteDocument(e, t, n) {
    e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToRemoteDocument(e, t, n) {
        // Unlike setMutationApplyToLocalView, if we're applying a mutation to a
        // remote document the server has accepted the mutation so the precondition
        // must have held.
        const r = e.value.clone(), i = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults);
        r.setAll(i), t.convertToFoundDocument(n.version, r).setHasCommittedMutations();
    }(e, t, n) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToRemoteDocument(e, t, n) {
        if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) 
        // Since the mutation was not rejected, we know that the precondition
        // matched on the backend. We therefore must not have the expected version
        // of the document in our cache and convert to an UnknownDocument with a
        // known updateTime.
        return void t.convertToUnknownDocument(n.version);
        const r = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults), i = t.data;
        i.setAll(__PRIVATE_getPatch(e)), i.setAll(r), t.convertToFoundDocument(n.version, i).setHasCommittedMutations();
    }(e, t, n) : function __PRIVATE_deleteMutationApplyToRemoteDocument(e, t, n) {
        // Unlike applyToLocalView, if we're applying a mutation to a remote
        // document the server has accepted the mutation so the precondition must
        // have held.
        t.convertToNoDocument(n.version).setHasCommittedMutations();
    }(0, t, n);
}

/**
 * Applies this mutation to the given document for the purposes of computing
 * the new local view of a document. If the input document doesn't match the
 * expected state, the document is not modified.
 *
 * @param mutation - The mutation to apply.
 * @param document - The document to mutate. The input document can be an
 *     invalid document if the client has no knowledge of the pre-mutation state
 *     of the document.
 * @param previousMask - The fields that have been updated before applying this mutation.
 * @param localWriteTime - A timestamp indicating the local write time of the
 *     batch this mutation is a part of.
 * @returns A `FieldMask` representing the fields that are changed by applying this mutation.
 */ function __PRIVATE_mutationApplyToLocalView(e, t, n, r) {
    return e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToLocalView(e, t, n, r) {
        if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) 
        // The mutation failed to apply (e.g. a document ID created with add()
        // caused a name collision).
        return n;
        const i = e.value.clone(), s = __PRIVATE_localTransformResults(e.fieldTransforms, r, t);
        return i.setAll(s), t.convertToFoundDocument(t.version, i).setHasLocalMutations(), 
        null;
 // SetMutation overwrites all fields.
        }
    /**
 * A mutation that modifies fields of the document at the given key with the
 * given values. The values are applied through a field mask:
 *
 *  * When a field is in both the mask and the values, the corresponding field
 *    is updated.
 *  * When a field is in neither the mask nor the values, the corresponding
 *    field is unmodified.
 *  * When a field is in the mask but not in the values, the corresponding field
 *    is deleted.
 *  * When a field is not in the mask but is in the values, the values map is
 *    ignored.
 */ (e, t, n, r) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToLocalView(e, t, n, r) {
        if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return n;
        const i = __PRIVATE_localTransformResults(e.fieldTransforms, r, t), s = t.data;
        if (s.setAll(__PRIVATE_getPatch(e)), s.setAll(i), t.convertToFoundDocument(t.version, s).setHasLocalMutations(), 
        null === n) return null;
        return n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e => e.field)));
    }
    /**
 * Returns a FieldPath/Value map with the content of the PatchMutation.
 */ (e, t, n, r) : function __PRIVATE_deleteMutationApplyToLocalView(e, t, n) {
        if (__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return t.convertToNoDocument(t.version).setHasLocalMutations(), 
        null;
        return n;
    }
    /**
 * A mutation that verifies the existence of the document at the given key with
 * the provided precondition.
 *
 * The `verify` operation is only used in Transactions, and this class serves
 * primarily to facilitate serialization into protos.
 */ (e, t, n);
}

/**
 * If this mutation is not idempotent, returns the base value to persist with
 * this mutation. If a base value is returned, the mutation is always applied
 * to this base value, even if document has already been updated.
 *
 * The base value is a sparse object that consists of only the document
 * fields for which this mutation contains a non-idempotent transformation
 * (e.g. a numeric increment). The provided value guarantees consistent
 * behavior for non-idempotent transforms and allow us to return the same
 * latency-compensated value even if the backend has already applied the
 * mutation. The base value is null for idempotent mutations, as they can be
 * re-played even if the backend has already applied them.
 *
 * @returns a base value to store along with the mutation, or null for
 * idempotent mutations.
 */ function __PRIVATE_mutationExtractBaseValue(e, t) {
    let n = null;
    for (const r of e.fieldTransforms) {
        const e = t.data.field(r.field), i = __PRIVATE_computeTransformOperationBaseValue(r.transform, e || null);
        null != i && (null === n && (n = ObjectValue.empty()), n.set(r.field, i));
    }
    return n || null;
}

function __PRIVATE_mutationEquals(e, t) {
    return e.type === t.type && (!!e.key.isEqual(t.key) && (!!e.precondition.isEqual(t.precondition) && (!!function __PRIVATE_fieldTransformsAreEqual(e, t) {
        return void 0 === e && void 0 === t || !(!e || !t) && __PRIVATE_arrayEquals(e, t, ((e, t) => __PRIVATE_fieldTransformEquals(e, t)));
    }(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)))));
}

/**
 * A mutation that creates or replaces the document at the given key with the
 * object value contents.
 */ class __PRIVATE_SetMutation extends Mutation {
    constructor(e, t, n, r = []) {
        super(), this.key = e, this.value = t, this.precondition = n, this.fieldTransforms = r, 
        this.type = 0 /* MutationType.Set */;
    }
    getFieldMask() {
        return null;
    }
}

class __PRIVATE_PatchMutation extends Mutation {
    constructor(e, t, n, r, i = []) {
        super(), this.key = e, this.data = t, this.fieldMask = n, this.precondition = r, 
        this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;
    }
    getFieldMask() {
        return this.fieldMask;
    }
}

function __PRIVATE_getPatch(e) {
    const t = new Map;
    return e.fieldMask.fields.forEach((n => {
        if (!n.isEmpty()) {
            const r = e.data.field(n);
            t.set(n, r);
        }
    })), t;
}

/**
 * Creates a list of "transform results" (a transform result is a field value
 * representing the result of applying a transform) for use after a mutation
 * containing transforms has been acknowledged by the server.
 *
 * @param fieldTransforms - The field transforms to apply the result to.
 * @param mutableDocument - The current state of the document after applying all
 * previous mutations.
 * @param serverTransformResults - The transform results received by the server.
 * @returns The transform results list.
 */ function __PRIVATE_serverTransformResults(e, t, n) {
    const r = new Map;
    __PRIVATE_hardAssert(e.length === n.length, 32656, {
        h: n.length,
        T: e.length
    });
    for (let i = 0; i < n.length; i++) {
        const s = e[i], _ = s.transform, o = t.data.field(s.field);
        r.set(s.field, __PRIVATE_applyTransformOperationToRemoteDocument(_, o, n[i]));
    }
    return r;
}

/**
 * Creates a list of "transform results" (a transform result is a field value
 * representing the result of applying a transform) for use when applying a
 * transform locally.
 *
 * @param fieldTransforms - The field transforms to apply the result to.
 * @param localWriteTime - The local time of the mutation (used to
 *     generate ServerTimestampValues).
 * @param mutableDocument - The document to apply transforms on.
 * @returns The transform results list.
 */ function __PRIVATE_localTransformResults(e, t, n) {
    const r = new Map;
    for (const i of e) {
        const e = i.transform, s = n.data.field(i.field);
        r.set(i.field, __PRIVATE_applyTransformOperationToLocalView(e, s, t));
    }
    return r;
}

/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation {
    constructor(e, t) {
        super(), this.key = e, this.precondition = t, this.type = 2 /* MutationType.Delete */ , 
        this.fieldTransforms = [];
    }
    getFieldMask() {
        return null;
    }
}

class __PRIVATE_VerifyMutation extends Mutation {
    constructor(e, t) {
        super(), this.key = e, this.precondition = t, this.type = 3 /* MutationType.Verify */ , 
        this.fieldTransforms = [];
    }
    getFieldMask() {
        return null;
    }
}

/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Concrete implementation of the Aggregate type.
 */ class __PRIVATE_AggregateImpl {
    constructor(e, t, n) {
        this.alias = e, this.aggregateType = t, this.fieldPath = n;
    }
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents a bound of a query.
 *
 * The bound is specified with the given components representing a position and
 * whether it's just before or just after the position (relative to whatever the
 * query order is).
 *
 * The position represents a logical index position for a query. It's a prefix
 * of values for the (potentially implicit) order by clauses of a query.
 *
 * Bound provides a function to determine whether a document comes before or
 * after a bound. This is influenced by whether the position is just before or
 * just after the provided values.
 */ class Bound {
    constructor(e, t) {
        this.position = e, this.inclusive = t;
    }
}

function __PRIVATE_boundCompareToDocument(e, t, n) {
    let r = 0;
    for (let i = 0; i < e.position.length; i++) {
        const s = t[i], _ = e.position[i];
        if (s.field.isKeyField()) r = DocumentKey.comparator(DocumentKey.fromName(_.referenceValue), n.key); else {
            r = __PRIVATE_valueCompare(_, n.data.field(s.field));
        }
        if ("desc" /* Direction.DESCENDING */ === s.dir && (r *= -1), 0 !== r) break;
    }
    return r;
}

/**
 * Returns true if a document sorts after a bound using the provided sort
 * order.
 */ function __PRIVATE_boundEquals(e, t) {
    if (null === e) return null === t;
    if (null === t) return false;
    if (e.inclusive !== t.inclusive || e.position.length !== t.position.length) return false;
    for (let n = 0; n < e.position.length; n++) {
        if (!__PRIVATE_valueEquals$1(e.position[n], t.position[n])) return false;
    }
    return true;
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class Filter {}

class FieldFilter extends Filter {
    constructor(e, t, n) {
        super(), this.field = e, this.op = t, this.value = n;
    }
    /**
     * Creates a filter based on the provided arguments.
     */    static create(e, t, 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);
    }
    static createKeyFieldInFilter(e, t, n) {
        return "in" /* Operator.IN */ === t ? new __PRIVATE_KeyFieldInFilter(e, n) : new __PRIVATE_KeyFieldNotInFilter(e, n);
    }
    matches(e) {
        const t = e.data.field(this.field);
        // Types do not have to match in NOT_EQUAL filters.
                return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== t && void 0 === t.nullValue && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)) : null !== t && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t) && this.matchesComparison(__PRIVATE_valueCompare(t, this.value));
        // Only compare types with matching backend order (such as double and int).
        }
    matchesComparison(e) {
        switch (this.op) {
          case "<" /* Operator.LESS_THAN */ :
            return e < 0;

          case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
            return e <= 0;

          case "==" /* Operator.EQUAL */ :
            return 0 === e;

          case "!=" /* Operator.NOT_EQUAL */ :
            return 0 !== e;

          case ">" /* Operator.GREATER_THAN */ :
            return e > 0;

          case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
            return e >= 0;

          default:
            return l(47266, {
                operator: this.op
            });
        }
    }
    isInequality() {
        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;
    }
    getFlattenedFilters() {
        return [ this ];
    }
    getFilters() {
        return [ this ];
    }
}

class CompositeFilter extends Filter {
    constructor(e, t) {
        super(), this.filters = e, this.op = t, this.P = null;
    }
    /**
     * Creates a filter based on the provided arguments.
     */    static create(e, t) {
        return new CompositeFilter(e, t);
    }
    matches(e) {
        return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t => !t.matches(e))) : void 0 !== this.filters.find((t => t.matches(e)));
    }
    getFlattenedFilters() {
        return null !== this.P || (this.P = this.filters.reduce(((e, t) => e.concat(t.getFlattenedFilters())), [])), 
        this.P;
    }
    // Returns a mutable copy of `this.filters`
    getFilters() {
        return Object.assign([], this.filters);
    }
}

function __PRIVATE_compositeFilterIsConjunction(e) {
    return "and" /* CompositeOperator.AND */ === e.op;
}

function __PRIVATE_compositeFilterIsDisjunction(e) {
    return "or" /* CompositeOperator.OR */ === e.op;
}

/**
 * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.
 */ function __PRIVATE_compositeFilterIsFlatConjunction(e) {
    return __PRIVATE_compositeFilterIsFlat(e) && __PRIVATE_compositeFilterIsConjunction(e);
}

/**
 * Returns true if this filter does not contain any composite filters. Returns false otherwise.
 */ function __PRIVATE_compositeFilterIsFlat(e) {
    for (const t of e.filters) if (t instanceof CompositeFilter) return false;
    return true;
}

function __PRIVATE_canonifyFilter(e) {
    if (e instanceof FieldFilter) 
    // TODO(b/29183165): Technically, this won't be unique if two values have
    // the same description, such as the int 3 and the string "3". So we should
    // add the types in here somehow, too.
    return e.field.canonicalString() + e.op.toString() + canonicalId(e.value);
    if (__PRIVATE_compositeFilterIsFlatConjunction(e)) 
    // Older SDK versions use an implicit AND operation between their filters.
    // In the new SDK versions, the developer may use an explicit AND filter.
    // To stay consistent with the old usages, we add a special case to ensure
    // the canonical ID for these two are the same. For example:
    // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same
    // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`.
    return e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(",");
    {
        // filter instanceof CompositeFilter
        const t = e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(",");
        return `${e.op}(${t})`;
    }
}

function __PRIVATE_filterEquals(e, t) {
    return e instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(e, t) {
        return t instanceof FieldFilter && e.op === t.op && e.field.isEqual(t.field) && __PRIVATE_valueEquals$1(e.value, t.value);
    }(e, t) : e instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(e, t) {
        if (t instanceof CompositeFilter && e.op === t.op && e.filters.length === t.filters.length) {
            return e.filters.reduce(((e, n, r) => e && __PRIVATE_filterEquals(n, t.filters[r])), true);
        }
        return false;
    }
    /**
 * Returns a new composite filter that contains all filter from
 * `compositeFilter` plus all the given filters in `otherFilters`.
 */ (e, t) : void l(19439);
}

function __PRIVATE_compositeFilterWithAddedFilters(e, t) {
    const n = e.filters.concat(t);
    return CompositeFilter.create(n, e.op);
}

/** Returns a debug description for `filter`. */ function __PRIVATE_stringifyFilter(e) {
    return e instanceof FieldFilter ? function __PRIVATE_stringifyFieldFilter(e) {
        return `${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`;
    }
    /** Filter that matches on key fields (i.e. '__name__'). */ (e) : e instanceof CompositeFilter ? function __PRIVATE_stringifyCompositeFilter(e) {
        return e.op.toString() + " {" + e.getFilters().map(__PRIVATE_stringifyFilter).join(" ,") + "}";
    }(e) : "Filter";
}

class __PRIVATE_KeyFieldFilter extends FieldFilter {
    constructor(e, t, n) {
        super(e, t, n), this.key = DocumentKey.fromName(n.referenceValue);
    }
    matches(e) {
        const t = DocumentKey.comparator(e.key, this.key);
        return this.matchesComparison(t);
    }
}

/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter {
    constructor(e, t) {
        super(e, "in" /* Operator.IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , t);
    }
    matches(e) {
        return this.keys.some((t => t.isEqual(e.key)));
    }
}

/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter {
    constructor(e, t) {
        super(e, "not-in" /* Operator.NOT_IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , t);
    }
    matches(e) {
        return !this.keys.some((t => t.isEqual(e.key)));
    }
}

function __PRIVATE_extractDocumentKeysFromArrayValue(e, t) {
    return (t.arrayValue?.values || []).map((e => DocumentKey.fromName(e.referenceValue)));
}

/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter {
    constructor(e, t) {
        super(e, "array-contains" /* Operator.ARRAY_CONTAINS */ , t);
    }
    matches(e) {
        const t = e.data.field(this.field);
        return isArray(t) && __PRIVATE_arrayValueContains(t.arrayValue, this.value);
    }
}

/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter {
    constructor(e, t) {
        super(e, "in" /* Operator.IN */ , t);
    }
    matches(e) {
        const t = e.data.field(this.field);
        return null !== t && __PRIVATE_arrayValueContains(this.value.arrayValue, t);
    }
}

/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter {
    constructor(e, t) {
        super(e, "not-in" /* Operator.NOT_IN */ , t);
    }
    matches(e) {
        if (__PRIVATE_arrayValueContains(this.value.arrayValue, {
            nullValue: "NULL_VALUE"
        })) return false;
        const t = e.data.field(this.field);
        return null !== t && void 0 === t.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, t);
    }
}

/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter {
    constructor(e, t) {
        super(e, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , t);
    }
    matches(e) {
        const t = e.data.field(this.field);
        return !(!isArray(t) || !t.arrayValue.values) && t.arrayValue.values.some((e => __PRIVATE_arrayValueContains(this.value.arrayValue, e)));
    }
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
 */ class OrderBy {
    constructor(e, t = "asc" /* Direction.ASCENDING */) {
        this.field = e, this.dir = t;
    }
}

function __PRIVATE_orderByEquals(e, t) {
    return e.dir === t.dir && e.field.isEqual(t.field);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A version of a document in Firestore. This corresponds to the version
 * timestamp, such as update_time or read_time.
 */ class SnapshotVersion {
    static fromTimestamp(e) {
        return new SnapshotVersion(e);
    }
    static min() {
        return new SnapshotVersion(new Timestamp(0, 0));
    }
    static max() {
        return new SnapshotVersion(new Timestamp(253402300799, 999999999));
    }
    constructor(e) {
        this.timestamp = e;
    }
    compareTo(e) {
        return this.timestamp._compareTo(e.timestamp);
    }
    isEqual(e) {
        return this.timestamp.isEqual(e.timestamp);
    }
    /** Returns a number representation of the version for use in spec tests. */    toMicroseconds() {
        // Convert to microseconds.
        return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
    }
    toString() {
        return "SnapshotVersion(" + this.timestamp.toString() + ")";
    }
    toTimestamp() {
        return this.timestamp;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents a document in Firestore with a key, version, data and whether it
 * has local mutations applied to it.
 *
 * Documents can transition between states via `convertToFoundDocument()`,
 * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does
 * not transition to one of these states even after all mutations have been
 * applied, `isValidDocument()` returns false and the document should be removed
 * from all views.
 */ class MutableDocument {
    constructor(e, t, n, r, i, s, _) {
        this.key = e, this.documentType = t, this.version = n, this.readTime = r, this.createTime = i, 
        this.data = s, this.documentState = _;
    }
    /**
     * Creates a document with no known version or data, but which can serve as
     * base document for mutations.
     */    static newInvalidDocument(e) {
        return new MutableDocument(e, 0 /* DocumentType.INVALID */ , 
        /* version */ SnapshotVersion.min(), 
        /* readTime */ SnapshotVersion.min(), 
        /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);
    }
    /**
     * Creates a new document that is known to exist with the given data at the
     * given version.
     */    static newFoundDocument(e, t, n, r) {
        return new MutableDocument(e, 1 /* DocumentType.FOUND_DOCUMENT */ , 
        /* version */ t, 
        /* readTime */ SnapshotVersion.min(), 
        /* createTime */ n, r, 0 /* DocumentState.SYNCED */);
    }
    /** Creates a new document that is known to not exist at the given version. */    static newNoDocument(e, t) {
        return new MutableDocument(e, 2 /* DocumentType.NO_DOCUMENT */ , 
        /* version */ t, 
        /* readTime */ SnapshotVersion.min(), 
        /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */);
    }
    /**
     * Creates a new document that is known to exist at the given version but
     * whose data is not known (e.g. a document that was updated without a known
     * base document).
     */    static newUnknownDocument(e, t) {
        return new MutableDocument(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , 
        /* version */ t, 
        /* readTime */ SnapshotVersion.min(), 
        /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);
    }
    /**
     * Changes the document type to indicate that it exists and that its version
     * and data are known.
     */    convertToFoundDocument(e, t) {
        // If a document is switching state from being an invalid or deleted
        // document to a valid (FOUND_DOCUMENT) document, either due to receiving an
        // update from Watch or due to applying a local set mutation on top
        // of a deleted document, our best guess about its createTime would be the
        // version at which the document transitioned to a FOUND_DOCUMENT.
        return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = e), 
        this.version = e, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = t, 
        this.documentState = 0 /* DocumentState.SYNCED */ , this;
    }
    /**
     * Changes the document type to indicate that it doesn't exist at the given
     * version.
     */    convertToNoDocument(e) {
        return this.version = e, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , 
        this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , 
        this;
    }
    /**
     * Changes the document type to indicate that it exists at a given version but
     * that its data is not known (e.g. a document that was updated without a known
     * base document).
     */    convertToUnknownDocument(e) {
        return this.version = e, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , 
        this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , 
        this;
    }
    setHasCommittedMutations() {
        return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;
    }
    setHasLocalMutations() {
        return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), 
        this;
    }
    setReadTime(e) {
        return this.readTime = e, this;
    }
    get hasLocalMutations() {
        return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;
    }
    get hasCommittedMutations() {
        return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;
    }
    get hasPendingWrites() {
        return this.hasLocalMutations || this.hasCommittedMutations;
    }
    isValidDocument() {
        return 0 /* DocumentType.INVALID */ !== this.documentType;
    }
    isFoundDocument() {
        return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;
    }
    isNoDocument() {
        return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;
    }
    isUnknownDocument() {
        return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;
    }
    isEqual(e) {
        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);
    }
    mutableCopy() {
        return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);
    }
    toString() {
        return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;
    }
}

/**
 * Compares the value for field `field` in the provided documents. Throws if
 * the field does not exist in both documents.
 */
/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The initial mutation batch id for each index. Gets updated during index
 * backfill.
 */
const Xe = -1;

/**
 * The initial sequence number for each index. Gets updated during index
 * backfill.
 */
/**
 * An index definition for field indexes in Firestore.
 *
 * Every index is associated with a collection. The definition contains a list
 * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or
 * `CONTAINS` for ArrayContains/ArrayContainsAny queries).
 *
 * Unlike the backend, the SDK does not differentiate between collection or
 * collection group-scoped indices. Every index can be used for both single
 * collection and collection group queries.
 */
class FieldIndex {
    constructor(
    /**
     * The index ID. Returns -1 if the index ID is not available (e.g. the index
     * has not yet been persisted).
     */
    e, 
    /** The collection ID this index applies to. */
    t, 
    /** The field segments for this index. */
    n, 
    /** Shows how up-to-date the index is for the current user. */
    r) {
        this.indexId = e, this.collectionGroup = t, this.fields = n, this.indexState = r;
    }
}

/** An ID for an index that has not yet been added to persistence.  */
/** Returns the ArrayContains/ArrayContainsAny segment for this index. */
function __PRIVATE_fieldIndexGetArraySegment(e) {
    return e.fields.find((e => 2 /* IndexKind.CONTAINS */ === e.kind));
}

/** Returns all directional (ascending/descending) segments for this index. */ function __PRIVATE_fieldIndexGetDirectionalSegments(e) {
    return e.fields.filter((e => 2 /* IndexKind.CONTAINS */ !== e.kind));
}

/**
 * Returns the order of the document key component for the given index.
 *
 * PORTING NOTE: This is only used in the Web IndexedDb implementation.
 */
/**
 * Compares indexes by collection group and segments. Ignores update time and
 * index ID.
 */
function __PRIVATE_fieldIndexSemanticComparator(e, t) {
    let n = __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);
    if (0 !== n) return 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]), 
    0 !== n) return n;
    return __PRIVATE_primitiveComparator(e.fields.length, t.fields.length);
}

/** Returns a debug representation of the field index */ FieldIndex.UNKNOWN_ID = -1;

/** An index component consisting of field path and index type.  */
class IndexSegment {
    constructor(
    /** The field path of the component. */
    e, 
    /** The fields sorting order. */
    t) {
        this.fieldPath = e, this.kind = t;
    }
}

function __PRIVATE_indexSegmentComparator(e, t) {
    const n = Oe.comparator(e.fieldPath, t.fieldPath);
    return 0 !== n ? n : __PRIVATE_primitiveComparator(e.kind, t.kind);
}

/**
 * Stores the "high water mark" that indicates how updated the Index is for the
 * current user.
 */ class IndexState {
    constructor(
    /**
     * Indicates when the index was last updated (relative to other indexes).
     */
    e, 
    /** The the latest indexed read time, document and batch id. */
    t) {
        this.sequenceNumber = e, this.offset = t;
    }
    /** The state of an index that has not yet been backfilled. */    static empty() {
        return new IndexState(0, IndexOffset.min());
    }
}

/**
 * Creates an offset that matches all documents with a read time higher than
 * `readTime`.
 */ function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e, t) {
    // We want to create an offset that matches all documents with a read time
    // greater than the provided read time. To do so, we technically need to
    // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use
    // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use
    // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches
    // all valid document IDs.
    const n = e.toTimestamp().seconds, r = e.toTimestamp().nanoseconds + 1, i = SnapshotVersion.fromTimestamp(1e9 === r ? new Timestamp(n + 1, 0) : new Timestamp(n, r));
    return new IndexOffset(i, DocumentKey.empty(), t);
}

/** Creates a new offset based on the provided document. */ function __PRIVATE_newIndexOffsetFromDocument(e) {
    return new IndexOffset(e.readTime, e.key, Xe);
}

/**
 * Stores the latest read time, document and batch ID that were processed for an
 * index.
 */ class IndexOffset {
    constructor(
    /**
     * The latest read time version that has been indexed by Firestore for this
     * field index.
     */
    e, 
    /**
     * The key of the last document that was indexed for this query. Use
     * `DocumentKey.empty()` if no document has been indexed.
     */
    t, 
    /*
     * The largest mutation batch id that's been processed by Firestore.
     */
    n) {
        this.readTime = e, this.documentKey = t, this.largestBatchId = n;
    }
    /** Returns an offset that sorts before all regular offsets. */    static min() {
        return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), Xe);
    }
    /** Returns an offset that sorts after all regular offsets. */    static max() {
        return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), Xe);
    }
}

function __PRIVATE_indexOffsetComparator(e, t) {
    let n = e.readTime.compareTo(t.readTime);
    return 0 !== n ? n : (n = DocumentKey.comparator(e.documentKey, t.documentKey), 
    0 !== n ? n : __PRIVATE_primitiveComparator(e.largestBatchId, t.largestBatchId));
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Visible for testing
class __PRIVATE_TargetImpl {
    constructor(e, t = null, n = [], r = [], i = null, s = null, _ = null) {
        this.path = e, this.collectionGroup = t, this.orderBy = n, this.filters = r, this.limit = i, 
        this.startAt = s, this.endAt = _, this.R = null;
    }
}

/**
 * Initializes a Target with a path and optional additional query constraints.
 * Path must currently be empty if this is a collection group query.
 *
 * NOTE: you should always construct `Target` from `Query.toTarget` instead of
 * using this factory method, because `Query` provides an implicit `orderBy`
 * property.
 */ function __PRIVATE_newTarget(e, t = null, n = [], r = [], i = null, s = null, _ = null) {
    return new __PRIVATE_TargetImpl(e, t, n, r, i, s, _);
}

function __PRIVATE_canonifyTarget(e) {
    const t = __PRIVATE_debugCast(e);
    if (null === t.R) {
        let e = t.path.canonicalString();
        null !== t.collectionGroup && (e += "|cg:" + t.collectionGroup), e += "|f:", e += t.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","), 
        e += "|ob:", e += t.orderBy.map((e => function __PRIVATE_canonifyOrderBy(e) {
            // TODO(b/29183165): Make this collision robust.
            return e.field.canonicalString() + e.dir;
        }(e))).join(","), __PRIVATE_isNullOrUndefined(t.limit) || (e += "|l:", e += t.limit), 
        t.startAt && (e += "|lb:", e += t.startAt.inclusive ? "b:" : "a:", e += t.startAt.position.map((e => canonicalId(e))).join(",")), 
        t.endAt && (e += "|ub:", e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((e => canonicalId(e))).join(",")), 
        t.R = e;
    }
    return t.R;
}

function __PRIVATE_targetEquals(e, t) {
    if (e.limit !== t.limit) return false;
    if (e.orderBy.length !== t.orderBy.length) return false;
    for (let n = 0; n < e.orderBy.length; n++) if (!__PRIVATE_orderByEquals(e.orderBy[n], t.orderBy[n])) return false;
    if (e.filters.length !== t.filters.length) return false;
    for (let n = 0; n < e.filters.length; n++) if (!__PRIVATE_filterEquals(e.filters[n], t.filters[n])) return false;
    return e.collectionGroup === t.collectionGroup && (!!e.path.isEqual(t.path) && (!!__PRIVATE_boundEquals(e.startAt, t.startAt) && __PRIVATE_boundEquals(e.endAt, t.endAt)));
}

function __PRIVATE_targetIsPipelineTarget(e) {
    // Workaround for circular dependency
    return !!e.isCorePipeline;
}

function __PRIVATE_targetIsDocumentTarget(e) {
    return !!e.path && DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;
}

/** Returns the field filters that target the given field path. */ function __PRIVATE_targetGetFieldFiltersForPath(e, t) {
    return e.filters.filter((e => e instanceof FieldFilter && e.field.isEqual(t)));
}

/**
 * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY
 * filters. Returns `null` if there are no such filters.
 */
/**
 * Returns the value to use as the lower bound for ascending index segment at
 * the provided `fieldPath` (or the upper bound for an descending segment).
 */
function __PRIVATE_targetGetAscendingBound(e, t, n) {
    let r = He, i = true;
    // Process all filters to find a value for the current field segment
    for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {
        let e = He, t = true;
        switch (n.op) {
          case "<" /* Operator.LESS_THAN */ :
          case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
            e = __PRIVATE_valuesGetLowerBound(n.value);
            break;

          case "==" /* Operator.EQUAL */ :
          case "in" /* Operator.IN */ :
          case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
            e = n.value;
            break;

          case ">" /* Operator.GREATER_THAN */ :
            e = n.value, t = false;
            break;

          case "!=" /* Operator.NOT_EQUAL */ :
          case "not-in" /* Operator.NOT_IN */ :
            e = He;
 // Remaining filters cannot be used as lower bounds.
                }
        __PRIVATE_lowerBoundCompare({
            value: r,
            inclusive: i
        }, {
            value: e,
            inclusive: t
        }) < 0 && (r = e, i = t);
    }
    // If there is an additional bound, compare the values against the existing
    // range to see if we can narrow the scope.
        if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {
        if (e.orderBy[s].field.isEqual(t)) {
            const e = n.position[s];
            __PRIVATE_lowerBoundCompare({
                value: r,
                inclusive: i
            }, {
                value: e,
                inclusive: n.inclusive
            }) < 0 && (r = e, i = n.inclusive);
            break;
        }
    }
    return {
        value: r,
        inclusive: i
    };
}

/**
 * Returns the value to use as the upper bound for ascending index segment at
 * the provided `fieldPath` (or the lower bound for a descending segment).
 */ function __PRIVATE_targetGetDescendingBound(e, t, n) {
    let r = Ge, i = true;
    // Process all filters to find a value for the current field segment
    for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) {
        let e = Ge, t = true;
        switch (n.op) {
          case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
          case ">" /* Operator.GREATER_THAN */ :
            e = __PRIVATE_valuesGetUpperBound(n.value), t = false;
            break;

          case "==" /* Operator.EQUAL */ :
          case "in" /* Operator.IN */ :
          case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
            e = n.value;
            break;

          case "<" /* Operator.LESS_THAN */ :
            e = n.value, t = false;
            break;

          case "!=" /* Operator.NOT_EQUAL */ :
          case "not-in" /* Operator.NOT_IN */ :
            e = Ge;
 // Remaining filters cannot be used as upper bounds.
                }
        __PRIVATE_upperBoundCompare({
            value: r,
            inclusive: i
        }, {
            value: e,
            inclusive: t
        }) > 0 && (r = e, i = t);
    }
    // If there is an additional bound, compare the values against the existing
    // range to see if we can narrow the scope.
        if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) {
        if (e.orderBy[s].field.isEqual(t)) {
            const e = n.position[s];
            __PRIVATE_upperBoundCompare({
                value: r,
                inclusive: i
            }, {
                value: e,
                inclusive: n.inclusive
            }) > 0 && (r = e, i = n.inclusive);
            break;
        }
    }
    return {
        value: r,
        inclusive: i
    };
}

/** Returns the number of segments of a perfect index for this target. */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Query encapsulates all the query attributes we support in the SDK. It can
 * be run against the LocalStore, as well as be converted to a `Target` to
 * query the RemoteStore results.
 *
 * Visible for testing.
 */
class __PRIVATE_QueryImpl {
    /**
     * Initializes a Query with a path and optional additional query constraints.
     * Path must currently be empty if this is a collection group query.
     */
    constructor(e, t = null, n = [], r = [], i = null, s = "F" /* LimitType.First */ , _ = null, o = null) {
        this.path = e, this.collectionGroup = t, this.explicitOrderBy = n, this.filters = r, 
        this.limit = i, this.limitType = s, this.startAt = _, this.endAt = o, this.I = null, 
        // The corresponding `Target` of this `Query` instance, for use with
        // non-aggregate queries.
        this.A = null, 
        // The corresponding `Target` of this `Query` instance, for use with
        // aggregate queries. Unlike targets for non-aggregate queries,
        // aggregate query targets do not contain normalized order-bys, they only
        // contain explicit order-bys.
        this.V = null, this.startAt, this.endAt;
    }
}

/** Creates a new Query instance with the options provided. */ function __PRIVATE_newQuery(e, t, n, r, i, s, _, o) {
    return new __PRIVATE_QueryImpl(e, t, n, r, i, s, _, o);
}

/** Creates a new Query for a query that matches all documents at `path` */ function __PRIVATE_newQueryForPath(e) {
    return new __PRIVATE_QueryImpl(e);
}

/**
 * Helper to convert a collection group query into a collection query at a
 * specific path. This is used when executing collection group queries, since
 * we have to split the query into a set of collection queries at multiple
 * paths.
 */
/**
 * Returns true if this query does not specify any query constraints that
 * could remove results.
 */
function __PRIVATE_queryMatchesAllDocuments(e) {
    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());
}

// Returns the sorted set of inequality filter fields used in this query.
/**
 * Returns whether the query matches a single document by path (rather than a
 * collection).
 */
function __PRIVATE_isDocumentQuery$1(e) {
    return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length;
}

/**
 * Returns whether the query matches a collection group rather than a specific
 * collection.
 */ function __PRIVATE_isCollectionGroupQuery(e) {
    return null !== e.collectionGroup;
}

/**
 * Returns the normalized order-by constraint that is used to execute the Query,
 * which can be different from the order-by constraints the user provided (e.g.
 * the SDK and backend always orders by `__name__`). The normalized order-by
 * includes implicit order-bys in addition to the explicit user provided
 * order-bys.
 */ function __PRIVATE_queryNormalizedOrderBy(e) {
    const t = __PRIVATE_debugCast(e);
    if (null === t.I) {
        t.I = [];
        const e = new Set;
        // Any explicit order by fields should be added as is.
                for (const n of t.explicitOrderBy) t.I.push(n), e.add(n.field.canonicalString());
        // The order of the implicit ordering always matches the last explicit order by.
                const n = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , r = function __PRIVATE_getInequalityFilterFields(e) {
            let t = new SortedSet(Oe.comparator);
            return e.filters.forEach((e => {
                e.getFlattenedFilters().forEach((e => {
                    e.isInequality() && (t = t.add(e.field));
                }));
            })), t;
        }
        /**
 * Creates a new Query for a collection group query that matches all documents
 * within the provided collection group.
 */ (t);
        // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical
        // order. When there are multiple inequality filters on the same field, the field should be added
        // only once.
        // Note: `SortedSet<FieldPath>` sorts the key field before other fields. However, we want the key
        // field to be sorted last.
                r.forEach((r => {
            e.has(r.canonicalString()) || r.isKeyField() || t.I.push(new OrderBy(r, n));
        })), 
        // Add the document key field to the last if it is not explicitly ordered.
        e.has(Oe.keyField().canonicalString()) || t.I.push(new OrderBy(Oe.keyField(), n));
    }
    return t.I;
}

/**
 * Converts this `Query` instance to its corresponding `Target` representation.
 */ function __PRIVATE_queryToTarget(e) {
    const t = __PRIVATE_debugCast(e);
    return t.A || (t.A = __PRIVATE__queryToTarget(t, __PRIVATE_queryNormalizedOrderBy(e))), 
    t.A;
}

/**
 * Converts this `Query` instance to its corresponding `Target` representation,
 * for use within an aggregate query. Unlike targets for non-aggregate queries,
 * aggregate query targets do not contain normalized order-bys, they only
 * contain explicit order-bys.
 */ function __PRIVATE_queryToAggregateTarget(e) {
    const t = __PRIVATE_debugCast(e);
    return t.V || (
    // Do not include implicit order-bys for aggregate queries.
    t.V = __PRIVATE__queryToTarget(t, e.explicitOrderBy)), t.V;
}

function __PRIVATE__queryToTarget(e, t) {
    if ("F" /* LimitType.First */ === e.limitType) return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, e.startAt, e.endAt);
    {
        // Flip the orderBy directions since we want the last results
        t = t.map((e => {
            const t = "desc" /* Direction.DESCENDING */ === e.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */;
            return new OrderBy(e.field, t);
        }));
        // We need to swap the cursors to match the now-flipped query ordering.
        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;
        // Now return as a LimitType.First query.
        return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, n, r);
    }
}

function __PRIVATE_queryWithAddedFilter(e, t) {
    const n = e.filters.concat([ t ]);
    return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), n, e.limit, e.limitType, e.startAt, e.endAt);
}

function __PRIVATE_queryWithAddedOrderBy(e, t) {
    // TODO(dimond): validate that orderBy does not list the same key twice.
    const n = e.explicitOrderBy.concat([ t ]);
    return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, n, e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);
}

function __PRIVATE_queryWithLimit(e, t, n) {
    return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), t, n, e.startAt, e.endAt);
}

function __PRIVATE_queryWithStartAt(e, t) {
    return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, t, e.endAt);
}

function __PRIVATE_queryWithEndAt(e, t) {
    return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, t);
}

function __PRIVATE_queryEquals(e, t) {
    return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e), __PRIVATE_queryToTarget(t)) && e.limitType === t.limitType;
}

// TODO(b/29183165): This is used to get a unique string from a query to, for
// example, use as a dictionary key, but the implementation is subject to
// collisions. Make it collision-free.
function __PRIVATE_stringifyQuery(e) {
    return `Query(target=${function __PRIVATE_stringifyTarget(e) {
        let t = e.path.canonicalString();
        return null !== e.collectionGroup && (t += " collectionGroup=" + e.collectionGroup), 
        e.filters.length > 0 && (t += `, filters: [${e.filters.map((e => __PRIVATE_stringifyFilter(e))).join(", ")}]`), 
        __PRIVATE_isNullOrUndefined(e.limit) || (t += ", limit: " + e.limit), e.orderBy.length > 0 && (t += `, orderBy: [${e.orderBy.map((e => function __PRIVATE_stringifyOrderBy(e) {
            return `${e.field.canonicalString()} (${e.dir})`;
        }(e))).join(", ")}]`), e.startAt && (t += ", startAt: ", t += e.startAt.inclusive ? "b:" : "a:", 
        t += e.startAt.position.map((e => canonicalId(e))).join(",")), e.endAt && (t += ", endAt: ", 
        t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((e => canonicalId(e))).join(",")), 
        `Target(${t})`;
    }(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`;
}

/** Returns whether `doc` matches the constraints of `query`. */ function __PRIVATE_queryMatches(e, t) {
    return t.isFoundDocument() && function __PRIVATE_queryMatchesPathAndCollectionGroup(e, t) {
        const n = t.key.path;
        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);
    }
    /**
 * A document must have a value for every ordering clause in order to show up
 * in the results.
 */ (e, t) && function __PRIVATE_queryMatchesOrderBy(e, t) {
        // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit).
        // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must
        // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due
        // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a".
        // A document with content of {b:1} matches the filters, but does not match the orderBy because
        // it's missing the field 'a'.
        for (const n of __PRIVATE_queryNormalizedOrderBy(e)) 
        // order-by key always matches
        if (!n.field.isKeyField() && null === t.data.field(n.field)) return false;
        return true;
    }(e, t) && function __PRIVATE_queryMatchesFilters(e, t) {
        for (const n of e.filters) if (!n.matches(t)) return false;
        return true;
    }
    /** Makes sure a document is within the bounds, if provided. */ (e, t) && function __PRIVATE_queryMatchesBounds(e, t) {
        if (e.startAt && !
        /**
 * Returns true if a document sorts before a bound using the provided sort
 * order.
 */
        function __PRIVATE_boundSortsBeforeDocument(e, t, n) {
            const r = __PRIVATE_boundCompareToDocument(e, t, n);
            return e.inclusive ? r <= 0 : r < 0;
        }(e.startAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return false;
        if (e.endAt && !function __PRIVATE_boundSortsAfterDocument(e, t, n) {
            const r = __PRIVATE_boundCompareToDocument(e, t, n);
            return e.inclusive ? r >= 0 : r > 0;
        }(e.endAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return false;
        return true;
    }
    /**
 * Returns the collection group that this query targets.
 *
 * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab
 * synchronization for query results.
 */ (e, t);
}

/**
 * Returns a new comparator function that can be used to compare two documents
 * based on the Query's ordering constraint.
 */
function __PRIVATE_newQueryComparator(e) {
    return (t, n) => {
        let r = false;
        for (const i of __PRIVATE_queryNormalizedOrderBy(e)) {
            const e = __PRIVATE_compareDocs(i, t, n);
            if (0 !== e) return e;
            r = r || i.field.isKeyField();
        }
        return 0;
    };
}

function __PRIVATE_compareDocs(e, t, n) {
    const r = e.field.isKeyField() ? DocumentKey.comparator(t.key, n.key) : function __PRIVATE_compareDocumentsByField(e, t, n) {
        const r = t.data.field(e), i = n.data.field(e);
        return null !== r && null !== i ? __PRIVATE_valueCompare(r, i) : l(42886);
    }(e.field, t, n);
    switch (e.dir) {
      case "asc" /* Direction.ASCENDING */ :
        return r;

      case "desc" /* Direction.DESCENDING */ :
        return -1 * r;

      default:
        return l(19790, {
            direction: e.dir
        });
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class ExistenceFilter {
    constructor(e, t) {
        this.count = e, this.unchangedNames = t;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Error Codes describing the different ways GRPC can fail. These are copied
 * directly from GRPC's sources here:
 *
 * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h
 *
 * Important! The names of these identifiers matter because the string forms
 * are used for reverse lookups from the webchannel stream. Do NOT change the
 * names of these identifiers or change this into a const enum.
 */ var et, tt;

/**
 * Determines whether an error code represents a permanent error when received
 * in response to a non-write operation.
 *
 * See isPermanentWriteError for classifying write errors.
 */
function __PRIVATE_isPermanentError(e) {
    switch (e) {
      case aa.OK:
        return l(64938);

      case aa.CANCELLED:
      case aa.UNKNOWN:
      case aa.DEADLINE_EXCEEDED:
      case aa.RESOURCE_EXHAUSTED:
      case aa.INTERNAL:
      case aa.UNAVAILABLE:
 // Unauthenticated means something went wrong with our token and we need
        // to retry with new credentials which will happen automatically.
              case aa.UNAUTHENTICATED:
        return false;

      case aa.INVALID_ARGUMENT:
      case aa.NOT_FOUND:
      case aa.ALREADY_EXISTS:
      case aa.PERMISSION_DENIED:
      case aa.FAILED_PRECONDITION:
 // Aborted might be retried in some scenarios, but that is dependent on
        // the context and should handled individually by the calling code.
        // See https://cloud.google.com/apis/design/errors.
              case aa.ABORTED:
      case aa.OUT_OF_RANGE:
      case aa.UNIMPLEMENTED:
      case aa.DATA_LOSS:
        return true;

      default:
        return l(15467, {
            code: e
        });
    }
}

/**
 * Determines whether an error code represents a permanent error when received
 * in response to a write operation.
 *
 * Write operations must be handled specially because as of b/119437764, ABORTED
 * errors on the write stream should be retried too (even though ABORTED errors
 * are not generally retryable).
 *
 * Note that during the initial handshake on the write stream an ABORTED error
 * signals that we should discard our stream token (i.e. it is permanent). This
 * means a handshake error should be classified with isPermanentError, above.
 */
/**
 * Maps an error Code from GRPC status code number, like 0, 1, or 14. These
 * are not the same as HTTP status codes.
 *
 * @returns The Code equivalent to the given GRPC status code. Fails if there
 *     is no match.
 */
function __PRIVATE_mapCodeFromRpcCode(e) {
    if (void 0 === e) 
    // This shouldn't normally happen, but in certain error cases (like trying
    // to send invalid proto messages) we may get an error with no GRPC code.
    return __PRIVATE_logError("GRPC error has no .code"), aa.UNKNOWN;
    switch (e) {
      case et.OK:
        return aa.OK;

      case et.CANCELLED:
        return aa.CANCELLED;

      case et.UNKNOWN:
        return aa.UNKNOWN;

      case et.DEADLINE_EXCEEDED:
        return aa.DEADLINE_EXCEEDED;

      case et.RESOURCE_EXHAUSTED:
        return aa.RESOURCE_EXHAUSTED;

      case et.INTERNAL:
        return aa.INTERNAL;

      case et.UNAVAILABLE:
        return aa.UNAVAILABLE;

      case et.UNAUTHENTICATED:
        return aa.UNAUTHENTICATED;

      case et.INVALID_ARGUMENT:
        return aa.INVALID_ARGUMENT;

      case et.NOT_FOUND:
        return aa.NOT_FOUND;

      case et.ALREADY_EXISTS:
        return aa.ALREADY_EXISTS;

      case et.PERMISSION_DENIED:
        return aa.PERMISSION_DENIED;

      case et.FAILED_PRECONDITION:
        return aa.FAILED_PRECONDITION;

      case et.ABORTED:
        return aa.ABORTED;

      case et.OUT_OF_RANGE:
        return aa.OUT_OF_RANGE;

      case et.UNIMPLEMENTED:
        return aa.UNIMPLEMENTED;

      case et.DATA_LOSS:
        return aa.DATA_LOSS;

      default:
        return l(39323, {
            code: e
        });
    }
}

/**
 * Converts an HTTP response's error status to the equivalent error code.
 *
 * @param status - An HTTP error response status ("FAILED_PRECONDITION",
 * "UNKNOWN", etc.)
 * @returns The equivalent Code. Non-matching responses are mapped to
 *     Code.UNKNOWN.
 */ (tt = et || (et = {}))[tt.OK = 0] = "OK", tt[tt.CANCELLED = 1] = "CANCELLED", 
tt[tt.UNKNOWN = 2] = "UNKNOWN", tt[tt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", 
tt[tt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", tt[tt.NOT_FOUND = 5] = "NOT_FOUND", 
tt[tt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", tt[tt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", 
tt[tt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", tt[tt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", 
tt[tt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", tt[tt.ABORTED = 10] = "ABORTED", 
tt[tt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", tt[tt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", 
tt[tt.INTERNAL = 13] = "INTERNAL", tt[tt.UNAVAILABLE = 14] = "UNAVAILABLE", tt[tt.DATA_LOSS = 15] = "DATA_LOSS";

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A map implementation that uses objects as keys. Objects must have an
 * associated equals function and must be immutable. Entries in the map are
 * stored together with the key being produced from the mapKeyFn. This map
 * automatically handles collisions of keys.
 */
class ObjectMap {
    constructor(e, t) {
        this.mapKeyFn = e, this.equalsFn = t, 
        /**
         * The inner map for a key/value pair. Due to the possibility of collisions we
         * keep a list of entries that we do a linear search through to find an actual
         * match. Note that collisions should be rare, so we still expect near
         * constant time lookups in practice.
         */
        this.inner = {}, 
        /** The number of entries stored in the map */
        this.innerSize = 0;
    }
    /** Get a value for this key, or undefined if it does not exist. */    get(e) {
        const t = this.mapKeyFn(e), n = this.inner[t];
        if (void 0 !== n) for (const [t, r] of n) if (this.equalsFn(t, e)) return r;
    }
    has(e) {
        return void 0 !== this.get(e);
    }
    /** Put this key and value in the map. */    set(e, t) {
        const n = this.mapKeyFn(e), r = this.inner[n];
        if (void 0 === r) return this.inner[n] = [ [ e, t ] ], void this.innerSize++;
        for (let n = 0; n < r.length; n++) if (this.equalsFn(r[n][0], e)) 
        // This is updating an existing entry and does not increase `innerSize`.
        return void (r[n] = [ e, t ]);
        r.push([ e, t ]), this.innerSize++;
    }
    /**
     * Remove this key from the map. Returns a boolean if anything was deleted.
     */    delete(e) {
        const t = this.mapKeyFn(e), n = this.inner[t];
        if (void 0 === n) return false;
        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), 
        this.innerSize--, true;
        return false;
    }
    forEach(e) {
        forEach(this.inner, ((t, n) => {
            for (const [t, r] of n) e(t, r);
        }));
    }
    isEmpty() {
        return isEmpty(this.inner);
    }
    size() {
        return this.innerSize;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const nt = new SortedMap(DocumentKey.comparator);

function __PRIVATE_mutableDocumentMap() {
    return nt;
}

const rt = new SortedMap(DocumentKey.comparator);

function documentMap(...e) {
    let t = rt;
    for (const n of e) t = t.insert(n.key, n);
    return t;
}

function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) {
    let t = rt;
    return e.forEach(((e, n) => t = t.insert(e, n.overlayedDocument))), t;
}

function __PRIVATE_newOverlayMap() {
    return __PRIVATE_newDocumentKeyMap();
}

function __PRIVATE_newMutationMap() {
    return __PRIVATE_newDocumentKeyMap();
}

function __PRIVATE_newDocumentKeyMap() {
    return new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t)));
}

const it = new SortedMap(DocumentKey.comparator);

const st = new SortedSet(DocumentKey.comparator);

function __PRIVATE_documentKeySet(...e) {
    let t = st;
    for (const n of e) t = t.add(n);
    return t;
}

const _t = new SortedSet(__PRIVATE_primitiveComparator);

function __PRIVATE_targetIdSet() {
    return _t;
}

/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The global, singleton instance of TestingHooksSpi.
 *
 * This variable will be `null` in all cases _except_ when running from
 * integration tests that have registered callbacks to be notified of events
 * that happen during the test execution.
 */ let ot = null;

/**
 * Sets the value of the `testingHooksSpi` object.
 * @param instance - the instance to set.
 */ function __PRIVATE_setTestingHooksSpi(e) {
    if (ot) throw new Error("a TestingHooksSpi instance is already set");
    ot = e;
}

/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An instance of the Platform's 'TextEncoder' implementation.
 */ function __PRIVATE_newTextEncoder() {
    return new TextEncoder;
}

/**
 * An instance of the Platform's 'TextDecoder' implementation.
 */
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const at = new bloomBlob.Integer([ 4294967295, 4294967295 ], 0);

// Hash a string using md5 hashing algorithm.
function __PRIVATE_getMd5HashValue(e) {
    const t = __PRIVATE_newTextEncoder().encode(e), n = new bloomBlob.Md5;
    return n.update(t), new Uint8Array(n.digest());
}

// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using
// 2’s complement using little endian.
function __PRIVATE_get64BitUints(e) {
    const t = new DataView(e.buffer), n = t.getUint32(0, /* littleEndian= */ true), r = t.getUint32(4, /* littleEndian= */ true), i = t.getUint32(8, /* littleEndian= */ true), s = t.getUint32(12, /* littleEndian= */ true);
    return [ new bloomBlob.Integer([ n, r ], 0), new bloomBlob.Integer([ i, s ], 0) ];
}

class BloomFilter {
    constructor(e, t, n) {
        if (this.bitmap = e, this.padding = t, this.hashCount = n, t < 0 || t >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t}`);
        if (n < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);
        if (e.length > 0 && 0 === this.hashCount) 
        // Only empty bloom filter can have 0 hash count.
        throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`);
        if (0 === e.length && 0 !== t) 
        // Empty bloom filter should have 0 padding.
        throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t}`);
        this.m = 8 * e.length - t, 
        // Set the bit count in Integer to avoid repetition in mightContain().
        this.p = bloomBlob.Integer.fromNumber(this.m);
    }
    // Calculate the ith hash value based on the hashed 64bit integers,
    // and calculate its corresponding bit index in the bitmap to be checked.
    v(e, t, n) {
        // Calculate hashed value h(i) = h1 + (i * h2).
        let r = e.add(t.multiply(bloomBlob.Integer.fromNumber(n)));
        // Wrap if hash value overflow 64bit.
                return 1 === r.compare(at) && (r = new bloomBlob.Integer([ r.getBits(0), r.getBits(1) ], 0)), 
        r.modulo(this.p).toNumber();
    }
    // Return whether the bit on the given index in the bitmap is set to 1.
    S(e) {
        return !!(this.bitmap[Math.floor(e / 8)] & 1 << e % 8);
    }
    mightContain(e) {
        // Empty bitmap should always return false on membership check.
        if (0 === this.m) return false;
        const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);
        for (let e = 0; e < this.hashCount; e++) {
            const t = this.v(n, r, e);
            if (!this.S(t)) return false;
        }
        return true;
    }
    /** Create bloom filter for testing purposes only. */    static create(e, t, n) {
        const r = e % 8 == 0 ? 0 : 8 - e % 8, i = new Uint8Array(Math.ceil(e / 8)), s = new BloomFilter(i, r, t);
        return n.forEach((e => s.insert(e))), s;
    }
    insert(e) {
        if (0 === this.m) return;
        const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t);
        for (let e = 0; e < this.hashCount; e++) {
            const t = this.v(n, r, e);
            this.D(t);
        }
    }
    D(e) {
        const t = Math.floor(e / 8), n = e % 8;
        this.bitmap[t] |= 1 << n;
    }
}

class __PRIVATE_BloomFilterError extends Error {
    constructor() {
        super(...arguments), this.name = "BloomFilterError";
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An event from the RemoteStore. It is split into targetChanges (changes to the
 * state or the set of documents in our watched targets) and documentUpdates
 * (changes to the actual documents).
 */ class RemoteEvent {
    constructor(
    /**
     * The snapshot version this event brings us up to, or MIN if not set.
     */
    e, 
    /**
     * A map from target to changes to the target. See TargetChange.
     */
    t, 
    /**
     * A map of targets that is known to be inconsistent, and the purpose for
     * re-listening. Listens for these targets should be re-established without
     * resume tokens.
     */
    n, 
    /**
     * A set of which documents have changed or been deleted, along with the
     * doc's new values (if not deleted).
     */
    r, 
    /**
     * A set of which augmented documents (pipeline) have changed or been deleted, along with the
     * doc's new values (if not deleted).
     */
    i, 
    /**
     * A set of which document updates are due only to limbo resolution targets.
     */
    s) {
        this.snapshotVersion = e, this.targetChanges = t, this.targetMismatches = n, this.documentUpdates = r, 
        this.augmentedDocumentUpdates = i, this.resolvedLimboDocuments = s;
    }
    /**
     * HACK: Views require RemoteEvents in order to determine whether the view is
     * CURRENT, but secondary tabs don't receive remote events. So this method is
     * used to create a synthesized RemoteEvent that can be used to apply a
     * CURRENT status change to a View, for queries executed in a different tab.
     */
    // PORTING NOTE: Multi-tab only
    static createSynthesizedRemoteEventForCurrentChange(e, t, n) {
        const r = new Map;
        return r.set(e, TargetChange.createSynthesizedTargetChangeForCurrentChange(e, t, n)), 
        new RemoteEvent(SnapshotVersion.min(), r, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet());
    }
}

/**
 * A TargetChange specifies the set of changes for a specific target as part of
 * a RemoteEvent. These changes track which documents are added, modified or
 * removed, as well as the target's resume token and whether the target is
 * marked CURRENT.
 * The actual changes *to* documents are not part of the TargetChange since
 * documents may be part of multiple targets.
 */ class TargetChange {
    constructor(
    /**
     * An opaque, server-assigned token that allows watching a query to be resumed
     * after disconnecting without retransmitting all the data that matches the
     * query. The resume token essentially identifies a point in time from which
     * the server should resume sending results.
     */
    e, 
    /**
     * The "current" (synced) status of this target. Note that "current"
     * has special meaning in the RPC protocol that implies that a target is
     * both up-to-date and consistent with the rest of the watch stream.
     */
    t, 
    /**
     * The set of documents that were newly assigned to this target as part of
     * this remote event.
     */
    n, 
    /**
     * The set of documents that were already assigned to this target but received
     * an update during this remote event.
     */
    r, 
    /**
     * The set of documents that were removed from this target as part of this
     * remote event.
     */
    i) {
        this.resumeToken = e, this.current = t, this.addedDocuments = n, this.modifiedDocuments = r, 
        this.removedDocuments = i;
    }
    /**
     * This method is used to create a synthesized TargetChanges that can be used to
     * apply a CURRENT status change to a View (for queries executed in a different
     * tab) or for new queries (to raise snapshots with correct CURRENT status).
     */    static createSynthesizedTargetChangeForCurrentChange(e, t, n) {
        return new TargetChange(n, t, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet());
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents a changed document and a list of target ids to which this change
 * applies.
 *
 * If document has been deleted NoDocument will be provided.
 */ class __PRIVATE_DocumentWatchChange {
    constructor(
    /** The new document applies to all of these targets. */
    e, 
    /** The new document is removed from all of these targets. */
    t, 
    /** The key of the document for this change. */
    n, 
    /**
     * The new document or NoDocument if it was deleted. Is null if the
     * document went out of view without the server sending a new document.
     */
    r) {
        this.C = e, this.removedTargetIds = t, this.key = n, this.F = r;
    }
}

class __PRIVATE_ExistenceFilterChange {
    constructor(e, t) {
        this.targetId = e, this.O = t;
    }
}

class __PRIVATE_WatchTargetChange {
    constructor(
    /** What kind of change occurred to the watch target. */
    e, 
    /** The target IDs that were added/removed/set. */
    t, 
    /**
     * An opaque, server-assigned token that allows watching a target to be
     * resumed after disconnecting without retransmitting all the data that
     * matches the target. The resume token essentially identifies a point in
     * time from which the server should resume sending results.
     */
    n = ByteString.EMPTY_BYTE_STRING
    /** An RPC error indicating why the watch failed. */ , r = null) {
        this.state = e, this.targetIds = t, this.resumeToken = n, this.cause = r;
    }
}

/** Tracks the internal state of a Watch target. */ class __PRIVATE_TargetState {
    /**
     * Track the targetId for logging.
     */
    constructor(e) {
        this.targetId = e, 
        /**
         * The number of pending responses (adds or removes) that we are waiting on.
         * We only consider targets active that have no pending responses.
         */
        this.M = 0, 
        /**
         * Keeps track of the document changes since the last raised snapshot.
         *
         * These changes are continuously updated as we receive document updates and
         * always reflect the current set of changes against the last issued snapshot.
         */
        this.N = __PRIVATE_snapshotChangesMap(), 
        /** See public getters for explanations of these fields. */
        this.L = ByteString.EMPTY_BYTE_STRING, this.B = false, 
        /**
         * Whether this target state should be included in the next snapshot. We
         * initialize to true so that newly-added targets are included in the next
         * RemoteEvent.
         */
        this.U = true;
    }
    /**
     * Whether this target has been marked 'current'.
     *
     * 'Current' has special meaning in the RPC protocol: It implies that the
     * Watch backend has sent us all changes up to the point at which the target
     * was added and that the target is consistent with the rest of the watch
     * stream.
     */    get current() {
        return this.B;
    }
    /** The last resume token sent to us for this target. */    get resumeToken() {
        return this.L;
    }
    /** Whether this target has pending target adds or target removes. */    get k() {
        return 0 !== this.M;
    }
    /** Whether we have modified any state that should trigger a snapshot. */    get q() {
        return this.U;
    }
    /**
     * Applies the resume token to the TargetChange, but only when it has a new
     * value. Empty resumeTokens are discarded.
     */    $(e) {
        e.approximateByteSize() > 0 && (this.U = true, this.L = e);
    }
    /**
     * Creates a target change from the current set of changes.
     *
     * To reset the document changes after raising this snapshot, call
     * `clearPendingChanges()`.
     */    K() {
        let e = __PRIVATE_documentKeySet(), t = __PRIVATE_documentKeySet(), n = __PRIVATE_documentKeySet();
        return this.N.forEach(((r, i) => {
            switch (i) {
              case 0 /* ChangeType.Added */ :
                e = e.add(r);
                break;

              case 2 /* ChangeType.Modified */ :
                t = t.add(r);
                break;

              case 1 /* ChangeType.Removed */ :
                n = n.add(r);
                break;

              default:
                l(38017, {
                    changeType: i
                });
            }
        })), new TargetChange(this.L, this.B, e, t, n);
    }
    /**
     * Resets the document changes and sets `hasPendingChanges` to false.
     */    W() {
        this.U = false, this.N = __PRIVATE_snapshotChangesMap();
    }
    G(e, t) {
        this.U = true, this.N = this.N.insert(e, t);
    }
    j(e) {
        this.U = true, this.N = this.N.remove(e);
    }
    H() {
        this.M += 1;
    }
    J() {
        this.M -= 1, __PRIVATE_hardAssert(this.M >= 0, 3241, {
            M: this.M,
            targetId: this.targetId
        });
    }
    Y() {
        this.U = true, this.B = true;
    }
}

const ut = "WatchChangeAggregator";

/**
 * A helper class to accumulate watch changes into a RemoteEvent.
 */ class __PRIVATE_WatchChangeAggregator {
    constructor(e) {
        this.Z = e, 
        /**
         * The internal state of all tracked targets.
         *
         * Targets have the following lifecycle of [states] within the WatchChangeAggregator:
         * [unknown] -> recordPendingTargetRequest(t)
         *           -> [pending]
         *           -> handleTargetChange(t, Added)
         *           -> [added / !pending]
         *           -> recordPendingTargetRequest(t)
         *           -> [pending]
         *           -> handleTargetChange(t, Removed)
         *           -> [unknown]
         *
         * A reset on an [added] target leaves the target in an [added] state.
         * [added / !pending] -> handleTargetChange(t, Reset)
         *                    -> [added / !pending]
         *
         * [active]: is a substate of [added], where also `remoteStore.listenTargets.has(t) === true`.
         *           Generally it is expected that when a target is [active / !pending]
         *           then it is also [active], but the implementation does not guarantee
         *           this will always be true.
         *
         */
        this.X = new Map, 
        /** Keeps track of the documents to update since the last raised snapshot. */
        this.ee = __PRIVATE_mutableDocumentMap(), this.te = __PRIVATE_documentTargetMap(), 
        /** Keeps track of the augmented documents to update since the last raised snapshot. */
        this.ne = __PRIVATE_mutableDocumentMap(), 
        /** A mapping of document keys to their set of target IDs. */
        this.re = __PRIVATE_documentTargetMap(), 
        /**
         * A map of targets with existence filter mismatches. These targets are
         * known to be inconsistent and their listens needs to be re-established by
         * RemoteStore.
         */
        this.ie = new SortedMap(__PRIVATE_primitiveComparator);
    }
    /**
     * Processes and adds the DocumentWatchChange to the current set of changes.
     */    se(e) {
        for (const t of e.C) e.F && e.F.isFoundDocument() ? this._e(t, e.F) : this.oe(t, e.key, e.F);
        for (const t of e.removedTargetIds) this.oe(t, e.key, e.F);
    }
    /** Processes and adds the WatchTargetChange to the current set of changes. */    ae(e) {
        this.forEachTarget(e, (t => {
            const n = this.X.get(t);
            // skip unknown target state, this indicates the target change is for
            // an old target
                        if (n) switch (e.state) {
              case 0 /* WatchTargetChangeState.NoChange */ :
                this.ue(t) && n.$(e.resumeToken);
                break;

              case 1 /* WatchTargetChangeState.Added */ :
                // We need to decrement the number of pending acks needed from watch
                // for this targetId.
                n.J(), n.k || 
                // We have a freshly added target, so we need to reset any state
                // that we had previously. This can happen e.g. when remove and add
                // back a target for existence filter mismatches.
                n.W(), n.$(e.resumeToken);
                break;

              case 2 /* WatchTargetChangeState.Removed */ :
                // We need to keep track of removed targets to we can post-filter and
                // remove any target changes.
                // We need to decrement the number of pending acks needed from watch
                // for this targetId.
                n.J(), n.k || this.removeTarget(t);
                break;

              case 3 /* WatchTargetChangeState.Current */ :
                this.ue(t) && (n.Y(), n.$(e.resumeToken));
                break;

              case 4 /* WatchTargetChangeState.Reset */ :
                this.ue(t) && (
                // Reset the target and synthesizes removes for all existing
                // documents. The backend will re-add any documents that still
                // match the target before it sends the next global snapshot.
                this.ce(t), n.$(e.resumeToken));
                break;

              default:
                l(56790, {
                    state: e.state
                });
            } else __PRIVATE_logDebug(ut, `handleTargetChange received targetChange for untracked target ID (${t}) with state (${e.state})`);
        }));
    }
    /**
     * Iterates over all targetIds that the watch change applies to: either the
     * targetIds explicitly listed in the change or the targetIds of all currently
     * active targets.
     */    forEachTarget(e, t) {
        e.targetIds.length > 0 ? e.targetIds.forEach(t) : this.X.forEach(((e, n) => {
            this.ue(n) && t(n);
        }));
    }
    le(e) {
        return __PRIVATE_targetIsPipelineTarget(e) ? "documents" === e.getPipelineSourceType() && 1 === e.getPipelineDocuments()?.length : __PRIVATE_targetIsDocumentTarget(e);
    }
    /**
     * Handles existence filters and synthesizes deletes for filter mismatches.
     * Targets that are invalidated by filter mismatches are added to
     * `pendingTargetResets`.
     */    Ee(e) {
        const t = e.targetId, n = e.O.count, r = this.he(t);
        if (r) {
            const i = r.target;
            if (this.le(i)) if (0 === n) {
                // The existence filter told us the document does not exist. We deduce
                // that this document does not exist and apply a deleted document to
                // our updates. Without applying this deleted document there might be
                // another query that will raise this document as part of a snapshot
                // until it is resolved, essentially exposing inconsistency between
                // queries.
                const e = new DocumentKey(__PRIVATE_targetIsPipelineTarget(i) ? ResourcePath.fromString(i.getPipelineDocuments()[0]) : i.path);
                this.oe(t, e, MutableDocument.newNoDocument(e, SnapshotVersion.min()));
            } else __PRIVATE_hardAssert(1 === n, 20013, "Single document existence filter with count: " + n); else {
                const r = this.Te(t);
                // Existence filter mismatch. Mark the documents as being in limbo, and
                // raise a snapshot with `isFromCache:true`.
                                if (r !== n) {
                    // Apply bloom filter to identify and mark removed documents.
                    const n = this.Pe(e), i = n ? this.Re(n, e, r) : 1 /* BloomFilterApplicationStatus.Skipped */;
                    if (0 /* BloomFilterApplicationStatus.Success */ !== i) {
                        // If bloom filter application fails, we reset the mapping and
                        // trigger re-run of the query.
                        this.ce(t);
                        const e = 2 /* BloomFilterApplicationStatus.FalsePositive */ === i ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */;
                        this.ie = this.ie.insert(t, e);
                    }
                    ot?.Ie(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e, t, n, r, i) {
                        const s = {
                            localCacheCount: e,
                            existenceFilterCount: t.count,
                            databaseId: n.database,
                            projectId: n.projectId
                        }, _ = t.unchangedNames;
                        _ && (s.bloomFilter = {
                            applied: 0 /* BloomFilterApplicationStatus.Success */ === i,
                            hashCount: _?.hashCount ?? 0,
                            bitmapLength: _?.bits?.bitmap?.length ?? 0,
                            padding: _?.bits?.padding ?? 0,
                            mightContain: e => r?.mightContain(e) ?? false
                        });
                        return s;
                    }
                    /**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (r, e.O, this.Z.Ae(), n, i));
                }
            }
        }
    }
    /**
     * Parse the bloom filter from the "unchanged_names" field of an existence
     * filter.
     */    Pe(e) {
        const t = e.O.unchangedNames;
        if (!t || !t.bits) return null;
        const {bits: {bitmap: n = "", padding: r = 0}, hashCount: i = 0} = t;
        let s, _;
        try {
            s = __PRIVATE_normalizeByteString(n).toUint8Array();
        } catch (e) {
            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."), 
            null;
            throw e;
        }
        try {
            // BloomFilter throws error if the inputs are invalid.
            _ = new BloomFilter(s, r, i);
        } catch (e) {
            return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError ? "BloomFilter error: " : "Applying bloom filter failed: ", e), 
            null;
        }
        return 0 === _.m ? null : _;
    }
    /**
     * Apply bloom filter to remove the deleted documents, and return the
     * application status.
     */    Re(e, t, n) {
        return t.O.count === n - this.Ve(e, t.targetId) ? 0 /* BloomFilterApplicationStatus.Success */ : 2 /* BloomFilterApplicationStatus.FalsePositive */;
    }
    /**
     * Filter out removed documents based on bloom filter membership result and
     * return number of documents removed.
     */    Ve(e, t) {
        const n = this.Z.getRemoteKeysForTarget(t);
        let r = 0;
        return n.forEach((n => {
            const i = this.Z.Ae(), s = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`;
            e.mightContain(s) || (this.oe(t, n, /*updatedDocument=*/ null), r++);
        })), r;
    }
    /**
     * Converts the currently accumulated state into a remote event at the
     * provided snapshot version. Resets the accumulated changes before returning.
     */    de(e) {
        const t = new Map;
        this.X.forEach(((n, r) => {
            const i = this.he(r);
            if (i) {
                if (n.current && this.le(i.target)) {
                    // Document queries for document that don't exist can produce an empty
                    // result set. To update our local cache, we synthesize a document
                    // delete if we have not previously received the document for this
                    // target. This resolves the limbo state of the document, removing it
                    // from limboDocumentRefs.
                    // TODO(dimond): Ideally we would have an explicit lookup target
                    // instead resulting in an explicit delete message and we could
                    // remove this special logic.
                    const t = __PRIVATE_targetIsPipelineTarget(i.target) ? ResourcePath.fromString(i.target.getPipelineDocuments()[0]) : i.target.path, n = new DocumentKey(t);
                    this.fe(n).has(r) || this.me(r, n) || this.oe(r, n, MutableDocument.newNoDocument(n, e));
                }
                n.q && (t.set(r, n.K()), n.W());
            }
        }));
        let n = __PRIVATE_documentKeySet();
        // We extract the set of limbo-only document updates as the GC logic
        // special-cases documents that do not appear in the target cache.
        
        // TODO(gsoltis): Expand on this comment once GC is available in the JS
        // client.
                this.re.forEach(((e, t) => {
            let r = true;
            t.forEachWhile((e => {
                const t = this.he(e);
                return !t || "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ === t.purpose || (r = false, 
                false);
            })), r && (n = n.add(e));
        })), this.ee.forEach(((t, n) => n.setReadTime(e))), this.ne.forEach(((t, n) => n.setReadTime(e)));
        const r = new RemoteEvent(e, t, this.ie, this.ee, this.ne, n);
        return this.ee = __PRIVATE_mutableDocumentMap(), this.te = __PRIVATE_documentTargetMap(), 
        this.ne = __PRIVATE_mutableDocumentMap(), this.re = __PRIVATE_documentTargetMap(), 
        this.ie = new SortedMap(__PRIVATE_primitiveComparator), r;
    }
    /**
     * Adds the provided document to the internal list of document updates and
     * its document key to the given target's mapping.
     */
    // Visible for testing.
    _e(e, t) {
        const n = this.X.get(e);
        // skip unknown or inactive targets
                if (!n || !this.ue(e)) return void __PRIVATE_logDebug(ut, `addDocumentToTarget received document for unknown inactive target (${e})`);
        const r = this.me(e, t.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;
        n.G(t.key, r), __PRIVATE_targetIsPipelineTarget(this.he(e).target) && "exact" !== this.he(e).target.getPipelineFlavor() ? this.ne = this.ne.insert(t.key, t) : this.ee = this.ee.insert(t.key, t), 
        this.te = this.te.insert(t.key, this.fe(t.key).add(e)), this.re = this.re.insert(t.key, this.pe(t.key).add(e));
    }
    /**
     * Removes the provided document from the target mapping. If the
     * document no longer matches the target, but the document's state is still
     * known (e.g. we know that the document was deleted or we received the change
     * that caused the filter mismatch), the new document can be provided
     * to update the remote document cache.
     */
    // Visible for testing.
    oe(e, t, n) {
        const r = this.X.get(e);
        // skip unknown target state, this indicates the target change is for
        // an old target
                r && this.ue(e) ? (this.me(e, t) ? r.G(t, 1 /* ChangeType.Removed */) : 
        // The document may have entered and left the target before we raised a
        // snapshot, so we can just ignore the change.
        r.j(t), this.re = this.re.insert(t, this.pe(t).delete(e)), this.re = this.re.insert(t, this.pe(t).add(e)), 
        n && (__PRIVATE_targetIsPipelineTarget(this.he(e).target) && "exact" !== this.he(e).target.getPipelineFlavor() ? this.ne = this.ne.insert(t, n) : this.ee = this.ee.insert(t, n))) : __PRIVATE_logDebug(ut, `removeDocumentFromTarget received document for unknown or inactive target (${e})`);
    }
    removeTarget(e) {
        this.X.delete(e);
    }
    /**
     * Returns the current count of documents in the target. This includes both
     * the number of documents that the LocalStore considers to be part of the
     * target as well as any accumulated changes.
     */    Te(e) {
        const t = this.X.get(e);
        // skip unknown target state
                if (!t) return 0;
        const n = t.K();
        return this.Z.getRemoteKeysForTarget(e).size + n.addedDocuments.size - n.removedDocuments.size;
    }
    /**
     * Increment the number of acks needed from watch before we can consider the
     * server to be 'in-sync' with the client's active targets.
     */    H(e) {
        // For each request we get we need to record we need a response for it.
        let t = this.X.get(e);
        t || (__PRIVATE_logDebug(ut, `recordPendingTargetRequest set up tracking for target ID ${e}`), 
        t = new __PRIVATE_TargetState(e), this.X.set(e, t)), t.H();
    }
    pe(e) {
        let t = this.re.get(e);
        return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.re = this.re.insert(e, t)), 
        t;
    }
    fe(e) {
        let t = this.te.get(e);
        return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.te = this.te.insert(e, t)), 
        t;
    }
    /**
     * Verifies that the user is still interested in this target (by calling
     * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
     * from watch.
     */    ue(e) {
        const t = null !== this.he(e);
        return t || __PRIVATE_logDebug(ut, "Detected inactive target", e), t;
    }
    /**
     * Returns the TargetData for an active target (i.e. a target that the user
     * is still interested in that has no outstanding target change requests).
     */    he(e) {
        const t = this.X.get(e);
        return void 0 === t || t.k ? null : this.Z.ge(e);
    }
    /**
     * Resets the state of a Watch target to its initial state (e.g. sets
     * 'current' to false, clears the resume token and removes its target mapping
     * from all documents).
     */    ce(e) {
        this.X.set(e, new __PRIVATE_TargetState(e));
        this.Z.getRemoteKeysForTarget(e).forEach((t => {
            this.oe(e, t, /*updatedDocument=*/ null);
        }));
    }
    /**
     * Returns whether the LocalStore considers the document to be part of the
     * specified target.
     */    me(e, t) {
        return this.Z.getRemoteKeysForTarget(e).has(t);
    }
}

function __PRIVATE_documentTargetMap() {
    return new SortedMap(DocumentKey.comparator);
}

function __PRIVATE_snapshotChangesMap() {
    return new SortedMap(DocumentKey.comparator);
}

const ct = (() => {
    const e = {
        asc: "ASCENDING",
        desc: "DESCENDING"
    };
    return e;
})(), lt = (() => {
    const e = {
        "<": "LESS_THAN",
        "<=": "LESS_THAN_OR_EQUAL",
        ">": "GREATER_THAN",
        ">=": "GREATER_THAN_OR_EQUAL",
        "==": "EQUAL",
        "!=": "NOT_EQUAL",
        "array-contains": "ARRAY_CONTAINS",
        in: "IN",
        "not-in": "NOT_IN",
        "array-contains-any": "ARRAY_CONTAINS_ANY"
    };
    return e;
})(), Et = (() => {
    const e = {
        and: "AND",
        or: "OR"
    };
    return e;
})();

/**
 * This class generates JsonObject values for the Datastore API suitable for
 * sending to either GRPC stub methods or via the JSON/HTTP REST API.
 *
 * The serializer supports both Protobuf.js and Proto3 JSON formats. By
 * setting `useProto3Json` to true, the serializer will use the Proto3 JSON
 * format.
 *
 * For a description of the Proto3 JSON format check
 * https://developers.google.com/protocol-buffers/docs/proto3#json
 *
 * TODO(klimt): We can remove the databaseId argument if we keep the full
 * resource name in documents.
 */
class JsonProtoSerializer {
    constructor(e, t) {
        this.databaseId = e, this.useProto3Json = t;
    }
}

/**
 * Returns a value for a number (or null) that's appropriate to put into
 * a google.protobuf.Int32Value proto.
 * DO NOT USE THIS FOR ANYTHING ELSE.
 * This method cheats. It's typed as returning "number" because that's what
 * our generated proto interfaces say Int32Value must be. But GRPC actually
 * expects a { value: <number> } struct.
 */
function __PRIVATE_toInt32Proto(e, t) {
    return e.useProto3Json || __PRIVATE_isNullOrUndefined(t) ? t : {
        value: t
    };
}

/**
 * Returns a number (or null) from a google.protobuf.Int32Value proto.
 */
/**
 * Returns a value for a Date that's appropriate to put into a proto.
 */
function toTimestamp(e, t) {
    if (e.useProto3Json) {
        return `${new Date(1e3 * t.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + t.nanoseconds).slice(-9)}Z`;
    }
    return {
        seconds: "" + t.seconds,
        nanos: t.nanoseconds
    };
}

/**
 * Returns a Timestamp typed object given protobuf timestamp value.
 */ function fromTimestamp(e) {
    const t = __PRIVATE_normalizeTimestamp(e);
    return new Timestamp(t.seconds, t.nanos);
}

/**
 * Returns a value for bytes that's appropriate to put in a proto.
 *
 * Visible for testing.
 */ function __PRIVATE_toBytes(e, t) {
    return e.useProto3Json ? t.toBase64() : t.toUint8Array();
}

/**
 * Returns a ByteString based on the proto string value.
 */ function __PRIVATE_toVersion(e, t) {
    return toTimestamp(e, t.toTimestamp());
}

function __PRIVATE_fromVersion(e) {
    return __PRIVATE_hardAssert(!!e, 49232), SnapshotVersion.fromTimestamp(fromTimestamp(e));
}

function __PRIVATE_toResourceName(e, t) {
    return __PRIVATE_toResourcePath(e, t).canonicalString();
}

function __PRIVATE_toResourcePath(e, t) {
    const n = function __PRIVATE_fullyQualifiedPrefixPath(e) {
        return new ResourcePath([ "projects", e.projectId, "databases", e.database ]);
    }(e).child("documents");
    return void 0 === t ? n : n.child(t);
}

function __PRIVATE_fromResourceName(e) {
    const t = ResourcePath.fromString(e);
    return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t), 10190, {
        key: t.toString()
    }), t;
}

function __PRIVATE_toName(e, t) {
    return __PRIVATE_toResourceName(e.databaseId, t.path);
}

function fromName(e, t) {
    const n = __PRIVATE_fromResourceName(t);
    if (n.get(1) !== e.databaseId.projectId) throw new s(aa.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + e.databaseId.projectId);
    if (n.get(3) !== e.databaseId.database) throw new s(aa.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + e.databaseId.database);
    return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n));
}

function __PRIVATE_toQueryPath(e, t) {
    return __PRIVATE_toResourceName(e.databaseId, t);
}

function __PRIVATE_fromQueryPath(e) {
    const t = __PRIVATE_fromResourceName(e);
    // In v1beta1 queries for collections at the root did not have a trailing
    // "/documents". In v1 all resource paths contain "/documents". Preserve the
    // ability to read the v1beta1 form for compatibility with queries persisted
    // in the local target cache.
        return 4 === t.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t);
}

function __PRIVATE_getEncodedDatabaseId(e) {
    return new ResourcePath([ "projects", e.databaseId.projectId, "databases", e.databaseId.database ]).canonicalString();
}

function __PRIVATE_extractLocalPathFromResourceName(e) {
    return __PRIVATE_hardAssert(e.length > 4 && "documents" === e.get(4), 29091, {
        key: e.toString()
    }), e.popFirst(5);
}

/** Creates a Document proto from key and fields (but no create/update time) */ function __PRIVATE_toMutationDocument(e, t, n) {
    return {
        name: __PRIVATE_toName(e, t),
        fields: n.value.mapValue.fields
    };
}

function __PRIVATE_fromPipelineResponse(e, t, n) {
    const r = {};
    t.transaction?.length && (r.transaction = t.transaction);
    const i = t.executionTime ? __PRIVATE_fromVersion(t.executionTime) : void 0;
    return r.executionTime = i, n && (r.key = n.name ? fromName(e, n.name) : void 0, 
    r.fields = new ObjectValue({
        mapValue: {
            fields: n.fields
        }
    }), r.createTime = n.createTime ? __PRIVATE_fromVersion(n.createTime) : void 0, 
    r.updateTime = n.updateTime ? __PRIVATE_fromVersion(n.updateTime) : void 0), r;
}

function fromDocument(e, t, n) {
    const r = fromName(e, t.name), i = __PRIVATE_fromVersion(t.updateTime), s = t.createTime ? __PRIVATE_fromVersion(t.createTime) : SnapshotVersion.min(), _ = new ObjectValue({
        mapValue: {
            fields: t.fields
        }
    }), o = MutableDocument.newFoundDocument(r, i, s, _);
    return n && o.setHasCommittedMutations(), n ? o.setHasCommittedMutations() : o;
}

function __PRIVATE_fromBatchGetDocumentsResponse(e, t) {
    return "found" in t ? function __PRIVATE_fromFound(e, t) {
        __PRIVATE_hardAssert(!!t.found, 43571), t.found.name, t.found.updateTime;
        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({
            mapValue: {
                fields: t.found.fields
            }
        });
        return MutableDocument.newFoundDocument(n, r, i, s);
    }(e, t) : "missing" in t ? function __PRIVATE_fromMissing(e, t) {
        __PRIVATE_hardAssert(!!t.missing, 3894), __PRIVATE_hardAssert(!!t.readTime, 22933);
        const n = fromName(e, t.missing), r = __PRIVATE_fromVersion(t.readTime);
        return MutableDocument.newNoDocument(n, r);
    }(e, t) : l(7234, {
        result: t
    });
}

function __PRIVATE_fromWatchChange(e, t) {
    let n;
    if ("targetChange" in t) {
        t.targetChange;
        // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
        // if unset
        const r = function __PRIVATE_fromWatchTargetChangeState(e) {
            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 */ : l(39313, {
                state: e
            });
        }(t.targetChange.targetChangeType || "NO_CHANGE"), i = t.targetChange.targetIds || [], _ = function __PRIVATE_fromBytes(e, t) {
            return e.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t || "string" == typeof t, 58123), 
            ByteString.fromBase64String(t || "")) : (__PRIVATE_hardAssert(void 0 === t || 
            // Check if the value is an instance of both Buffer and Uint8Array,
            // despite the fact that Buffer extends Uint8Array. In some
            // environments, such as jsdom, the prototype chain of Buffer
            // does not indicate that it extends Uint8Array.
            t instanceof Buffer || t instanceof Uint8Array, 16193), ByteString.fromUint8Array(t || new Uint8Array));
        }(e, t.targetChange.resumeToken), o = t.targetChange.cause, a = o && function __PRIVATE_fromRpcStatus(e) {
            const t = void 0 === e.code ? aa.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e.code);
            return new s(t, e.message || "");
        }(o);
        n = new __PRIVATE_WatchTargetChange(r, i, _, a || null);
    } else if ("documentChange" in t) {
        t.documentChange;
        const r = t.documentChange;
        r.document, r.document.name, r.document.updateTime;
        const i = fromName(e, r.document.name), s = __PRIVATE_fromVersion(r.document.updateTime), _ = r.document.createTime ? __PRIVATE_fromVersion(r.document.createTime) : SnapshotVersion.min(), o = new ObjectValue({
            mapValue: {
                fields: r.document.fields
            }
        }), a = MutableDocument.newFoundDocument(i, s, _, o), u = r.targetIds || [], c = r.removedTargetIds || [];
        n = new __PRIVATE_DocumentWatchChange(u, c, a.key, a);
    } else if ("documentDelete" in t) {
        t.documentDelete;
        const r = t.documentDelete;
        r.document;
        const i = fromName(e, r.document), s = r.readTime ? __PRIVATE_fromVersion(r.readTime) : SnapshotVersion.min(), _ = MutableDocument.newNoDocument(i, s), o = r.removedTargetIds || [];
        n = new __PRIVATE_DocumentWatchChange([], o, _.key, _);
    } else if ("documentRemove" in t) {
        t.documentRemove;
        const r = t.documentRemove;
        r.document;
        const i = fromName(e, r.document), s = r.removedTargetIds || [];
        n = new __PRIVATE_DocumentWatchChange([], s, i, null);
    } else {
        if (!("filter" in t)) return l(11601, {
            ye: t
        });
        {
            t.filter;
            const e = t.filter;
            e.targetId;
            const {count: r = 0, unchangedNames: i} = e, s = new ExistenceFilter(r, i), _ = e.targetId;
            n = new __PRIVATE_ExistenceFilterChange(_, s);
        }
    }
    return n;
}

function toMutation(e, t) {
    let n;
    if (t instanceof __PRIVATE_SetMutation) n = {
        update: __PRIVATE_toMutationDocument(e, t.key, t.value)
    }; else if (t instanceof __PRIVATE_DeleteMutation) n = {
        delete: __PRIVATE_toName(e, t.key)
    }; else if (t instanceof __PRIVATE_PatchMutation) n = {
        update: __PRIVATE_toMutationDocument(e, t.key, t.data),
        updateMask: __PRIVATE_toDocumentMask(t.fieldMask)
    }; else {
        if (!(t instanceof __PRIVATE_VerifyMutation)) return l(16599, {
            we: t.type
        });
        n = {
            verify: __PRIVATE_toName(e, t.key)
        };
    }
    return t.fieldTransforms.length > 0 && (n.updateTransforms = t.fieldTransforms.map((e => function __PRIVATE_toFieldTransform(e, t) {
        const n = t.transform;
        if (n instanceof __PRIVATE_ServerTimestampTransform) return {
            fieldPath: t.field.canonicalString(),
            setToServerValue: "REQUEST_TIME"
        };
        if (n instanceof __PRIVATE_ArrayUnionTransformOperation) return {
            fieldPath: t.field.canonicalString(),
            appendMissingElements: {
                values: n.elements
            }
        };
        if (n instanceof __PRIVATE_ArrayRemoveTransformOperation) return {
            fieldPath: t.field.canonicalString(),
            removeAllFromArray: {
                values: n.elements
            }
        };
        if (n instanceof __PRIVATE_NumericIncrementTransformOperation) return {
            fieldPath: t.field.canonicalString(),
            increment: n.l
        };
        if (n instanceof __PRIVATE_NumericMinimumTransformOperation) return {
            fieldPath: t.field.canonicalString(),
            minimum: n.l
        };
        if (n instanceof __PRIVATE_NumericMaximumTransformOperation) return {
            fieldPath: t.field.canonicalString(),
            maximum: n.l
        };
        throw l(20930, {
            transform: t.transform
        });
    }(0, e)))), t.precondition.isNone || (n.currentDocument = function __PRIVATE_toPrecondition(e, t) {
        return void 0 !== t.updateTime ? {
            updateTime: __PRIVATE_toVersion(e, t.updateTime)
        } : void 0 !== t.exists ? {
            exists: t.exists
        } : l(27497);
    }(e, t.precondition)), n;
}

function __PRIVATE_fromMutation(e, t) {
    const n = t.currentDocument ? function __PRIVATE_fromPrecondition(e) {
        return void 0 !== e.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)) : void 0 !== e.exists ? Precondition.exists(e.exists) : Precondition.none();
    }(t.currentDocument) : Precondition.none(), r = t.updateTransforms ? t.updateTransforms.map((t => function __PRIVATE_fromFieldTransform(e, t) {
        let n = null;
        if ("setToServerValue" in t) __PRIVATE_hardAssert("REQUEST_TIME" === t.setToServerValue, 16630, {
            proto: t
        }), n = new __PRIVATE_ServerTimestampTransform; else if ("appendMissingElements" in t) {
            const e = t.appendMissingElements.values || [];
            n = new __PRIVATE_ArrayUnionTransformOperation(e);
        } else if ("removeAllFromArray" in t) {
            const e = t.removeAllFromArray.values || [];
            n = new __PRIVATE_ArrayRemoveTransformOperation(e);
        } else "increment" in t ? n = new __PRIVATE_NumericIncrementTransformOperation(e, t.increment) : "minimum" in t ? n = new __PRIVATE_NumericMinimumTransformOperation(e, t.minimum) : "maximum" in t ? n = new __PRIVATE_NumericMaximumTransformOperation(e, t.maximum) : l(16584, {
            proto: t
        });
        const r = Oe.fromServerFormat(t.fieldPath);
        return new FieldTransform(r, n);
    }(e, t))) : [];
    if (t.update) {
        t.update.name;
        const i = fromName(e, t.update.name), s = new ObjectValue({
            mapValue: {
                fields: t.update.fields
            }
        });
        if (t.updateMask) {
            const e = function __PRIVATE_fromDocumentMask(e) {
                const t = e.fieldPaths || [];
                return new FieldMask(t.map((e => Oe.fromServerFormat(e))));
            }(t.updateMask);
            return new __PRIVATE_PatchMutation(i, s, e, n, r);
        }
        return new __PRIVATE_SetMutation(i, s, n, r);
    }
    if (t.delete) {
        const r = fromName(e, t.delete);
        return new __PRIVATE_DeleteMutation(r, n);
    }
    if (t.verify) {
        const r = fromName(e, t.verify);
        return new __PRIVATE_VerifyMutation(r, n);
    }
    return l(1463, {
        proto: t
    });
}

function __PRIVATE_fromWriteResults(e, t) {
    return e && e.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t, 14353), e.map((e => function __PRIVATE_fromWriteResult(e, t) {
        // NOTE: Deletes don't have an updateTime.
        let n = e.updateTime ? __PRIVATE_fromVersion(e.updateTime) : __PRIVATE_fromVersion(t);
        return n.isEqual(SnapshotVersion.min()) && (
        // The Firestore Emulator currently returns an update time of 0 for
        // deletes of non-existing documents (rather than null). This breaks the
        // test "get deleted doc while offline with source=cache" as NoDocuments
        // with version 0 are filtered by IndexedDb's RemoteDocumentCache.
        // TODO(#2149): Remove this when Emulator is fixed
        n = __PRIVATE_fromVersion(t)), new MutationResult(n, e.transformResults || []);
    }(e, t)))) : [];
}

function __PRIVATE_toDocumentsTarget(e, t) {
    return {
        documents: [ __PRIVATE_toQueryPath(e, t.path) ]
    };
}

function __PRIVATE_toQueryTarget(e, t) {
    // Dissect the path into parent, collectionId, and optional key filter.
    const n = {
        structuredQuery: {}
    }, r = t.path;
    let i;
    null !== t.collectionGroup ? (i = r, n.structuredQuery.from = [ {
        collectionId: t.collectionGroup,
        allDescendants: true
    } ]) : (i = r.popLast(), n.structuredQuery.from = [ {
        collectionId: r.lastSegment()
    } ]), n.parent = __PRIVATE_toQueryPath(e, i);
    const s = function __PRIVATE_toFilters(e) {
        if (0 === e.length) return;
        return __PRIVATE_toFilter(CompositeFilter.create(e, "and" /* CompositeOperator.AND */));
    }(t.filters);
    s && (n.structuredQuery.where = s);
    const _ = function __PRIVATE_toOrder(e) {
        if (0 === e.length) return;
        return e.map((e => 
        // visible for testing
        function __PRIVATE_toPropertyOrder(e) {
            return {
                field: __PRIVATE_toFieldPathReference(e.field),
                direction: __PRIVATE_toDirection(e.dir)
            };
        }(e)));
    }(t.orderBy);
    _ && (n.structuredQuery.orderBy = _);
    const o = __PRIVATE_toInt32Proto(e, t.limit);
    return null !== o && (n.structuredQuery.limit = o), t.startAt && (n.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(e) {
        return {
            before: e.inclusive,
            values: e.position
        };
    }(t.startAt)), t.endAt && (n.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(e) {
        return {
            before: !e.inclusive,
            values: e.position
        };
    }(t.endAt)), {
        be: n,
        parent: i
    };
}

function __PRIVATE_toRunAggregationQueryRequest(e, t, n, r) {
    const {be: i, parent: s} = __PRIVATE_toQueryTarget(e, t), _ = {}, o = [];
    let a = 0;
    return n.forEach((e => {
        // Map all client-side aliases to a unique short-form
        // alias. This avoids issues with client-side aliases that
        // exceed the 1500-byte string size limit.
        const t = r ? e.alias : "aggregate_" + a++;
        _[t] = e.alias, "count" === e.aggregateType ? o.push({
            alias: t,
            count: {}
        }) : "avg" === e.aggregateType ? o.push({
            alias: t,
            avg: {
                field: __PRIVATE_toFieldPathReference(e.fieldPath)
            }
        }) : "sum" === e.aggregateType && o.push({
            alias: t,
            sum: {
                field: __PRIVATE_toFieldPathReference(e.fieldPath)
            }
        });
    })), {
        request: {
            structuredAggregationQuery: {
                aggregations: o,
                structuredQuery: i.structuredQuery
            },
            parent: i.parent
        },
        ve: _,
        parent: s
    };
}

function __PRIVATE_convertQueryTargetToQuery(e) {
    let t = __PRIVATE_fromQueryPath(e.parent);
    const n = e.structuredQuery, r = n.from ? n.from.length : 0;
    let i = null;
    if (r > 0) {
        __PRIVATE_hardAssert(1 === r, 65062);
        const e = n.from[0];
        e.allDescendants ? i = e.collectionId : t = t.child(e.collectionId);
    }
    let s = [];
    n.where && (s = function __PRIVATE_fromFilters(e) {
        const t = __PRIVATE_fromFilter(e);
        if (t instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t)) return t.getFilters();
        return [ t ];
    }(n.where));
    let _ = [];
    n.orderBy && (_ = function __PRIVATE_fromOrder(e) {
        return e.map((e => function __PRIVATE_fromPropertyOrder(e) {
            return new OrderBy(__PRIVATE_fromFieldPathReference(e.field), 
            // visible for testing
            function __PRIVATE_fromDirection(e) {
                switch (e) {
                  case "ASCENDING":
                    return "asc" /* Direction.ASCENDING */;

                  case "DESCENDING":
                    return "desc" /* Direction.DESCENDING */;

                  default:
                    return;
                }
            }
            // visible for testing
            (e.direction));
        }
        // visible for testing
        (e)));
    }(n.orderBy));
    let o = null;
    n.limit && (o = function __PRIVATE_fromInt32Proto(e) {
        let t;
        return t = "object" == typeof e ? e.value : e, __PRIVATE_isNullOrUndefined(t) ? null : t;
    }(n.limit));
    let a = null;
    n.startAt && (a = function __PRIVATE_fromStartAtCursor(e) {
        const t = !!e.before, n = e.values || [];
        return new Bound(n, t);
    }(n.startAt));
    let u = null;
    return n.endAt && (u = function __PRIVATE_fromEndAtCursor(e) {
        const t = !e.before, n = e.values || [];
        return new Bound(n, t);
    }
    // visible for testing
    (n.endAt)), __PRIVATE_newQuery(t, i, _, s, o, "F" /* LimitType.First */ , a, u);
}

function __PRIVATE_toListenRequestLabels(e, t) {
    const n = function __PRIVATE_toLabel(e) {
        switch (e) {
          case "TargetPurposeListen" /* TargetPurpose.Listen */ :
            return null;

          case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */ :
            return "existence-filter-mismatch";

          case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ :
            return "existence-filter-mismatch-bloom";

          case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ :
            return "limbo-document";

          default:
            return l(28987, {
                purpose: e
            });
        }
    }(t.purpose);
    return null == n ? null : {
        "goog-listen-tags": n
    };
}

function __PRIVATE_toPipelineTarget(e, t) {
    return {
        structuredPipeline: {
            pipeline: {
                stages: t.stages.map((t => t._toProto(e)))
            }
        }
    };
}

function __PRIVATE_fromFilter(e) {
    return void 0 !== e.unaryFilter ? function __PRIVATE_fromUnaryFilter(e) {
        switch (e.unaryFilter.op) {
          case "IS_NAN":
            const t = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);
            return FieldFilter.create(t, "==" /* Operator.EQUAL */ , {
                doubleValue: NaN
            });

          case "IS_NULL":
            const n = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);
            return FieldFilter.create(n, "==" /* Operator.EQUAL */ , {
                nullValue: "NULL_VALUE"
            });

          case "IS_NOT_NAN":
            const r = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);
            return FieldFilter.create(r, "!=" /* Operator.NOT_EQUAL */ , {
                doubleValue: NaN
            });

          case "IS_NOT_NULL":
            const i = __PRIVATE_fromFieldPathReference(e.unaryFilter.field);
            return FieldFilter.create(i, "!=" /* Operator.NOT_EQUAL */ , {
                nullValue: "NULL_VALUE"
            });

          case "OPERATOR_UNSPECIFIED":
            return l(61313);

          default:
            return l(60726);
        }
    }(e) : void 0 !== e.fieldFilter ? function __PRIVATE_fromFieldFilter(e) {
        return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field), function __PRIVATE_fromOperatorName(e) {
            switch (e) {
              case "EQUAL":
                return "==" /* Operator.EQUAL */;

              case "NOT_EQUAL":
                return "!=" /* Operator.NOT_EQUAL */;

              case "GREATER_THAN":
                return ">" /* Operator.GREATER_THAN */;

              case "GREATER_THAN_OR_EQUAL":
                return ">=" /* Operator.GREATER_THAN_OR_EQUAL */;

              case "LESS_THAN":
                return "<" /* Operator.LESS_THAN */;

              case "LESS_THAN_OR_EQUAL":
                return "<=" /* Operator.LESS_THAN_OR_EQUAL */;

              case "ARRAY_CONTAINS":
                return "array-contains" /* Operator.ARRAY_CONTAINS */;

              case "IN":
                return "in" /* Operator.IN */;

              case "NOT_IN":
                return "not-in" /* Operator.NOT_IN */;

              case "ARRAY_CONTAINS_ANY":
                return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */;

              case "OPERATOR_UNSPECIFIED":
                return l(58110);

              default:
                return l(50506);
            }
        }(e.fieldFilter.op), e.fieldFilter.value);
    }(e) : void 0 !== e.compositeFilter ? function __PRIVATE_fromCompositeFilter(e) {
        return CompositeFilter.create(e.compositeFilter.filters.map((e => __PRIVATE_fromFilter(e))), function __PRIVATE_fromCompositeOperatorName(e) {
            switch (e) {
              case "AND":
                return "and" /* CompositeOperator.AND */;

              case "OR":
                return "or" /* CompositeOperator.OR */;

              default:
                return l(1026);
            }
        }(e.compositeFilter.op));
    }(e) : l(30097, {
        filter: e
    });
}

function __PRIVATE_toDirection(e) {
    return ct[e];
}

function __PRIVATE_toOperatorName(e) {
    return lt[e];
}

function __PRIVATE_toCompositeOperatorName(e) {
    return Et[e];
}

function __PRIVATE_toFieldPathReference(e) {
    return {
        fieldPath: e.canonicalString()
    };
}

function __PRIVATE_fromFieldPathReference(e) {
    return Oe.fromServerFormat(e.fieldPath);
}

function __PRIVATE_toFilter(e) {
    return e instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(e) {
        if ("==" /* Operator.EQUAL */ === e.op) {
            if (__PRIVATE_isNanValue(e.value)) return {
                unaryFilter: {
                    field: __PRIVATE_toFieldPathReference(e.field),
                    op: "IS_NAN"
                }
            };
            if (__PRIVATE_isNullValue(e.value)) return {
                unaryFilter: {
                    field: __PRIVATE_toFieldPathReference(e.field),
                    op: "IS_NULL"
                }
            };
        } else if ("!=" /* Operator.NOT_EQUAL */ === e.op) {
            if (__PRIVATE_isNanValue(e.value)) return {
                unaryFilter: {
                    field: __PRIVATE_toFieldPathReference(e.field),
                    op: "IS_NOT_NAN"
                }
            };
            if (__PRIVATE_isNullValue(e.value)) return {
                unaryFilter: {
                    field: __PRIVATE_toFieldPathReference(e.field),
                    op: "IS_NOT_NULL"
                }
            };
        }
        return {
            fieldFilter: {
                field: __PRIVATE_toFieldPathReference(e.field),
                op: __PRIVATE_toOperatorName(e.op),
                value: e.value
            }
        };
    }(e) : e instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(e) {
        const t = e.getFilters().map((e => __PRIVATE_toFilter(e)));
        if (1 === t.length) return t[0];
        return {
            compositeFilter: {
                op: __PRIVATE_toCompositeOperatorName(e.op),
                filters: t
            }
        };
    }(e) : l(54877, {
        filter: e
    });
}

function __PRIVATE_toDocumentMask(e) {
    const t = [];
    return e.fields.forEach((e => t.push(e.canonicalString()))), {
        fieldPaths: t
    };
}

function __PRIVATE_isValidResourceName(e) {
    // Resource names have at least 4 components (project ID, database ID)
    return e.length >= 4 && "projects" === e.get(0) && "databases" === e.get(2);
}

function __PRIVATE_isProtoValueSerializable(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
e) {
    return !!e && "function" == typeof e._toProto && "ProtoValue" === e._protoValueType;
}

function toMapValue(e, t) {
    const n = {
        fields: {}
    };
    return t.forEach(((t, r) => {
        if ("string" != typeof r) throw new Error(`Cannot encode map with non-string key: ${r}`);
        n.fields[r] = t._toProto(e);
    })), {
        mapValue: n
    };
}

function __PRIVATE_toStringValue(e) {
    return {
        stringValue: e
    };
}

function __PRIVATE_toPipelineValue(e) {
    return {
        pipelineValue: e
    };
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function __PRIVATE_newSerializer(e) {
    return new JsonProtoSerializer(e, /* useProto3Json= */ true);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An immutable object representing an array of bytes.
 */ class Bytes {
    /** @hideconstructor */
    constructor(e) {
        this._byteString = e;
    }
    /**
     * Creates a new `Bytes` object from the given Base64 string, converting it to
     * bytes.
     *
     * @param base64 - The Base64 string used to create the `Bytes` object.
     */    static fromBase64String(e) {
        try {
            return new Bytes(ByteString.fromBase64String(e));
        } catch (e) {
            throw new s(aa.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + e);
        }
    }
    /**
     * Creates a new `Bytes` object from the given Uint8Array.
     *
     * @param array - The Uint8Array used to create the `Bytes` object.
     */    static fromUint8Array(e) {
        return new Bytes(ByteString.fromUint8Array(e));
    }
    /**
     * Returns the underlying bytes as a Base64-encoded string.
     *
     * @returns The Base64-encoded string created from the `Bytes` object.
     */    toBase64() {
        return this._byteString.toBase64();
    }
    /**
     * Returns the underlying bytes in a new `Uint8Array`.
     *
     * @returns The Uint8Array created from the `Bytes` object.
     */    toUint8Array() {
        return this._byteString.toUint8Array();
    }
    /**
     * Returns a string representation of the `Bytes` object.
     *
     * @returns A string representation of the `Bytes` object.
     */    toString() {
        return "Bytes(base64: " + this.toBase64() + ")";
    }
    /**
     * Returns true if this `Bytes` object is equal to the provided one.
     *
     * @param other - The `Bytes` object to compare against.
     * @returns true if this `Bytes` object is equal to the provided one.
     */    isEqual(e) {
        return this._byteString.isEqual(e._byteString);
    }
    /**
     * Returns a JSON-serializable representation of this `Bytes` instance.
     *
     * @returns a JSON representation of this object.
     */    toJSON() {
        return {
            type: Bytes._jsonSchemaVersion,
            bytes: this.toBase64()
        };
    }
    /**
     * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.
     *
     * @param json - a JSON object represention of a `Bytes` instance
     * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a
     * {@link FirestoreError} if an error occurs.
     */    static fromJSON(e) {
        if (__PRIVATE_validateJSON(e, Bytes._jsonSchema)) return Bytes.fromBase64String(e.bytes);
    }
}

Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = {
    type: property("string", Bytes._jsonSchemaVersion),
    bytes: property("string")
};

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A `FieldPath` refers to a field in a document. The path may consist of a
 * single field name (referring to a top-level field in the document), or a
 * list of field names (referring to a nested field in the document).
 *
 * Create a `FieldPath` by providing field names. If more than one field
 * name is provided, the path will point to a nested field in a document.
 */
class FieldPath {
    /**
     * Creates a `FieldPath` from the provided field names. If more than one field
     * name is provided, the path will point to a nested field in a document.
     *
     * @param fieldNames - A list of field names.
     */
    constructor(...e) {
        for (let t = 0; t < e.length; ++t) if (0 === e[t].length) throw new s(aa.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
        this._internalPath = new Oe(e);
    }
    /**
     * Returns true if this `FieldPath` is equal to the provided one.
     *
     * @param other - The `FieldPath` to compare against.
     * @returns true if this `FieldPath` is equal to the provided one.
     */    isEqual(e) {
        return this._internalPath.isEqual(e._internalPath);
    }
}

/**
 * Returns a special sentinel `FieldPath` to refer to the ID of a document.
 * It can be used in queries to sort or filter by the document ID.
 */ function documentId$1() {
    return new FieldPath(Ce);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Sentinel values that can be used when writing document fields with `set()`
 * or `update()`.
 */ class FieldValue {
    /**
     * @param _methodName - The public API endpoint that returns this class.
     * @hideconstructor
     */
    constructor(e) {
        this._methodName = e;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An immutable object representing a geographic location in Firestore. The
 * location is represented as latitude/longitude pair.
 *
 * Latitude values are in the range of [-90, 90].
 * Longitude values are in the range of [-180, 180].
 */ class GeoPoint {
    /**
     * Creates a new immutable `GeoPoint` object with the provided latitude and
     * longitude values.
     * @param latitude - The latitude as number between -90 and 90.
     * @param longitude - The longitude as number between -180 and 180.
     */
    constructor(e, t) {
        if (!isFinite(e) || e < -90 || e > 90) throw new s(aa.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + e);
        if (!isFinite(t) || t < -180 || t > 180) throw new s(aa.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + t);
        this._lat = e, this._long = t;
    }
    /**
     * The latitude of this `GeoPoint` instance.
     */    get latitude() {
        return this._lat;
    }
    /**
     * The longitude of this `GeoPoint` instance.
     */    get longitude() {
        return this._long;
    }
    /**
     * Returns true if this `GeoPoint` is equal to the provided one.
     *
     * @param other - The `GeoPoint` to compare against.
     * @returns true if this `GeoPoint` is equal to the provided one.
     */    isEqual(e) {
        return this._lat === e._lat && this._long === e._long;
    }
    /**
     * Actually private to JS consumers of our API, so this function is prefixed
     * with an underscore.
     */    _compareTo(e) {
        return __PRIVATE_primitiveComparator(this._lat, e._lat) || __PRIVATE_primitiveComparator(this._long, e._long);
    }
    /**
     * Returns a JSON-serializable representation of this `GeoPoint` instance.
     *
     * @returns a JSON representation of this object.
     */    toJSON() {
        return {
            latitude: this._lat,
            longitude: this._long,
            type: GeoPoint._jsonSchemaVersion
        };
    }
    /**
     * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.
     *
     * @param json - a JSON object represention of a `GeoPoint` instance
     * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a
     * {@link FirestoreError} if an error occurs.
     */    static fromJSON(e) {
        if (__PRIVATE_validateJSON(e, GeoPoint._jsonSchema)) return new GeoPoint(e.latitude, e.longitude);
    }
}

GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = {
    type: property("string", GeoPoint._jsonSchemaVersion),
    latitude: property("number"),
    longitude: property("number")
};

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Simple wrapper around a nullable UID. Mostly exists to make code more
 * readable.
 */
class User {
    constructor(e) {
        this.uid = e;
    }
    isAuthenticated() {
        return null != this.uid;
    }
    /**
     * Returns a key representing this user, suitable for inclusion in a
     * dictionary.
     */    toKey() {
        return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
    }
    isEqual(e) {
        return e.uid === this.uid;
    }
}

/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), 
// TODO(mikelehen): Look into getting a proper uid-equivalent for
// non-FirebaseAuth providers.
User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), 
User.MOCK_USER = new User("mock-user");

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class __PRIVATE_Deferred {
    constructor() {
        this.promise = new Promise(((e, t) => {
            this.resolve = e, this.reject = t;
        }));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_OAuthToken {
    constructor(e, t) {
        this.user = t, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${e}`);
    }
}

/**
 * A CredentialsProvider that always yields an empty token.
 * @internal
 */ class __PRIVATE_EmptyAuthCredentialsProvider {
    getToken() {
        return Promise.resolve(null);
    }
    invalidateToken() {}
    start(e, t) {
        // Fire with initial user.
        e.enqueueRetryable((() => t(User.UNAUTHENTICATED)));
    }
    shutdown() {}
}

/**
 * A CredentialsProvider that always returns a constant token. Used for
 * emulator token mocking.
 */ class __PRIVATE_EmulatorAuthCredentialsProvider {
    constructor(e) {
        this.token = e, 
        /**
         * Stores the listener registered with setChangeListener()
         * This isn't actually necessary since the UID never changes, but we use this
         * to verify the listen contract is adhered to in tests.
         */
        this.changeListener = null;
    }
    getToken() {
        return Promise.resolve(this.token);
    }
    invalidateToken() {}
    start(e, t) {
        this.changeListener = t, 
        // Fire with initial user.
        e.enqueueRetryable((() => t(this.token.user)));
    }
    shutdown() {
        this.changeListener = null;
    }
}

class __PRIVATE_FirebaseAuthCredentialsProvider {
    constructor(e) {
        this.Se = e, 
        /** Tracks the current User. */
        this.currentUser = User.UNAUTHENTICATED, 
        /**
         * Counter used to detect if the token changed while a getToken request was
         * outstanding.
         */
        this.De = 0, this.forceRefresh = false, this.auth = null;
    }
    start(e, t) {
        __PRIVATE_hardAssert(void 0 === this.xe, 42304);
        let n = this.De;
        // A change listener that prevents double-firing for the same token change.
                const __PRIVATE_guardedChangeListener = e => this.De !== n ? (n = this.De, 
        t(e)) : Promise.resolve();
        // A promise that can be waited on to block on the next token change.
        // This promise is re-created after each change.
                let r = new __PRIVATE_Deferred;
        this.xe = () => {
            this.De++, this.currentUser = this.Ce(), r.resolve(), r = new __PRIVATE_Deferred, 
            e.enqueueRetryable((() => __PRIVATE_guardedChangeListener(this.currentUser)));
        };
        const __PRIVATE_awaitNextToken = () => {
            const t = r;
            e.enqueueRetryable((async () => {
                await t.promise, await __PRIVATE_guardedChangeListener(this.currentUser);
            }));
        }, __PRIVATE_registerAuth = e => {
            __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = e, 
            this.xe && (this.auth.addAuthTokenListener(this.xe), __PRIVATE_awaitNextToken());
        };
        this.Se.onInit((e => __PRIVATE_registerAuth(e))), 
        // Our users can initialize Auth right after Firestore, so we give it
        // a chance to register itself with the component framework before we
        // determine whether to start up in unauthenticated mode.
        setTimeout((() => {
            if (!this.auth) {
                const e = this.Se.getImmediate({
                    optional: true
                });
                e ? __PRIVATE_registerAuth(e) : (
                // If auth is still not available, proceed with `null` user
                __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth not yet detected"), 
                r.resolve(), r = new __PRIVATE_Deferred);
            }
        }), 0), __PRIVATE_awaitNextToken();
    }
    getToken() {
        // Take note of the current value of the tokenCounter so that this method
        // can fail (with an ABORTED error) if there is a token change while the
        // request is outstanding.
        const e = this.De, t = this.forceRefresh;
        return this.forceRefresh = false, this.auth ? this.auth.getToken(t).then((t => 
        // Cancel the request since the token changed while the request was
        // outstanding so the response is potentially for a previous user (which
        // user, we can't be sure).
        this.De !== e ? (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."), 
        this.getToken()) : t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 31837, {
            Fe: t
        }), new __PRIVATE_OAuthToken(t.accessToken, this.currentUser)) : null)) : Promise.resolve(null);
    }
    invalidateToken() {
        this.forceRefresh = true;
    }
    shutdown() {
        this.auth && this.xe && this.auth.removeAuthTokenListener(this.xe), this.xe = void 0;
    }
    // Auth.getUid() can return null even with a user logged in. It is because
    // getUid() is synchronous, but the auth code populating Uid is asynchronous.
    // This method should only be called in the AuthTokenListener callback
    // to guarantee to get the actual user.
    Ce() {
        const e = this.auth && this.auth.getUid();
        return __PRIVATE_hardAssert(null === e || "string" == typeof e, 2055, {
            Oe: e
        }), new User(e);
    }
}

/*
 * FirstPartyToken provides a fresh token each time its value
 * is requested, because if the token is too old, requests will be rejected.
 * Technically this may no longer be necessary since the SDK should gracefully
 * recover from unauthenticated errors (see b/33147818 for context), but it's
 * safer to keep the implementation as-is.
 */ class __PRIVATE_FirstPartyToken {
    constructor(e, t, n) {
        this.Me = e, this.Ne = t, this.Le = n, this.type = "FirstParty", this.user = User.FIRST_PARTY, 
        this.Be = new Map;
    }
    /**
     * Gets an authorization token, using a provided factory function, or return
     * null.
     */    Ue() {
        return this.Le ? this.Le() : null;
    }
    get headers() {
        this.Be.set("X-Goog-AuthUser", this.Me);
        // Use array notation to prevent minification
        const e = this.Ue();
        return e && this.Be.set("Authorization", e), this.Ne && this.Be.set("X-Goog-Iam-Authorization-Token", this.Ne), 
        this.Be;
    }
}

/*
 * Provides user credentials required for the Firestore JavaScript SDK
 * to authenticate the user, using technique that is only available
 * to applications hosted by Google.
 */ class __PRIVATE_FirstPartyAuthCredentialsProvider {
    constructor(e, t, n) {
        this.Me = e, this.Ne = t, this.Le = n;
    }
    getToken() {
        return Promise.resolve(new __PRIVATE_FirstPartyToken(this.Me, this.Ne, this.Le));
    }
    start(e, t) {
        // Fire with initial uid.
        e.enqueueRetryable((() => t(User.FIRST_PARTY)));
    }
    shutdown() {}
    invalidateToken() {}
}

class AppCheckToken {
    constructor(e) {
        this.value = e, this.type = "AppCheck", this.headers = new Map, e && e.length > 0 && this.headers.set("x-firebase-appcheck", this.value);
    }
}

class __PRIVATE_FirebaseAppCheckTokenProvider {
    constructor(e, t) {
        this.ke = t, this.forceRefresh = false, this.appCheck = null, this.qe = null, this.$e = null, 
        app._isFirebaseServerApp(e) && e.settings.appCheckToken && (this.$e = e.settings.appCheckToken);
    }
    start(e, t) {
        __PRIVATE_hardAssert(void 0 === this.xe, 3512);
        const onTokenChanged = e => {
            null != e.error && __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);
            const n = e.token !== this.qe;
            return this.qe = e.token, __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`), 
            n ? t(e.token) : Promise.resolve();
        };
        this.xe = t => {
            e.enqueueRetryable((() => onTokenChanged(t)));
        };
        const __PRIVATE_registerAppCheck = e => {
            __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = e, 
            this.xe && this.appCheck.addTokenListener(this.xe);
        };
        this.ke.onInit((e => __PRIVATE_registerAppCheck(e))), 
        // Our users can initialize AppCheck after Firestore, so we give it
        // a chance to register itself with the component framework.
        setTimeout((() => {
            if (!this.appCheck) {
                const e = this.ke.getImmediate({
                    optional: true
                });
                e ? __PRIVATE_registerAppCheck(e) : 
                // If AppCheck is still not available, proceed without it.
                __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck not yet detected");
            }
        }), 0);
    }
    getToken() {
        if (this.$e) return Promise.resolve(new AppCheckToken(this.$e));
        const e = this.forceRefresh;
        return this.forceRefresh = false, this.appCheck ? this.appCheck.getToken(e).then((e => e ? (__PRIVATE_hardAssert("string" == typeof e.token, 44558, {
            tokenResult: e
        }), this.qe = e.token, new AppCheckToken(e.token)) : null)) : Promise.resolve(null);
    }
    invalidateToken() {
        this.forceRefresh = true;
    }
    shutdown() {
        this.appCheck && this.xe && this.appCheck.removeTokenListener(this.xe), this.xe = void 0;
    }
}

/**
 * An AppCheck token provider that always yields an empty token.
 * @internal
 */ class __PRIVATE_EmptyAppCheckTokenProvider {
    getToken() {
        return Promise.resolve(new AppCheckToken(""));
    }
    invalidateToken() {}
    start(e, t) {}
    shutdown() {}
}

/**
 * Builds a CredentialsProvider depending on the type of
 * the credentials passed in.
 */
/**
 * Creates and returns a new `ExperimentalLongPollingOptions` with the same
 * option values as the given instance.
 */
function __PRIVATE_cloneLongPollingOptions(e) {
    const t = {};
    return void 0 !== e.timeoutSeconds && (t.timeoutSeconds = e.timeoutSeconds), t;
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_NoopConnectivityMonitor {
    Ke(e) {
        // No-op.
    }
    shutdown() {
        // No-op.
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()
/* eslint-disable no-restricted-globals */ const ht = "ConnectivityMonitor";

/**
 * Browser implementation of ConnectivityMonitor.
 */ class __PRIVATE_BrowserConnectivityMonitor {
    constructor() {
        this.We = () => this.Qe(), this.Ge = () => this.ze(), this.je = [], this.He();
    }
    Ke(e) {
        this.je.push(e);
    }
    shutdown() {
        window.removeEventListener("online", this.We), window.removeEventListener("offline", this.Ge);
    }
    He() {
        window.addEventListener("online", this.We), window.addEventListener("offline", this.Ge);
    }
    Qe() {
        __PRIVATE_logDebug(ht, "Network connectivity changed: AVAILABLE");
        for (const e of this.je) e(0 /* NetworkStatus.AVAILABLE */);
    }
    ze() {
        __PRIVATE_logDebug(ht, "Network connectivity changed: UNAVAILABLE");
        for (const e of this.je) e(1 /* NetworkStatus.UNAVAILABLE */);
    }
    // TODO(chenbrian): Consider passing in window either into this component or
    // here for testing via FakeWindow.
    /** Checks that all used attributes of window are available. */
    static Je() {
        return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
    }
}

/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The value returned from the most recent invocation of
 * `generateUniqueDebugId()`, or null if it has never been invoked.
 */ let Tt = null;

/**
 * Generates and returns an initial value for `lastUniqueDebugId`.
 *
 * The returned value is randomly selected from a range of integers that are
 * represented as 8 hexadecimal digits. This means that (within reason) any
 * numbers generated by incrementing the returned number by 1 will also be
 * represented by 8 hexadecimal digits. This leads to all "IDs" having the same
 * length when converted to a hexadecimal string, making reading logs containing
 * these IDs easier to follow. And since the return value is randomly selected
 * it will help to differentiate between logs from different executions.
 */
/**
 * Generates and returns a unique ID as a hexadecimal string.
 *
 * The returned ID is intended to be used in debug logging messages to help
 * correlate log messages that may be spatially separated in the logs, but
 * logically related. For example, a network connection could include the same
 * "debug ID" string in all of its log messages to help trace a specific
 * connection over time.
 *
 * @returns the 10-character generated ID (e.g. "0xa1b2c3d4").
 */
function __PRIVATE_generateUniqueDebugId() {
    return null === Tt ? Tt = function __PRIVATE_generateInitialUniqueDebugId() {
        return 268435456 + Math.round(2147483648 * Math.random());
    }() : Tt++, "0x" + Tt.toString(16);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const Pt = "RestConnection", Rt = {
    BatchGetDocuments: "batchGet",
    Commit: "commit",
    RunQuery: "runQuery",
    RunAggregationQuery: "runAggregationQuery",
    ExecutePipeline: "executePipeline"
};

/**
 * Maps RPC names to the corresponding REST endpoint name.
 *
 * We use array notation to avoid mangling.
 */
/**
 * Base class for all Rest-based connections to the backend (WebChannel and
 * HTTP).
 */
class __PRIVATE_RestConnection {
    get Ye() {
        // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine
        // where to run the query, and expect the `request` to NOT specify the "path".
        return false;
    }
    constructor(e) {
        this.databaseInfo = e, this.databaseId = e.databaseId;
        const t = e.ssl ? "https" : "http", n = encodeURIComponent(this.databaseId.projectId), r = encodeURIComponent(this.databaseId.database);
        this.Ze = t + "://" + e.host, this.Xe = `projects/${n}/databases/${r}`, this.et = this.databaseId.database === $e ? `project_id=${n}` : `project_id=${n}&database_id=${r}`;
    }
    tt(e, t, n, r, i) {
        const s = __PRIVATE_generateUniqueDebugId(), _ = this.nt(e, t.toUriEncodedString());
        __PRIVATE_logDebug(Pt, `Sending RPC '${e}' ${s}:`, _, n);
        const o = {
            "google-cloud-resource-prefix": this.Xe,
            "x-goog-request-params": this.et
        };
        this.rt(o, r, i);
        const {host: a} = new URL(_), u = util.isCloudWorkstation(a);
        return this.it(e, _, o, n, u).then((t => (__PRIVATE_logDebug(Pt, `Received RPC '${e}' ${s}: `, t), 
        t)), (t => {
            throw __PRIVATE_logWarn(Pt, `RPC '${e}' ${s} failed with error: `, t, "url: ", _, "request:", n), 
            t;
        }));
    }
    st(e, t, n, r, i, s) {
        // The REST API automatically aggregates all of the streamed results, so we
        // can just use the normal invoke() method.
        return this.tt(e, t, n, r, i);
    }
    /**
     * Modifies the headers for a request, adding any authorization token if
     * present and any additional headers for the request.
     */    rt(e, t, n) {
        if (e["X-Goog-Api-Client"] = 
        // SDK_VERSION is updated to different value at runtime depending on the entry point,
        // so we need to get its value when we need it in a function.
        function __PRIVATE_getGoogApiClientValue() {
            return "gl-js/ fire/" + ve;
        }(), 
        // Content-Type: text/plain will avoid preflight requests which might
        // mess with CORS and redirects by proxies. If we add custom headers
        // we will need to change this code to potentially use the $httpOverwrite
        // parameter supported by ESF to avoid triggering preflight requests.
        e["Content-Type"] = "text/plain", this.databaseInfo.appId && (e["X-Firebase-GMPID"] = this.databaseInfo.appId), 
        t && t.headers.forEach(((t, n) => e[n] = t)), n && n.headers.forEach(((t, n) => e[n] = t)), 
        this.databaseInfo._customHeaders) for (const t of Object.keys(this.databaseInfo._customHeaders)) e[t] = this.databaseInfo._customHeaders[t];
    }
    nt(e, t) {
        const n = Rt[e];
        let r = `${this.Ze}/v1/${t}:${n}`;
        return this.databaseInfo.apiKey && (r = `${r}?key=${encodeURIComponent(this.databaseInfo.apiKey)}`), 
        r;
    }
    /**
     * Closes and cleans up any resources associated with the connection. This
     * implementation is a no-op because there are no resources associated
     * with the RestConnection that need to be cleaned up.
     */    terminate() {
        // No-op
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Provides a simple helper class that implements the Stream interface to
 * bridge to other implementations that are streams but do not implement the
 * interface. The stream callbacks are invoked with the callOn... methods.
 */ class __PRIVATE_StreamBridge {
    constructor(e) {
        this._t = e._t, this.ot = e.ot;
    }
    ut(e) {
        this.ct = e;
    }
    lt(e) {
        this.Et = e;
    }
    ht(e) {
        this.Tt = e;
    }
    onMessage(e) {
        this.Pt = e;
    }
    close() {
        this.ot();
    }
    send(e) {
        this._t(e);
    }
    Rt() {
        this.ct();
    }
    It() {
        this.Et();
    }
    At(e) {
        this.Tt(e);
    }
    Vt(e) {
        this.Pt(e);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const It = "WebChannelConnection", __PRIVATE_unguardedEventListen = (e, t, n) => {
    // TODO(dimond): closure typing seems broken because WebChannel does
    // not implement goog.events.Listenable
    e.listen(t, (e => {
        try {
            n(e);
        } catch (e) {
            setTimeout((() => {
                throw e;
            }), 0);
        }
    }));
};

class __PRIVATE_WebChannelConnection extends __PRIVATE_RestConnection {
    constructor(e) {
        super(e), 
        /** A collection of open WebChannel instances */
        this.dt = [], this.forceLongPolling = e.forceLongPolling, this.autoDetectLongPolling = e.autoDetectLongPolling, 
        this.useFetchStreams = e.useFetchStreams, this.longPollingOptions = e.longPollingOptions;
    }
    /**
     * Initialize STAT_EVENT listener once. Subsequent calls are a no-op.
     * getStatEventTarget() returns the same target every time.
     */    static ft() {
        if (!__PRIVATE_WebChannelConnection.gt) {
            const e = webchannelBlob.getStatEventTarget();
            __PRIVATE_unguardedEventListen(e, webchannelBlob.Event.STAT_EVENT, (e => {
                e.stat === webchannelBlob.Stat.PROXY ? __PRIVATE_logDebug(It, "STAT_EVENT: detected buffering proxy") : e.stat === webchannelBlob.Stat.NOPROXY && __PRIVATE_logDebug(It, "STAT_EVENT: detected no buffering proxy");
            })), __PRIVATE_WebChannelConnection.gt = true;
        }
    }
    it(e, t, n, r, i) {
        const _ = __PRIVATE_generateUniqueDebugId();
        return new Promise(((i, o) => {
            const a = new webchannelBlob.XhrIo;
            a.setWithCredentials(true), a.listenOnce(webchannelBlob.EventType.COMPLETE, (() => {
                try {
                    switch (a.getLastErrorCode()) {
                      case webchannelBlob.ErrorCode.NO_ERROR:
                        const t = a.getResponseJson();
                        __PRIVATE_logDebug(It, `XHR for RPC '${e}' ${_} received:`, JSON.stringify(t)), 
                        i(t);
                        break;

                      case webchannelBlob.ErrorCode.TIMEOUT:
                        __PRIVATE_logDebug(It, `RPC '${e}' ${_} timed out`), o(new s(aa.DEADLINE_EXCEEDED, "Request time out"));
                        break;

                      case webchannelBlob.ErrorCode.HTTP_ERROR:
                        const n = a.getStatus();
                        if (__PRIVATE_logDebug(It, `RPC '${e}' ${_} failed with status:`, n, "response text:", a.getResponseText()), 
                        n > 0) {
                            let e = a.getResponseJson();
                            Array.isArray(e) && (e = e[0]);
                            const t = e?.error;
                            if (t && t.status && t.message) {
                                const e = function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e) {
                                    const t = e.toLowerCase().replace(/_/g, "-");
                                    return Object.values(aa).indexOf(t) >= 0 ? t : aa.UNKNOWN;
                                }(t.status);
                                o(new s(e, t.message));
                            } else o(new s(aa.UNKNOWN, "Server responded with status " + a.getStatus()));
                        } else 
                        // If we received an HTTP_ERROR but there's no status code,
                        // it's most probably a connection issue
                        o(new s(aa.UNAVAILABLE, "Connection failed."));
                        break;

                      default:
                        l(9055, {
                            yt: e,
                            streamId: _,
                            wt: a.getLastErrorCode(),
                            bt: a.getLastError()
                        });
                    }
                } finally {
                    __PRIVATE_logDebug(It, `RPC '${e}' ${_} completed.`);
                }
            }));
            const u = JSON.stringify(r);
            __PRIVATE_logDebug(It, `RPC '${e}' ${_} sending request:`, r), a.send(t, "POST", u, n, 15);
        }));
    }
    vt(e, t, n) {
        const r = __PRIVATE_generateUniqueDebugId(), i = [ this.Ze, "/", "google.firestore.v1.Firestore", "/", e, "/channel" ], _ = this.createWebChannelTransport(), o = {
            // Required for backend stickiness, routing behavior is based on this
            // parameter.
            httpSessionIdParam: "gsessionid",
            initMessageHeaders: {},
            messageUrlParams: {
                // This param is used to improve routing and project isolation by the
                // backend and must be included in every request.
                database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`
            },
            sendRawJson: true,
            supportsCrossDomainXhr: true,
            internalChannelParams: {
                // Override the default timeout (randomized between 10-20 seconds) since
                // a large write batch on a slow internet connection may take a long
                // time to send to the backend. Rather than have WebChannel impose a
                // tight timeout which could lead to infinite timeouts and retries, we
                // set it very large (5-10 minutes) and rely on the browser's builtin
                // timeouts to kick in if the request isn't working.
                forwardChannelRequestTimeoutMs: 6e5
            },
            forceLongPolling: this.forceLongPolling,
            detectBufferingProxy: this.autoDetectLongPolling
        }, a = this.longPollingOptions.timeoutSeconds;
        void 0 !== a && (o.longPollingTimeout = Math.round(1e3 * a)), this.useFetchStreams && (o.useFetchStreams = true), 
        this.rt(o.initMessageHeaders, t, n), 
        // Sending the custom headers we just added to request.initMessageHeaders
        // (Authorization, etc.) will trigger the browser to make a CORS preflight
        // request because the XHR will no longer meet the criteria for a "simple"
        // CORS request:
        // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests
        // Therefore to avoid the CORS preflight request (an extra network
        // roundtrip), we use the encodeInitMessageHeaders option to specify that
        // the headers should instead be encoded in the request's POST payload,
        // which is recognized by the webchannel backend.
        o.encodeInitMessageHeaders = true;
        const u = i.join("");
        __PRIVATE_logDebug(It, `Creating RPC '${e}' stream ${r}: ${u}`, o);
        const c = _.createWebChannel(u, o);
        this.St(c);
        // WebChannel supports sending the first message with the handshake - saving
        // a network round trip. However, it will have to call send in the same
        // JS event loop as open. In order to enforce this, we delay actually
        // opening the WebChannel until send is called. Whether we have called
        // open is tracked with this variable.
        let l = false, E = false;
        // A flag to determine whether the stream was closed (by us or through an
        // error/close event) to avoid delivering multiple close events or sending
        // on a closed stream
                const h = new __PRIVATE_StreamBridge({
            _t: t => {
                E ? __PRIVATE_logDebug(It, `Not sending because RPC '${e}' stream ${r} is closed:`, t) : (l || (__PRIVATE_logDebug(It, `Opening RPC '${e}' stream ${r} transport.`), 
                c.open(), l = true), __PRIVATE_logDebug(It, `RPC '${e}' stream ${r} sending:`, t), 
                c.send(t));
            },
            ot: () => c.close()
        });
        return __PRIVATE_unguardedEventListen(c, webchannelBlob.WebChannel.EventType.OPEN, (() => {
            E || (__PRIVATE_logDebug(It, `RPC '${e}' stream ${r} transport opened.`), h.Rt());
        })), __PRIVATE_unguardedEventListen(c, webchannelBlob.WebChannel.EventType.CLOSE, (() => {
            E || (E = !0, __PRIVATE_logDebug(It, `RPC '${e}' stream ${r} transport closed`), 
            h.At(), this.Dt(c));
        })), __PRIVATE_unguardedEventListen(c, webchannelBlob.WebChannel.EventType.ERROR, (t => {
            E || (E = !0, __PRIVATE_logWarn(It, `RPC '${e}' stream ${r} transport errored. Name:`, t.name, "Message:", t.message), 
            h.At(new s(aa.UNAVAILABLE, "The operation could not be completed")));
        })), __PRIVATE_unguardedEventListen(c, webchannelBlob.WebChannel.EventType.MESSAGE, (t => {
            if (!E) {
                const n = t.data[0];
                __PRIVATE_hardAssert(!!n, 16349);
                // TODO(b/35143891): There is a bug in One Platform that caused errors
                // (and only errors) to be wrapped in an extra array. To be forward
                // compatible with the bug we need to check either condition. The latter
                // can be removed once the fix has been rolled out.
                // Use any because msgData.error is not typed.
                const i = n, _ = i?.error || i[0]?.error;
                if (_) {
                    __PRIVATE_logDebug(It, `RPC '${e}' stream ${r} received error:`, _);
                    // error.status will be a string like 'OK' or 'NOT_FOUND'.
                    const t = _.status;
                    let n = 
                    /**
 * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.
 *
 * @returns The Code equivalent to the given status string or undefined if
 *     there is no match.
 */
                    function __PRIVATE_mapCodeFromRpcStatus(e) {
                        // lookup by string
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        const t = et[e];
                        if (void 0 !== t) return __PRIVATE_mapCodeFromRpcCode(t);
                    }(t), i = _.message;
                    "NOT_FOUND" === t && i.includes("database") && i.includes("does not exist") && i.includes(this.databaseId.database) && __PRIVATE_logWarn(`Database '${this.databaseId.database}' not found. Please check your project configuration.`), 
                    void 0 === n && (n = aa.INTERNAL, i = "Unknown error status: " + t + " with message " + _.message), 
                    // Mark closed so no further events are propagated
                    E = !0, h.At(new s(n, i)), c.close();
                } else __PRIVATE_logDebug(It, `RPC '${e}' stream ${r} received:`, n), h.Vt(n);
            }
        })), 
        // Ensure that event listeners are configured for STAT_EVENTs.
        __PRIVATE_WebChannelConnection.ft(), setTimeout((() => {
            // Technically we could/should wait for the WebChannel opened event,
            // but because we want to send the first message with the WebChannel
            // handshake we pretend the channel opened here (asynchronously), and
            // then delay the actual open until the first message is sent.
            h.It();
        }), 0), h;
    }
    /**
     * Closes and cleans up any resources associated with the connection.
     */    terminate() {
        // If the Firestore instance is terminated, we will explicitly
        // close any remaining open WebChannel instances.
        this.dt.forEach((e => e.close())), this.dt = [];
    }
    /**
     * Add a WebChannel instance to the collection of open instances.
     * @param webChannel
     */    St(e) {
        this.dt.push(e);
    }
    /**
     * Remove a WebChannel instance from the collection of open instances.
     * @param webChannel
     */    Dt(e) {
        this.dt = this.dt.filter((t => t === e));
    }
    /**
     * Modifies the headers for a request, adding the api key if present,
     * and then calling super.modifyHeadersForRequest
     */    rt(e, t, n) {
        super.rt(e, t, n), 
        // For web channel streams, we want to send the api key in the headers.
        this.databaseInfo.apiKey && (e["x-goog-api-key"] = this.databaseInfo.apiKey);
    }
    /**
     * Wrapped for mocking.
     * @protected
     */    createWebChannelTransport() {
        return webchannelBlob.createWebChannelTransport();
    }
}

/**
 * Track if the STAT_EVENT listener has been initialized.
 */
/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Initializes the WebChannelConnection for the browser. */
function __PRIVATE_newConnection(e) {
    return new __PRIVATE_WebChannelConnection(e);
}

/** Return the Platform-specific connectivity monitor. */ __PRIVATE_WebChannelConnection.gt = false;

/**
 * A helper for running delayed tasks following an exponential backoff curve
 * between attempts.
 *
 * Each delay is made up of a "base" delay which follows the exponential
 * backoff curve, and a +/- 50% "jitter" that is calculated and added to the
 * base delay. This prevents clients from accidentally synchronizing their
 * delays causing spikes of load to the backend.
 */
class __PRIVATE_ExponentialBackoff {
    constructor(
    /**
     * The AsyncQueue to run backoff operations on.
     */
    e, 
    /**
     * The ID to use when scheduling backoff operations on the AsyncQueue.
     */
    t, 
    /**
     * The initial delay (used as the base delay on the first retry attempt).
     * Note that jitter will still be applied, so the actual delay could be as
     * little as 0.5*initialDelayMs.
     */
    n = 1e3
    /**
     * The multiplier to use to determine the extended base delay after each
     * attempt.
     */ , r = 1.5
    /**
     * The maximum base delay after which no further backoff is performed.
     * Note that jitter will still be applied, so the actual delay could be as
     * much as 1.5*maxDelayMs.
     */ , i = 6e4) {
        this.xt = e, this.timerId = t, this.Ct = n, this.Ft = r, this.Ot = i, this.Mt = 0, 
        this.Nt = null, 
        /** The last backoff attempt, as epoch milliseconds. */
        this.Lt = Date.now(), this.reset();
    }
    /**
     * Resets the backoff delay.
     *
     * The very next backoffAndWait() will have no delay. If it is called again
     * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and
     * subsequent ones will increase according to the backoffFactor.
     */    reset() {
        this.Mt = 0;
    }
    /**
     * Resets the backoff delay to the maximum delay (e.g. for use after a
     * RESOURCE_EXHAUSTED error).
     */    Bt() {
        this.Mt = this.Ot;
    }
    /**
     * Returns a promise that resolves after currentDelayMs, and increases the
     * delay for any subsequent attempts. If there was a pending backoff operation
     * already, it will be canceled.
     */    Ut(e) {
        // Cancel any pending backoff operation.
        this.cancel();
        // First schedule using the current base (which may be 0 and should be
        // honored as such).
        const t = Math.floor(this.Mt + this.kt()), n = Math.max(0, Date.now() - this.Lt), r = Math.max(0, t - n);
        // Guard against lastAttemptTime being in the future due to a clock change.
                r > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${r} ms (base delay: ${this.Mt} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`), 
        this.Nt = this.xt.enqueueAfterDelay(this.timerId, r, (() => (this.Lt = Date.now(), 
        e()))), 
        // Apply backoff factor to determine next delay and ensure it is within
        // bounds.
        this.Mt *= this.Ft, this.Mt < this.Ct && (this.Mt = this.Ct), this.Mt > this.Ot && (this.Mt = this.Ot);
    }
    qt() {
        null !== this.Nt && (this.Nt.skipDelay(), this.Nt = null);
    }
    cancel() {
        null !== this.Nt && (this.Nt.cancel(), this.Nt = null);
    }
    /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */    kt() {
        return (Math.random() - .5) * this.Mt;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const At = "PersistentStream";

/** The time a stream stays open after it is marked idle. */
/**
 * A PersistentStream is an abstract base class that represents a streaming RPC
 * to the Firestore backend. It's built on top of the connections own support
 * for streaming RPCs, and adds several critical features for our clients:
 *
 *   - Exponential backoff on failure
 *   - Authentication via CredentialsProvider
 *   - Dispatching all callbacks into the shared worker queue
 *   - Closing idle streams after 60 seconds of inactivity
 *
 * Subclasses of PersistentStream implement serialization of models to and
 * from the JSON representation of the protocol buffers for a specific
 * streaming RPC.
 *
 * ## Starting and Stopping
 *
 * Streaming RPCs are stateful and need to be start()ed before messages can
 * be sent and received. The PersistentStream will call the onOpen() function
 * of the listener once the stream is ready to accept requests.
 *
 * Should a start() fail, PersistentStream will call the registered onClose()
 * listener with a FirestoreError indicating what went wrong.
 *
 * A PersistentStream can be started and stopped repeatedly.
 *
 * Generic types:
 *  SendType: The type of the outgoing message of the underlying
 *    connection stream
 *  ReceiveType: The type of the incoming message of the underlying
 *    connection stream
 *  ListenerType: The type of the listener that will be used for callbacks
 */
class __PRIVATE_PersistentStream {
    constructor(e, t, n, r, i, s, _, o) {
        this.xt = e, this.$t = n, this.Kt = r, this.connection = i, this.authCredentialsProvider = s, 
        this.appCheckCredentialsProvider = _, this.listener = o, this.state = 0 /* PersistentStreamState.Initial */ , 
        /**
         * A close count that's incremented every time the stream is closed; used by
         * getCloseGuardedDispatcher() to invalidate callbacks that happen after
         * close.
         */
        this.Wt = 0, this.Qt = null, this.Gt = null, this.stream = null, 
        /**
         * Count of response messages received.
         */
        this.zt = 0, this.jt = new __PRIVATE_ExponentialBackoff(e, t);
    }
    /**
     * Returns true if start() has been called and no error has occurred. True
     * indicates the stream is open or in the process of opening (which
     * encompasses respecting backoff, getting auth tokens, and starting the
     * actual RPC). Use isOpen() to determine if the stream is open and ready for
     * outbound requests.
     */    Ht() {
        return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.Jt();
    }
    /**
     * Returns true if the underlying RPC is open (the onOpen() listener has been
     * called) and the stream is ready for outbound requests.
     */    Jt() {
        return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;
    }
    /**
     * Starts the RPC. Only allowed if isStarted() returns false. The stream is
     * not immediately ready for use: onOpen() will be invoked when the RPC is
     * ready for outbound requests, at which point isOpen() will return true.
     *
     * When start returns, isStarted() will return true.
     */    start() {
        this.zt = 0, 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Yt();
    }
    /**
     * Stops the RPC. This call is idempotent and allowed regardless of the
     * current isStarted() state.
     *
     * When stop returns, isStarted() and isOpen() will both return false.
     */    async stop() {
        this.Ht() && await this.close(0 /* PersistentStreamState.Initial */);
    }
    /**
     * After an error the stream will usually back off on the next attempt to
     * start it. If the error warrants an immediate restart of the stream, the
     * sender can use this to indicate that the receiver should not back off.
     *
     * Each error will call the onClose() listener. That function can decide to
     * inhibit backoff if required.
     */    Zt() {
        this.state = 0 /* PersistentStreamState.Initial */ , this.jt.reset();
    }
    /**
     * Marks this stream as idle. If no further actions are performed on the
     * stream for one minute, the stream will automatically close itself and
     * notify the stream's onClose() handler with Status.OK. The stream will then
     * be in a !isStarted() state, requiring the caller to start the stream again
     * before further use.
     *
     * Only streams that are in state 'Open' can be marked idle, as all other
     * states imply pending network operations.
     */    Xt() {
        // Starts the idle time if we are in state 'Open' and are not yet already
        // running a timer (in which case the previous idle timeout still applies).
        this.Jt() && null === this.Qt && (this.Qt = this.xt.enqueueAfterDelay(this.$t, 6e4, (() => this.en())));
    }
    /** Sends a message to the underlying stream. */    tn(e) {
        this.nn(), this.stream.send(e);
    }
    /** Called by the idle timer when the stream should close due to inactivity. */    async en() {
        if (this.Jt()) 
        // When timing out an idle stream there's no reason to force the stream into backoff when
        // it restarts so set the stream state to Initial instead of Error.
        return this.close(0 /* PersistentStreamState.Initial */);
    }
    /** Marks the stream as active again. */    nn() {
        this.Qt && (this.Qt.cancel(), this.Qt = null);
    }
    /** Cancels the health check delayed operation. */    rn() {
        this.Gt && (this.Gt.cancel(), this.Gt = null);
    }
    /**
     * Closes the stream and cleans up as necessary:
     *
     * * closes the underlying GRPC stream;
     * * calls the onClose handler with the given 'error';
     * * sets internal stream state to 'finalState';
     * * adjusts the backoff timer based on the error
     *
     * A new stream can be opened by calling start().
     *
     * @param finalState - the intended state of the stream after closing.
     * @param error - the error the connection was closed with.
     */    async close(e, t) {
        // Cancel any outstanding timers (they're guaranteed not to execute).
        this.nn(), this.rn(), this.jt.cancel(), 
        // Invalidates any stream-related callbacks (e.g. from auth or the
        // underlying stream), guaranteeing they won't execute.
        this.Wt++, 4 /* PersistentStreamState.Error */ !== e ? 
        // If this is an intentional close ensure we don't delay our next connection attempt.
        this.jt.reset() : t && t.code === aa.RESOURCE_EXHAUSTED ? (
        // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
        __PRIVATE_logError(t.toString()), __PRIVATE_logError("Using maximum backoff delay to prevent overloading the backend."), 
        this.jt.Bt()) : t && t.code === aa.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (
        // "unauthenticated" error means the token was rejected. This should rarely
        // happen since both Auth and AppCheck ensure a sufficient TTL when we
        // request a token. If a user manually resets their system clock this can
        // fail, however. In this case, we should get a Code.UNAUTHENTICATED error
        // before we received the first message and we need to invalidate the token
        // to ensure that we fetch a new token.
        this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), 
        // Clean up the underlying stream because we are no longer interested in events.
        null !== this.stream && (this.sn(), this.stream.close(), this.stream = null), 
        // This state must be assigned before calling onClose() to allow the callback to
        // inhibit backoff or otherwise manipulate the state in its non-started state.
        this.state = e, 
        // Notify the listener that the stream closed.
        await this.listener.ht(t);
    }
    /**
     * Can be overridden to perform additional cleanup before the stream is closed.
     * Calling super.tearDown() is not required.
     */    sn() {}
    auth() {
        this.state = 1 /* PersistentStreamState.Starting */;
        const e = this._n(this.Wt), t = this.Wt;
        // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
                Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([e, n]) => {
            // Stream can be stopped while waiting for authentication.
            // TODO(mikelehen): We really should just use dispatchIfNotClosed
            // and let this dispatch onto the queue, but that opened a spec test can
            // of worms that I don't want to deal with in this PR.
            this.Wt === t && 
            // Normally we'd have to schedule the callback on the AsyncQueue.
            // However, the following calls are safe to be called outside the
            // AsyncQueue since they don't chain asynchronous calls
            this.an(e, n);
        }), (t => {
            e((() => {
                const e = new s(aa.UNKNOWN, "Fetching auth token failed: " + t.message);
                return this.un(e);
            }));
        }));
    }
    an(e, t) {
        const n = this._n(this.Wt);
        this.stream = this.cn(e, t), this.stream.ut((() => {
            n((() => this.listener.ut()));
        })), this.stream.lt((() => {
            n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Gt = this.xt.enqueueAfterDelay(this.Kt, 1e4, (() => (this.Jt() && (this.state = 3 /* PersistentStreamState.Healthy */), 
            Promise.resolve()))), this.listener.lt())));
        })), this.stream.ht((e => {
            n((() => this.un(e)));
        })), this.stream.onMessage((e => {
            n((() => 1 == ++this.zt ? this.En(e) : this.onNext(e)));
        }));
    }
    Yt() {
        this.state = 5 /* PersistentStreamState.Backoff */ , this.jt.Ut((async () => {
            this.state = 0 /* PersistentStreamState.Initial */ , this.start();
        }));
    }
    // Visible for tests
    un(e) {
        // In theory the stream could close cleanly, however, in our current model
        // we never expect this to happen because if we stop a stream ourselves,
        // this callback will never be called. To prevent cases where we retry
        // without a backoff accidentally, we set the stream to error in all cases.
        return __PRIVATE_logDebug(At, `close with error: ${e}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , e);
    }
    /**
     * Returns a "dispatcher" function that dispatches operations onto the
     * AsyncQueue but only runs them if closeCount remains unchanged. This allows
     * us to turn auth / stream callbacks into no-ops if the stream is closed /
     * re-opened, etc.
     */    _n(e) {
        return t => {
            this.xt.enqueueAndForget((() => this.Wt === e ? t() : (__PRIVATE_logDebug(At, "stream callback skipped by getCloseGuardedDispatcher."), 
            Promise.resolve())));
        };
    }
}

/**
 * A PersistentStream that implements the Listen RPC.
 *
 * Once the Listen stream has called the onOpen() listener, any number of
 * listen() and unlisten() calls can be made to control what changes will be
 * sent from the server for ListenResponses.
 */ class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream {
    constructor(e, t, n, r, i, s) {
        super(e, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , t, n, r, s), 
        this.serializer = i;
    }
    cn(e, t) {
        return this.connection.vt("Listen", e, t);
    }
    En(e) {
        return this.onNext(e);
    }
    onNext(e) {
        // A successful response means the stream is healthy
        this.jt.reset();
        const t = __PRIVATE_fromWatchChange(this.serializer, e), n = function __PRIVATE_versionFromListenResponse(e) {
            // We have only reached a consistent snapshot for the entire stream if there
            // is a read_time set and it applies to all targets (i.e. the list of
            // targets is empty). The backend is guaranteed to send such responses.
            if (!("targetChange" in e)) return SnapshotVersion.min();
            const t = e.targetChange;
            return t.targetIds && t.targetIds.length ? SnapshotVersion.min() : t.readTime ? __PRIVATE_fromVersion(t.readTime) : SnapshotVersion.min();
        }(e);
        return this.listener.hn(t, n);
    }
    /**
     * Registers interest in the results of the given target. If the target
     * includes a resumeToken it will be included in the request. Results that
     * affect the target will be streamed back as WatchChange messages that
     * reference the targetId.
     */    Tn(e) {
        const t = {};
        t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.addTarget = function __PRIVATE_toTarget(e, t) {
            let n;
            const r = t.target;
            if (n = __PRIVATE_targetIsPipelineTarget(r) ? {
                pipelineQuery: __PRIVATE_toPipelineTarget(e, r)
            } : __PRIVATE_targetIsDocumentTarget(r) ? {
                documents: __PRIVATE_toDocumentsTarget(e, r)
            } : {
                query: __PRIVATE_toQueryTarget(e, r).be
            }, n.targetId = t.targetId, t.resumeToken.approximateByteSize() > 0) {
                n.resumeToken = __PRIVATE_toBytes(e, t.resumeToken);
                const r = __PRIVATE_toInt32Proto(e, t.expectedCount);
                null !== r && (n.expectedCount = r);
            } else if (t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {
                // TODO(wuandy): Consider removing above check because it is most likely true.
                // Right now, many tests depend on this behaviour though (leaving min() out
                // of serialization).
                n.readTime = toTimestamp(e, t.snapshotVersion.toTimestamp());
                const r = __PRIVATE_toInt32Proto(e, t.expectedCount);
                null !== r && (n.expectedCount = r);
            }
            return n;
        }(this.serializer, e);
        const n = __PRIVATE_toListenRequestLabels(this.serializer, e);
        n && (t.labels = n), this.tn(t);
    }
    /**
     * Unregisters interest in the results of the target associated with the
     * given targetId.
     */    Pn(e) {
        const t = {};
        t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.removeTarget = e, 
        this.tn(t);
    }
}

/**
 * A Stream that implements the Write RPC.
 *
 * The Write RPC requires the caller to maintain special streamToken
 * state in between calls, to help the server understand which responses the
 * client has processed by the time the next request is made. Every response
 * will contain a streamToken; this value must be passed to the next
 * request.
 *
 * After calling start() on this stream, the next request must be a handshake,
 * containing whatever streamToken is on hand. Once a response to this
 * request is received, all pending mutations may be submitted. When
 * submitting multiple batches of mutations at the same time, it's
 * okay to use the same streamToken for the calls to writeMutations.
 *
 * TODO(b/33271235): Use proto types
 */ class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream {
    constructor(e, t, n, r, i, s) {
        super(e, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , t, n, r, s), 
        this.serializer = i;
    }
    /**
     * Tracks whether or not a handshake has been successfully exchanged and
     * the stream is ready to accept mutations.
     */    get Rn() {
        return this.zt > 0;
    }
    // Override of PersistentStream.start
    start() {
        this.lastStreamToken = void 0, super.start();
    }
    sn() {
        this.Rn && this.In([]);
    }
    cn(e, t) {
        return this.connection.vt("Write", e, t);
    }
    En(e) {
        // Always capture the last stream token.
        return __PRIVATE_hardAssert(!!e.streamToken, 31322), this.lastStreamToken = e.streamToken, 
        // The first response is always the handshake response
        __PRIVATE_hardAssert(!e.writeResults || 0 === e.writeResults.length, 55816), this.listener.An();
    }
    onNext(e) {
        // Always capture the last stream token.
        __PRIVATE_hardAssert(!!e.streamToken, 12678), this.lastStreamToken = e.streamToken, 
        // A successful first write response means the stream is healthy,
        // Note, that we could consider a successful handshake healthy, however,
        // the write itself might be causing an error we want to back off from.
        this.jt.reset();
        const t = __PRIVATE_fromWriteResults(e.writeResults, e.commitTime), n = __PRIVATE_fromVersion(e.commitTime);
        return this.listener.Vn(n, t);
    }
    /**
     * Sends an initial streamToken to the server, performing the handshake
     * required to make the StreamingWrite RPC work. Subsequent
     * calls should wait until onHandshakeComplete was called.
     */    dn() {
        // TODO(dimond): Support stream resumption. We intentionally do not set the
        // stream token on the handshake, ignoring any stream token we might have.
        const e = {};
        e.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.tn(e);
    }
    /** Sends a group of mutations to the Firestore backend to apply. */    In(e) {
        const t = {
            streamToken: this.lastStreamToken,
            writes: e.map((e => toMutation(this.serializer, e)))
        };
        this.tn(t);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Datastore and its related methods are a wrapper around the external Google
 * Cloud Datastore grpc API, which provides an interface that is more convenient
 * for the rest of the client SDK architecture to consume.
 */ class Datastore {}

/**
 * An implementation of Datastore that exposes additional state for internal
 * consumption.
 */ class __PRIVATE_DatastoreImpl extends Datastore {
    constructor(e, t, n, r) {
        super(), this.authCredentials = e, this.appCheckCredentials = t, this.connection = n, 
        this.serializer = r, this.fn = false;
    }
    mn() {
        if (this.fn) throw new s(aa.FAILED_PRECONDITION, "The client has already been terminated.");
    }
    /** Invokes the provided RPC with auth and AppCheck tokens. */    tt(e, t, n, r) {
        return this.mn(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.tt(e, __PRIVATE_toResourcePath(t, n), r, i, s))).catch((e => {
            throw "FirebaseError" === e.name ? (e.code === aa.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), 
            this.appCheckCredentials.invalidateToken()), e) : new s(aa.UNKNOWN, e.toString());
        }));
    }
    /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */    st(e, t, n, r, i) {
        return this.mn(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, _]) => this.connection.st(e, __PRIVATE_toResourcePath(t, n), r, s, _, i))).catch((e => {
            throw "FirebaseError" === e.name ? (e.code === aa.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), 
            this.appCheckCredentials.invalidateToken()), e) : new s(aa.UNKNOWN, e.toString());
        }));
    }
    terminate() {
        this.fn = true, this.connection.terminate();
    }
}

// TODO(firestorexp): Make sure there is only one Datastore instance per
// firestore-exp client.
function __PRIVATE_newDatastore(e, t, n, r) {
    return new __PRIVATE_DatastoreImpl(e, t, n, r);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const Vt = "ComponentProvider", dt = new Map;

/**
 * An instance map that ensures only one Datastore exists per Firestore
 * instance.
 */ function __PRIVATE_makeDatabaseInfo(e, t, n, r, i) {
    return new DatabaseInfo(e, t, n, i.host, i.ssl, i.experimentalForceLongPolling, i.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(i.experimentalLongPollingOptions), i.useFetchStreams, i.isUsingEmulator, r, i._customHeaders, i.grpcFlowControlWindow);
}

/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const ft = {
    didRun: false,
    sequenceNumbersCollected: 0,
    targetsRemoved: 0,
    documentsRemoved: 0
}, mt = 41943040;

class LruParams {
    static withCacheSize(e) {
        return new LruParams(e, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);
    }
    constructor(
    // When we attempt to collect, we will only do so if the cache size is greater than this
    // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.
    e, 
    // The percentage of sequence numbers that we will attempt to collect
    t, 
    // A cap on the total number of sequence numbers that will be collected. This prevents
    // us from collecting a huge number of sequence numbers if the cache has grown very large.
    n) {
        this.cacheSizeCollectionThreshold = e, this.percentileToCollect = t, this.maximumSequenceNumbersToCollect = n;
    }
}

LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, 
LruParams.DEFAULT = new LruParams(mt, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), 
LruParams.DISABLED = new LruParams(-1, 0, 0);

/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to
 * exceed. All subsequent calls to next will return increasing values. If provided with a
 * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as
 * well as write out sequence numbers that it produces via `next()`.
 */
class __PRIVATE_ListenSequence {
    constructor(e, t) {
        this.previousValue = e, t && (t.sequenceNumberHandler = e => this.pn(e), this.gn = e => t.writeSequenceNumber(e));
    }
    pn(e) {
        return this.previousValue = Math.max(e, this.previousValue), this.previousValue;
    }
    next() {
        const e = ++this.previousValue;
        return this.gn && this.gn(e), e;
    }
}

__PRIVATE_ListenSequence.yn = -1;

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const pt = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.";

/**
 * A base class representing a persistence transaction, encapsulating both the
 * transaction's sequence numbers as well as a list of onCommitted listeners.
 *
 * When you call Persistence.runTransaction(), it will create a transaction and
 * pass it to your callback. You then pass it to any method that operates
 * on persistence.
 */ class PersistenceTransaction {
    constructor() {
        this.onCommittedListeners = [];
    }
    addOnCommittedListener(e) {
        this.onCommittedListeners.push(e);
    }
    raiseOnCommittedEvent() {
        this.onCommittedListeners.forEach((e => e()));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Verifies the error thrown by a LocalStore operation. If a LocalStore
 * operation fails because the primary lease has been taken by another client,
 * we ignore the error (the persistence layer will immediately call
 * `applyPrimaryLease` to propagate the primary state change). All other errors
 * are re-thrown.
 *
 * @param err - An error returned by a LocalStore operation.
 * @returns A Promise that resolves after we recovered, or the original error.
 */ async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e) {
    if (e.code !== aa.FAILED_PRECONDITION || e.message !== pt) throw e;
    __PRIVATE_logDebug("LocalStore", "Unexpectedly lost primary lease");
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * PersistencePromise is essentially a re-implementation of Promise except
 * it has a .next() method instead of .then() and .next() and .catch() callbacks
 * are executed synchronously when a PersistencePromise resolves rather than
 * asynchronously (Promise implementations use setImmediate() or similar).
 *
 * This is necessary to interoperate with IndexedDB which will automatically
 * commit transactions if control is returned to the event loop without
 * synchronously initiating another operation on the transaction.
 *
 * NOTE: .then() and .catch() only allow a single consumer, unlike normal
 * Promises.
 */ class PersistencePromise {
    constructor(e) {
        // NOTE: next/catchCallback will always point to our own wrapper functions,
        // not the user's raw next() or catch() callbacks.
        this.nextCallback = null, this.catchCallback = null, 
        // When the operation resolves, we'll set result or error and mark isDone.
        this.result = void 0, this.error = void 0, this.isDone = false, 
        // Set to true when .then() or .catch() are called and prevents additional
        // chaining.
        this.callbackAttached = false, e((e => {
            this.isDone = true, this.result = e, this.nextCallback && 
            // value should be defined unless T is Void, but we can't express
            // that in the type system.
            this.nextCallback(e);
        }), (e => {
            this.isDone = true, this.error = e, this.catchCallback && this.catchCallback(e);
        }));
    }
    catch(e) {
        return this.next(void 0, e);
    }
    next(e, t) {
        return this.callbackAttached && l(59440), this.callbackAttached = true, this.isDone ? this.error ? this.wrapFailure(t, this.error) : this.wrapSuccess(e, this.result) : new PersistencePromise(((n, r) => {
            this.nextCallback = t => {
                this.wrapSuccess(e, t).next(n, r);
            }, this.catchCallback = e => {
                this.wrapFailure(t, e).next(n, r);
            };
        }));
    }
    toPromise() {
        return new Promise(((e, t) => {
            this.next(e, t);
        }));
    }
    wrapUserFunction(e) {
        try {
            const t = e();
            return t instanceof PersistencePromise ? t : PersistencePromise.resolve(t);
        } catch (e) {
            return PersistencePromise.reject(e);
        }
    }
    wrapSuccess(e, t) {
        return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.resolve(t);
    }
    wrapFailure(e, t) {
        return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.reject(t);
    }
    static resolve(e) {
        return new PersistencePromise(((t, n) => {
            t(e);
        }));
    }
    static reject(e) {
        return new PersistencePromise(((t, n) => {
            n(e);
        }));
    }
    static waitFor(
    // Accept all Promise types in waitFor().
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    e) {
        return new PersistencePromise(((t, n) => {
            let r = 0, i = 0, s = false;
            e.forEach((e => {
                ++r, e.next((() => {
                    ++i, s && i === r && t();
                }), (e => n(e)));
            })), s = true, i === r && t();
        }));
    }
    /**
     * Given an array of predicate functions that asynchronously evaluate to a
     * boolean, implements a short-circuiting `or` between the results. Predicates
     * will be evaluated until one of them returns `true`, then stop. The final
     * result will be whether any of them returned `true`.
     */    static or(e) {
        let t = PersistencePromise.resolve(false);
        for (const n of e) t = t.next((e => e ? PersistencePromise.resolve(e) : n()));
        return t;
    }
    static forEach(e, t) {
        const n = [];
        return e.forEach(((e, r) => {
            n.push(t.call(this, e, r));
        })), this.waitFor(n);
    }
    /**
     * Concurrently map all array elements through asynchronous function.
     */    static mapArray(e, t) {
        return new PersistencePromise(((n, r) => {
            const i = e.length, s = new Array(i);
            let _ = 0;
            for (let o = 0; o < i; o++) {
                const a = o;
                t(e[a]).next((e => {
                    s[a] = e, ++_, _ === i && n(s);
                }), (e => r(e)));
            }
        }));
    }
    /**
     * An alternative to recursive PersistencePromise calls, that avoids
     * potential memory problems from unbounded chains of promises.
     *
     * The `action` will be called repeatedly while `condition` is true.
     */    static doWhile(e, t) {
        return new PersistencePromise(((n, r) => {
            const process = () => {
                true === e() ? t().next((() => {
                    process();
                }), r) : n();
            };
            process();
        }));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()
/* eslint-disable no-restricted-globals */ const gt = "SimpleDb";

/**
 * The maximum number of retry attempts for an IndexedDb transaction that fails
 * with a DOMException.
 */
/**
 * Wraps an IDBTransaction and exposes a store() method to get a handle to a
 * specific object store.
 */
class __PRIVATE_SimpleDbTransaction {
    static open(e, t, n, r) {
        try {
            return new __PRIVATE_SimpleDbTransaction(t, e.transaction(r, n));
        } catch (e) {
            throw new __PRIVATE_IndexedDbTransactionError(t, e);
        }
    }
    constructor(e, t) {
        this.action = e, this.transaction = t, this.aborted = false, 
        /**
         * A `Promise` that resolves with the result of the IndexedDb transaction.
         */
        this.wn = new __PRIVATE_Deferred, this.transaction.oncomplete = () => {
            this.wn.resolve();
        }, this.transaction.onabort = () => {
            t.error ? this.wn.reject(new __PRIVATE_IndexedDbTransactionError(e, t.error)) : this.wn.resolve();
        }, this.transaction.onerror = t => {
            const n = __PRIVATE_checkForAndReportiOSError(t.target.error);
            this.wn.reject(new __PRIVATE_IndexedDbTransactionError(e, n));
        };
    }
    get bn() {
        return this.wn.promise;
    }
    abort(e) {
        e && this.wn.reject(e), this.aborted || (__PRIVATE_logDebug(gt, "Aborting transaction:", e ? e.message : "Client-initiated abort"), 
        this.aborted = true, this.transaction.abort());
    }
    vn() {
        // If the browser supports V3 IndexedDB, we invoke commit() explicitly to
        // speed up index DB processing if the event loop remains blocks.
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const e = this.transaction;
        this.aborted || "function" != typeof e.commit || e.commit();
    }
    /**
     * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All
     * operations performed on the SimpleDbStore happen within the context of this
     * transaction and it cannot be used anymore once the transaction is
     * completed.
     *
     * Note that we can't actually enforce that the KeyType and ValueType are
     * correct, but they allow type safety through the rest of the consuming code.
     */    store(e) {
        const t = this.transaction.objectStore(e);
        return new __PRIVATE_SimpleDbStore(t);
    }
}

/**
 * Provides a wrapper around IndexedDb with a simplified interface that uses
 * Promise-like return values to chain operations. Real promises cannot be used
 * since .then() continuations are executed asynchronously (e.g. via
 * .setImmediate), which would cause IndexedDB to end the transaction.
 * See PersistencePromise for more details.
 */ class __PRIVATE_SimpleDb {
    /** Deletes the specified database. */
    static delete(e) {
        __PRIVATE_logDebug(gt, "Removing database:", e);
        return __PRIVATE_wrapRequest(util.getGlobal().indexedDB.deleteDatabase(e)).toPromise();
    }
    /** Returns true if IndexedDB is available in the current environment. */    static Je() {
        if (!util.isIndexedDBAvailable()) return false;
        if (__PRIVATE_SimpleDb.Sn()) return true;
        // We extensively use indexed array values and compound keys,
        // which IE and Edge do not support. However, they still have indexedDB
        // defined on the window, so we need to check for them here and make sure
        // to return that persistence is not enabled for those browsers.
        // For tracking support of this feature, see here:
        // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/
        // Check the UA string to find out the browser.
                const e = util.getUA(), t = __PRIVATE_SimpleDb.Dn(e), n = 0 < t && t < 10, r = __PRIVATE_getAndroidVersion(e), i = 0 < r && r < 4.5;
        // IE 10
        // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
        // IE 11
        // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
        // Edge
        // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
        // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
        // iOS Safari: Disable for users running iOS version < 10.
                return !(e.indexOf("MSIE ") > 0 || e.indexOf("Trident/") > 0 || e.indexOf("Edge/") > 0 || n || i);
    }
    /**
     * Returns true if the backing IndexedDB store is the Node IndexedDBShim
     * (see https://github.com/axemclion/IndexedDBShim).
     */    static Sn() {
        return "undefined" != typeof process && "YES" === process.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE;
    }
    /** Helper to get a typed SimpleDbStore from a transaction. */    static xn(e, t) {
        return e.store(t);
    }
    // visible for testing
    /** Parse User Agent to determine iOS version. Returns -1 if not found. */
    static Dn(e) {
        const t = e.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = t ? t[1].split("_").slice(0, 2).join(".") : "-1";
        return Number(n);
    }
    /*
     * Creates a new SimpleDb wrapper for IndexedDb database `name`.
     *
     * Note that `version` must not be a downgrade. IndexedDB does not support
     * downgrading the schema version. We currently do not support any way to do
     * versioning outside of IndexedDB's versioning mechanism, as only
     * version-upgrade transactions are allowed to do things like create
     * objectstores.
     */    constructor(e, t, n) {
        this.name = e, this.version = t, this.Cn = n, this.Fn = null;
        // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the
        // bug we're checking for should exist in iOS >= 12.2 and < 13, but for
        // whatever reason it's much harder to hit after 12.2 so we only proactively
        // log on 12.2.
        12.2 === __PRIVATE_SimpleDb.Dn(util.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.");
    }
    /**
     * Opens the specified database, creating or upgrading it if necessary.
     */    async On(e) {
        return this.db || (__PRIVATE_logDebug(gt, "Opening database:", this.name), this.db = await new Promise(((t, n) => {
            // TODO(mikelehen): Investigate browser compatibility.
            // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
            // suggests IE9 and older WebKit browsers handle upgrade
            // differently. They expect setVersion, as described here:
            // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion
            const r = indexedDB.open(this.name, this.version);
            r.onsuccess = e => {
                const n = e.target.result;
                t(n);
            }, r.onblocked = () => {
                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."));
            }, r.onerror = t => {
                const r = t.target.error;
                "VersionError" === r.name ? n(new s(aa.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 s(aa.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));
            }, r.onupgradeneeded = e => {
                __PRIVATE_logDebug(gt, 'Database "' + this.name + '" requires upgrade from version:', e.oldVersion);
                const t = e.target.result;
                this.Cn.Mn(t, r.transaction, e.oldVersion, this.version).next((() => {
                    __PRIVATE_logDebug(gt, "Database upgrade to version " + this.version + " complete");
                }));
            };
        }))), this.Nn && (this.db.onversionchange = e => this.Nn(e)), this.db;
    }
    Ln(e) {
        this.Nn = e, this.db && (this.db.onversionchange = t => e(t));
    }
    async runTransaction(e, t, n, r) {
        const i = "readonly" === t;
        let s = 0;
        for (;;) {
            ++s;
            try {
                this.db = await this.On(e);
                const t = __PRIVATE_SimpleDbTransaction.open(this.db, e, i ? "readonly" : "readwrite", n), s = r(t).next((e => (t.vn(), 
                e))).catch((e => (
                // Abort the transaction if there was an error.
                t.abort(e), PersistencePromise.reject(e)))).toPromise();
                // As noted above, errors are propagated by aborting the transaction. So
                // we swallow any error here to avoid the browser logging it as unhandled.
                return s.catch((() => {})), 
                // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to
                // fire), but still return the original transactionFnResult back to the
                // caller.
                await t.bn, s;
            } catch (e) {
                const t = e, n = "FirebaseError" !== t.name && s < 3;
                // TODO(schmidt-sebastian): We could probably be smarter about this and
                // not retry exceptions that are likely unrecoverable (such as quota
                // exceeded errors).
                // Note: We cannot use an instanceof check for FirestoreException, since the
                // exception is wrapped in a generic error by our async/await handling.
                                if (__PRIVATE_logDebug(gt, "Transaction failed with error:", t.message, "Retrying:", n), 
                this.close(), !n) return Promise.reject(t);
            }
        }
    }
    close() {
        this.db && this.db.close(), this.db = void 0;
    }
}

/** Parse User Agent to determine Android version. Returns -1 if not found. */ function __PRIVATE_getAndroidVersion(e) {
    const t = e.match(/Android ([\d.]+)/i), n = t ? t[1].split(".").slice(0, 2).join(".") : "-1";
    return Number(n);
}

/**
 * A controller for iterating over a key range or index. It allows an iterate
 * callback to delete the currently-referenced object, or jump to a new key
 * within the key range or index.
 */ class __PRIVATE_IterationController {
    constructor(e) {
        this.Bn = e, this.Un = false, this.kn = null;
    }
    get isDone() {
        return this.Un;
    }
    get qn() {
        return this.kn;
    }
    set cursor(e) {
        this.Bn = e;
    }
    /**
     * This function can be called to stop iteration at any point.
     */    done() {
        this.Un = true;
    }
    /**
     * This function can be called to skip to that next key, which could be
     * an index or a primary key.
     */    $n(e) {
        this.kn = e;
    }
    /**
     * Delete the current cursor value from the object store.
     *
     * NOTE: You CANNOT do this with a keysOnly query.
     */    delete() {
        return __PRIVATE_wrapRequest(this.Bn.delete());
    }
}

/** An error that wraps exceptions that thrown during IndexedDB execution. */ class __PRIVATE_IndexedDbTransactionError extends s {
    constructor(e, t) {
        super(aa.UNAVAILABLE, `IndexedDB transaction '${e}' failed: ${t}`), this.name = "IndexedDbTransactionError";
    }
}

/** Verifies whether `e` is an IndexedDbTransactionError. */ function __PRIVATE_isIndexedDbTransactionError(e) {
    // Use name equality, as instanceof checks on errors don't work with errors
    // that wrap other errors.
    return "IndexedDbTransactionError" === e.name;
}

/**
 * A wrapper around an IDBObjectStore providing an API that:
 *
 * 1) Has generic KeyType / ValueType parameters to provide strongly-typed
 * methods for acting against the object store.
 * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every
 * method return a PersistencePromise instead.
 * 3) Provides a higher-level API to avoid needing to do excessive wrapping of
 * intermediate IndexedDB types (IDBCursorWithValue, etc.)
 */ class __PRIVATE_SimpleDbStore {
    constructor(e) {
        this.store = e;
    }
    put(e, t) {
        let n;
        return void 0 !== t ? (__PRIVATE_logDebug(gt, "PUT", this.store.name, e, t), n = this.store.put(t, e)) : (__PRIVATE_logDebug(gt, "PUT", this.store.name, "<auto-key>", e), 
        n = this.store.put(e)), __PRIVATE_wrapRequest(n);
    }
    /**
     * Adds a new value into an Object Store and returns the new key. Similar to
     * IndexedDb's `add()`, this method will fail on primary key collisions.
     *
     * @param value - The object to write.
     * @returns The key of the value to add.
     */    add(e) {
        __PRIVATE_logDebug(gt, "ADD", this.store.name, e, e);
        return __PRIVATE_wrapRequest(this.store.add(e));
    }
    /**
     * Gets the object with the specified key from the specified store, or null
     * if no object exists with the specified key.
     *
     * @key The key of the object to get.
     * @returns The object with the specified key or null if no object exists.
     */    get(e) {
        // We're doing an unsafe cast to ValueType.
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return __PRIVATE_wrapRequest(this.store.get(e)).next((t => (
        // Normalize nonexistence to null.
        void 0 === t && (t = null), __PRIVATE_logDebug(gt, "GET", this.store.name, e, t), 
        t)));
    }
    delete(e) {
        __PRIVATE_logDebug(gt, "DELETE", this.store.name, e);
        return __PRIVATE_wrapRequest(this.store.delete(e));
    }
    /**
     * If we ever need more of the count variants, we can add overloads. For now,
     * all we need is to count everything in a store.
     *
     * Returns the number of rows in the store.
     */    count() {
        __PRIVATE_logDebug(gt, "COUNT", this.store.name);
        return __PRIVATE_wrapRequest(this.store.count());
    }
    Kn(e, t) {
        const n = this.options(e, t), r = n.index ? this.store.index(n.index) : this.store;
        // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly
        // 20% faster.
                if ("function" == typeof r.getAll) {
            const e = r.getAll(n.range);
            return new PersistencePromise(((t, n) => {
                e.onerror = e => {
                    n(e.target.error);
                }, e.onsuccess = e => {
                    t(e.target.result);
                };
            }));
        }
        {
            const e = this.cursor(n), t = [];
            return this.Wn(e, ((e, n) => {
                t.push(n);
            })).next((() => t));
        }
    }
    /**
     * Loads the first `count` elements from the provided index range. Loads all
     * elements if no limit is provided.
     */    Qn(e, t) {
        const n = this.store.getAll(e, null === t ? void 0 : t);
        return new PersistencePromise(((e, t) => {
            n.onerror = e => {
                t(e.target.error);
            }, n.onsuccess = t => {
                e(t.target.result);
            };
        }));
    }
    Gn(e, t) {
        __PRIVATE_logDebug(gt, "DELETE ALL", this.store.name);
        const n = this.options(e, t);
        n.zn = false;
        const r = this.cursor(n);
        return this.Wn(r, ((e, t, n) => n.delete()));
    }
    jn(e, t) {
        let n;
        t ? n = e : (n = {}, t = e);
        const r = this.cursor(n);
        return this.Wn(r, t);
    }
    /**
     * Iterates over a store, but waits for the given callback to complete for
     * each entry before iterating the next entry. This allows the callback to do
     * asynchronous work to determine if this iteration should continue.
     *
     * The provided callback should return `true` to continue iteration, and
     * `false` otherwise.
     */    Hn(e) {
        const t = this.cursor({});
        return new PersistencePromise(((n, r) => {
            t.onerror = e => {
                const t = __PRIVATE_checkForAndReportiOSError(e.target.error);
                r(t);
            }, t.onsuccess = t => {
                const r = t.target.result;
                r ? e(r.primaryKey, r.value).next((e => {
                    e ? r.continue() : n();
                })) : n();
            };
        }));
    }
    Wn(e, t) {
        const n = [];
        return new PersistencePromise(((r, i) => {
            e.onerror = e => {
                i(e.target.error);
            }, e.onsuccess = e => {
                const i = e.target.result;
                if (!i) return void r();
                const s = new __PRIVATE_IterationController(i), _ = t(i.primaryKey, i.value, s);
                if (_ instanceof PersistencePromise) {
                    const e = _.catch((e => (s.done(), PersistencePromise.reject(e))));
                    n.push(e);
                }
                s.isDone ? r() : null === s.qn ? i.continue() : i.continue(s.qn);
            };
        })).next((() => PersistencePromise.waitFor(n)));
    }
    options(e, t) {
        let n;
        return void 0 !== e && ("string" == typeof e ? n = e : t = e), {
            index: n,
            range: t
        };
    }
    cursor(e) {
        let t = "next";
        if (e.reverse && (t = "prev"), e.index) {
            const n = this.store.index(e.index);
            return e.zn ? n.openKeyCursor(e.range, t) : n.openCursor(e.range, t);
        }
        return this.store.openCursor(e.range, t);
    }
}

/**
 * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror
 * handlers to resolve / reject the PersistencePromise as appropriate.
 */ function __PRIVATE_wrapRequest(e) {
    return new PersistencePromise(((t, n) => {
        e.onsuccess = e => {
            const n = e.target.result;
            t(n);
        }, e.onerror = e => {
            const t = __PRIVATE_checkForAndReportiOSError(e.target.error);
            n(t);
        };
    }));
}

// Guard so we only report the error once.
let yt = false;

function __PRIVATE_checkForAndReportiOSError(e) {
    const t = __PRIVATE_SimpleDb.Dn(util.getUA());
    if (t >= 12.2 && t < 13) {
        const t = "An internal error was encountered in the Indexed Database server";
        if (e.message.indexOf(t) >= 0) {
            // Wrap error in a more descriptive one.
            const e = new s("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.`);
            return yt || (yt = true, 
            // Throw a global exception outside of this promise chain, for the user to
            // potentially catch.
            setTimeout((() => {
                throw e;
            }), 0)), e;
        }
    }
    return e;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const wt = "LruGarbageCollector", bt = 1048576;

function __PRIVATE_bufferEntryComparator([e, t], [n, r]) {
    const i = __PRIVATE_primitiveComparator(e, n);
    return 0 === i ? __PRIVATE_primitiveComparator(t, r) : i;
}

/**
 * Used to calculate the nth sequence number. Keeps a rolling buffer of the
 * lowest n values passed to `addElement`, and finally reports the largest of
 * them in `maxValue`.
 */ class __PRIVATE_RollingSequenceNumberBuffer {
    constructor(e) {
        this.Jn = e, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.Yn = 0;
    }
    Zn() {
        return ++this.Yn;
    }
    Xn(e) {
        const t = [ e, this.Zn() ];
        if (this.buffer.size < this.Jn) this.buffer = this.buffer.add(t); else {
            const e = this.buffer.last();
            __PRIVATE_bufferEntryComparator(t, e) < 0 && (this.buffer = this.buffer.delete(e).add(t));
        }
    }
    get maxValue() {
        // Guaranteed to be non-empty. If we decide we are not collecting any
        // sequence numbers, nthSequenceNumber below short-circuits. If we have
        // decided that we are collecting n sequence numbers, it's because n is some
        // percentage of the existing sequence numbers. That means we should never
        // be in a situation where we are collecting sequence numbers but don't
        // actually have any.
        return this.buffer.last()[0];
    }
}

/**
 * This class is responsible for the scheduling of LRU garbage collection. It handles checking
 * whether or not GC is enabled, as well as which delay to use before the next run.
 */ class __PRIVATE_LruScheduler {
    constructor(e, t, n) {
        this.garbageCollector = e, this.asyncQueue = t, this.localStore = n, this.er = null;
    }
    start() {
        -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.tr(6e4);
    }
    stop() {
        this.er && (this.er.cancel(), this.er = null);
    }
    get started() {
        return null !== this.er;
    }
    tr(e) {
        __PRIVATE_logDebug(wt, `Garbage collection scheduled in ${e}ms`), this.er = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , e, (async () => {
            this.er = null;
            try {
                await this.localStore.collectGarbage(this.garbageCollector);
            } catch (e) {
                __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(wt, "Ignoring IndexedDB error during garbage collection: ", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);
            }
            await this.tr(3e5);
        }));
    }
}

/**
 * Implements the steps for LRU garbage collection.
 */ class __PRIVATE_LruGarbageCollectorImpl {
    constructor(e, t) {
        this.nr = e, this.params = t;
    }
    calculateTargetCount(e, t) {
        return this.nr.rr(e).next((e => Math.floor(t / 100 * e)));
    }
    nthSequenceNumber(e, t) {
        if (0 === t) return PersistencePromise.resolve(__PRIVATE_ListenSequence.yn);
        const n = new __PRIVATE_RollingSequenceNumberBuffer(t);
        return this.nr.forEachTarget(e, (e => n.Xn(e.sequenceNumber))).next((() => this.nr.ir(e, (e => n.Xn(e))))).next((() => n.maxValue));
    }
    removeTargets(e, t, n) {
        return this.nr.removeTargets(e, t, n);
    }
    removeOrphanedDocuments(e, t) {
        return this.nr.removeOrphanedDocuments(e, t);
    }
    collect(e, t) {
        return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", "Garbage collection skipped; disabled"), 
        PersistencePromise.resolve(ft)) : 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}`), 
        ft) : this.sr(e, t)));
    }
    getCacheSize(e) {
        return this.nr.getCacheSize(e);
    }
    sr(e, t) {
        let n, r, i, s, _, o, a;
        const u = Date.now();
        return this.calculateTargetCount(e, this.params.percentileToCollect).next((t => (
        // Cap at the configured max
        t > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`), 
        r = this.params.maximumSequenceNumbersToCollect) : r = t, s = Date.now(), this.nthSequenceNumber(e, r)))).next((r => (n = r, 
        _ = Date.now(), this.removeTargets(e, n, t)))).next((t => (i = t, o = Date.now(), 
        this.removeOrphanedDocuments(e, n)))).next((e => {
            if (a = Date.now(), __PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG) {
                __PRIVATE_logDebug("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${s - u}ms\n\tDetermined least recently used ${r} in ` + (_ - s) + "ms\n" + `\tRemoved ${i} targets in ` + (o - _) + "ms\n" + `\tRemoved ${e} documents in ` + (a - o) + "ms\n" + `Total Duration: ${a - u}ms`);
            }
            return PersistencePromise.resolve({
                didRun: true,
                sequenceNumbersCollected: r,
                targetsRemoved: i,
                documentsRemoved: e
            });
        }));
    }
}

function __PRIVATE_newLruGarbageCollector(e, t) {
    return new __PRIVATE_LruGarbageCollectorImpl(e, t);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// settings() defaults:
const vt = "firestore.googleapis.com", St = true;

/**
 * A concrete type describing all the values that can be applied via a
 * user-supplied `FirestoreSettings` object. This is a separate type so that
 * defaults can be supplied and the value can be checked for equality.
 */
class FirestoreSettingsImpl {
    constructor(e) {
        if (void 0 === e.host) {
            if (void 0 !== e.ssl) throw new s(aa.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
            this.host = vt, this.ssl = St;
        } else this.host = e.host, this.ssl = e.ssl ?? St;
        if (this.isUsingEmulator = void 0 !== e.emulatorOptions, this.credentials = e.credentials, 
        this.ignoreUndefinedProperties = !!e.ignoreUndefinedProperties, this.localCache = e.localCache, 
        e._customHeaders && (this._customHeaders = {
            ...e._customHeaders
        }), void 0 === e.cacheSizeBytes) this.cacheSizeBytes = mt; else {
            if (-1 !== e.cacheSizeBytes && e.cacheSizeBytes < bt) throw new s(aa.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
            this.cacheSizeBytes = e.cacheSizeBytes;
        }
        if (__PRIVATE_validateIsNotUsedTogether("experimentalForceLongPolling", e.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", e.experimentalAutoDetectLongPolling), 
        this.experimentalForceLongPolling = !!e.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = false : void 0 === e.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : 
        // For backwards compatibility, coerce the value to boolean even though
        // the TypeScript compiler has narrowed the type to boolean already.
        // noinspection PointlessBooleanExpressionJS
        this.experimentalAutoDetectLongPolling = !!e.experimentalAutoDetectLongPolling, 
        this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(e.experimentalLongPollingOptions ?? {}), 
        function __PRIVATE_validateLongPollingOptions(e) {
            if (void 0 !== e.timeoutSeconds) {
                if (isNaN(e.timeoutSeconds)) throw new s(aa.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`);
                if (e.timeoutSeconds < 5) throw new s(aa.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`);
                if (e.timeoutSeconds > 30) throw new s(aa.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`);
            }
        }
        /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
        // eslint-disable-next-line import/no-extraneous-dependencies
        /**
 * The Cloud Firestore service interface.
 *
 * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
 */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!e.useFetchStreams, void 0 !== e.grpcFlowControlWindow) {
            if ("number" != typeof e.grpcFlowControlWindow || e.grpcFlowControlWindow <= 0 || e.grpcFlowControlWindow > 2147483647 || !Number.isInteger(e.grpcFlowControlWindow)) throw new s(aa.INVALID_ARGUMENT, "grpcFlowControlWindow must be a positive integer and cannot exceed 2147483647");
            this.grpcFlowControlWindow = e.grpcFlowControlWindow;
        }
    }
    isEqual(e) {
        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 && 
        /**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
        /**
 * Compares two `ExperimentalLongPollingOptions` objects for equality.
 */
        function __PRIVATE_longPollingOptionsEqual(e, t) {
            return e.timeoutSeconds === t.timeoutSeconds;
        }(this.experimentalLongPollingOptions, e.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e.ignoreUndefinedProperties && this.useFetchStreams === e.useFetchStreams && this.grpcFlowControlWindow === e.grpcFlowControlWindow && function __PRIVATE_customHeadersEqual(e, t) {
            if (e === t) return true;
            if (!e || !t) return false;
            const n = Object.keys(e), r = Object.keys(t);
            if (n.length !== r.length) return false;
            for (const r of n) if (e[r] !== t[r]) return false;
            return true;
        }(this._customHeaders, e._customHeaders);
    }
}

let Dt = class Firestore {
    /** @hideconstructor */
    constructor(e, t, n, r) {
        this._authCredentials = e, this._appCheckCredentials = t, this._databaseId = n, 
        this._app = r, 
        /**
         * Whether it's a Firestore or Firestore Lite instance.
         */
        this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), 
        this._settingsFrozen = false, this._emulatorOptions = {}, 
        // A task that is assigned when the terminate() is invoked and resolved when
        // all components have shut down. Otherwise, Firestore is not terminated,
        // which can mean either the FirestoreClient is in the process of starting,
        // or restarting.
        this._terminateTask = "notTerminated";
    }
    /**
     * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service
     * instance.
     */    get app() {
        if (!this._app) throw new s(aa.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
        return this._app;
    }
    get _initialized() {
        return this._settingsFrozen;
    }
    get _terminated() {
        return "notTerminated" !== this._terminateTask;
    }
    _setSettings(e) {
        if (this._settingsFrozen) throw new s(aa.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.");
        this._settings = new FirestoreSettingsImpl(e), this._emulatorOptions = e.emulatorOptions || {}, 
        void 0 !== e.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(e) {
            if (!e) return new __PRIVATE_EmptyAuthCredentialsProvider;
            switch (e.type) {
              case "firstParty":
                return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex || "0", e.iamToken || null, e.authTokenFactory || null);

              case "provider":
                return e.client;

              default:
                throw new s(aa.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type");
            }
        }(e.credentials));
    }
    _getSettings() {
        return this._settings;
    }
    _getEmulatorOptions() {
        return this._emulatorOptions;
    }
    _freezeSettings() {
        return this._settingsFrozen = true, this._settings;
    }
    _delete() {
        // The `_terminateTask` must be assigned future that completes when
        // terminate is complete. The existence of this future puts SDK in state
        // that will not accept further API interaction.
        return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), 
        this._terminateTask;
    }
    async _restart() {
        // The `_terminateTask` must equal 'notTerminated' after restart to
        // signal that client is in a state that accepts API calls.
        "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated";
    }
    /** Returns a JSON-serializable representation of this `Firestore` instance. */    toJSON() {
        return {
            app: this._app,
            databaseId: this._databaseId,
            settings: this._settings
        };
    }
    /**
     * Terminates all components used by this client. Subclasses can override
     * this method to clean up their own dependencies, but must also call this
     * method.
     *
     * Only ever called once.
     */    _terminate() {
        /**
 * Removes all components associated with the provided instance. Must be called
 * when the `Firestore` instance is terminated.
 */
        return function __PRIVATE_removeComponents(e) {
            const t = dt.get(e);
            t && (__PRIVATE_logDebug(Vt, "Removing Datastore"), dt.delete(e), t.terminate());
        }(this), Promise.resolve();
    }
};

/**
 * Modify this instance to communicate with the Cloud Firestore emulator.
 *
 * Note: This must be called before this instance has been used to do any
 * operations.
 *
 * @param firestore - The `Firestore` instance to configure to connect to the
 * emulator.
 * @param host - the emulator host (ex: localhost).
 * @param port - the emulator port (ex: 9000).
 * @param options.mockUserToken - the mock auth token to use for unit testing
 * Security Rules.
 */ function connectFirestoreEmulator(e, t, n, r = {}) {
    e = ra(e, Dt);
    const i = util.isCloudWorkstation(t), _ = e._getSettings(), o = {
        ..._,
        emulatorOptions: e._getEmulatorOptions()
    }, a = `${t}:${n}`;
    i && util.pingServer(`https://${a}`), _.host !== vt && _.host !== a && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.");
    const u = {
        ..._,
        host: a,
        ssl: i,
        emulatorOptions: r
    };
    // No-op if the new configuration matches the current configuration. This supports SSR
    // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.
        if (!util.deepEqual(u, o) && (e._setSettings(u), r.mockUserToken)) {
        let t, n;
        if ("string" == typeof r.mockUserToken) t = r.mockUserToken, n = User.MOCK_USER; else {
            // Let createMockUserToken validate first (catches common mistakes like
            // invalid field "uid" and missing field "sub" / "user_id".)
            t = util.createMockUserToken(r.mockUserToken, e._app?.options.projectId);
            const i = r.mockUserToken.sub || r.mockUserToken.user_id;
            if (!i) throw new s(aa.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!");
            n = new User(i);
        }
        e._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t, n));
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A `Query` refers to a query which you can read or listen to. You can also
 * construct refined `Query` objects by adding filters and ordering.
 */ class Query {
    // This is the lite version of the Query class in the main SDK.
    /** @hideconstructor protected */
    constructor(e, 
    /**
     * If provided, the `FirestoreDataConverter` associated with this instance.
     */
    t, n) {
        this.converter = t, this._query = n, 
        /** The type of this Firestore reference. */
        this.type = "query", this.firestore = e;
    }
    withConverter(e) {
        return new Query(this.firestore, e, this._query);
    }
}

/**
 * A `DocumentReference` refers to a document location in a Firestore database
 * and can be used to write, read, or listen to the location. The document at
 * the referenced location may or may not exist.
 */ class X {
    /** @hideconstructor */
    constructor(e, 
    /**
     * If provided, the `FirestoreDataConverter` associated with this instance.
     */
    t, n) {
        this.converter = t, this._key = n, 
        /** The type of this Firestore reference. */
        this.type = "document", this.firestore = e;
    }
    get _path() {
        return this._key.path;
    }
    /**
     * The document's identifier within its collection.
     */    get id() {
        return this._key.path.lastSegment();
    }
    /**
     * A string representing the path of the referenced document (relative
     * to the root of the database).
     */    get path() {
        return this._key.path.canonicalString();
    }
    /**
     * The collection this `DocumentReference` belongs to.
     */    get parent() {
        return new ea(this.firestore, this.converter, this._key.path.popLast());
    }
    withConverter(e) {
        return new X(this.firestore, e, this._key);
    }
    /**
     * Returns a JSON-serializable representation of this `DocumentReference` instance.
     *
     * @returns a JSON representation of this object.
     */    toJSON() {
        return {
            type: X._jsonSchemaVersion,
            referencePath: this._key.toString()
        };
    }
    static fromJSON(e, t, n) {
        if (__PRIVATE_validateJSON(t, X._jsonSchema)) return new X(e, n || null, new DocumentKey(ResourcePath.fromString(t.referencePath)));
    }
}

X._jsonSchemaVersion = "firestore/documentReference/1.0", X._jsonSchema = {
    type: property("string", X._jsonSchemaVersion),
    referencePath: property("string")
};

/**
 * A `CollectionReference` object can be used for adding documents, getting
 * document references, and querying for documents (using {@link (query:1)}).
 */
class ea extends Query {
    /** @hideconstructor */
    constructor(e, t, n) {
        super(e, t, __PRIVATE_newQueryForPath(n)), this._path = n, 
        /** The type of this Firestore reference. */
        this.type = "collection";
    }
    /** The collection's identifier. */    get id() {
        return this._query.path.lastSegment();
    }
    /**
     * A string representing the path of the referenced collection (relative
     * to the root of the database).
     */    get path() {
        return this._query.path.canonicalString();
    }
    /**
     * A reference to the containing `DocumentReference` if this is a
     * subcollection. If this isn't a subcollection, the reference is null.
     */    get parent() {
        const e = this._path.popLast();
        return e.isEmpty() ? null : new X(this.firestore, 
        /* converter= */ null, new DocumentKey(e));
    }
    withConverter(e) {
        return new ea(this.firestore, e, this._path);
    }
}

function z(e) {
    return e instanceof ea;
}

function collection(e, t, ...n) {
    if (e = util.getModularInstance(e), __PRIVATE_validateNonEmptyArgument("collection", "path", t), e instanceof Dt) {
        const r = ResourcePath.fromString(t, ...n);
        return __PRIVATE_validateCollectionPath(r), new ea(e, /* converter= */ null, r);
    }
    {
        if (!(e instanceof X || e instanceof ea)) throw new s(aa.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
        const r = e._path.child(ResourcePath.fromString(t, ...n));
        return __PRIVATE_validateCollectionPath(r), new ea(e.firestore, 
        /* converter= */ null, r);
    }
}

// TODO(firestorelite): Consider using ErrorFactory -
// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106
/**
 * Creates and returns a new `Query` instance that includes all documents in the
 * database that are contained in a collection or subcollection with the
 * given `collectionId`.
 *
 * @param firestore - A reference to the root `Firestore` instance.
 * @param collectionId - Identifies the collections to query over. Every
 * collection or subcollection with this ID as the last segment of its path
 * will be included. Cannot contain a slash.
 * @returns The created `Query`.
 */ function collectionGroup(e, t) {
    if (e = ra(e, Dt), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", t), 
    t.indexOf("/") >= 0) throw new s(aa.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);
    return new Query(e, 
    /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(e) {
        return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e);
    }(t));
}

function doc(e, t, ...n) {
    if (e = util.getModularInstance(e), 
    // We allow omission of 'pathString' but explicitly prohibit passing in both
    // 'undefined' and 'null'.
    1 === arguments.length && (t = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", t), 
    e instanceof Dt) {
        const r = ResourcePath.fromString(t, ...n);
        return __PRIVATE_validateDocumentPath(r), new X(e, 
        /* converter= */ null, new DocumentKey(r));
    }
    {
        if (!(e instanceof X || e instanceof ea)) throw new s(aa.INVALID_ARGUMENT, "Expected first argument to doc() to be a CollectionReference, a DocumentReference or FirebaseFirestore");
        const r = e._path.child(ResourcePath.fromString(t, ...n));
        return __PRIVATE_validateDocumentPath(r), new X(e.firestore, e instanceof ea ? e.converter : null, new DocumentKey(r));
    }
}

/**
 * Returns true if the provided references are equal.
 *
 * @param left - A reference to compare.
 * @param right - A reference to compare.
 * @returns true if the references point to the same location in the same
 * Firestore database.
 */ function ia(e, t) {
    return e = util.getModularInstance(e), t = util.getModularInstance(t), (e instanceof X || e instanceof ea) && (t instanceof X || t instanceof ea) && (e.firestore === t.firestore && e.path === t.path && e.converter === t.converter);
}

/**
 * Returns true if the provided queries point to the same collection and apply
 * the same constraints.
 *
 * @param left - A `Query` to compare.
 * @param right - A `Query` to compare.
 * @returns true if the references point to the same location in the same
 * Firestore database.
 */ function queryEqual(e, t) {
    return e = util.getModularInstance(e), t = util.getModularInstance(t), e instanceof Query && t instanceof Query && (e.firestore === t.firestore && __PRIVATE_queryEquals(e._query, t._query) && e.converter === t.converter);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Returns true iff the array contains the value using strong equality.
 */
/**
 * Compares two array for equality using comparator. The method computes the
 * intersection and invokes `onAdd` for every element that is in `after` but not
 * `before`. `onRemove` is invoked for every element in `before` but missing
 * from `after`.
 *
 * The method creates a copy of both `before` and `after` and runs in O(n log
 * n), where n is the size of the two lists.
 *
 * @param before - The elements that exist in the original array.
 * @param after - The elements to diff against the original array.
 * @param comparator - The comparator for the elements in before and after.
 * @param onAdd - A function to invoke for every element that is part of `
 * after` but not `before`.
 * @param onRemove - A function to invoke for every element that is part of
 * `before` but not `after`.
 */
/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents a vector type in Firestore documents.
 * Create an instance with <code>{@link vector}</code>.
 */
class n {
    /**
     * @private
     * @internal
     */
    constructor(e) {
        // Making a copy of the parameter.
        this._values = (e || []).map((e => e));
    }
    /**
     * Returns a copy of the raw number array form of the vector.
     */    toArray() {
        return this._values.map((e => e));
    }
    /**
     * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise.
     */    isEqual(e) {
        /**
 * Verifies equality for an array of primitives.
 *
 * @private
 * @internal
 * @param left - Array of primitives.
 * @param right - Array of primitives.
 * @returns True if arrays are equal.
 */
        return function __PRIVATE_isPrimitiveArrayEqual(e, t) {
            if (e.length !== t.length) return false;
            for (let n = 0; n < e.length; ++n) if (e[n] !== t[n]) return false;
            return true;
        }(this._values, e._values);
    }
    /**
     * Returns a JSON-serializable representation of this `VectorValue` instance.
     *
     * @returns a JSON representation of this object.
     */    toJSON() {
        return {
            type: n._jsonSchemaVersion,
            vectorValues: this._values
        };
    }
    /**
     * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.
     *
     * @param json - a JSON object represention of a `VectorValue` instance.
     * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a
     * {@link FirestoreError} if an error occurs.
     */    static fromJSON(e) {
        if (__PRIVATE_validateJSON(e, n._jsonSchema)) {
            if (Array.isArray(e.vectorValues) && e.vectorValues.every((e => "number" == typeof e))) return new n(e.vectorValues);
            throw new s(aa.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array");
        }
    }
}

n._jsonSchemaVersion = "firestore/vectorValue/1.0", n._jsonSchema = {
    type: property("string", n._jsonSchemaVersion),
    vectorValues: property("object")
};

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const xt = /^__.*__$/;

/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData {
    constructor(e, t, n) {
        this.data = e, this.fieldMask = t, this.fieldTransforms = n;
    }
    toMutation(e, t) {
        return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms) : new __PRIVATE_SetMutation(e, this.data, t, this.fieldTransforms);
    }
}

/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData {
    constructor(e, 
    // The fieldMask does not include document transforms.
    t, n) {
        this.data = e, this.fieldMask = t, this.fieldTransforms = n;
    }
    toMutation(e, t) {
        return new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms);
    }
}

function __PRIVATE_isWrite(e) {
    switch (e) {
      case 0 /* UserDataSource.Set */ :
 // fall through
              case 2 /* UserDataSource.MergeSet */ :
 // fall through
              case 1 /* UserDataSource.Update */ :
        return true;

      case 3 /* UserDataSource.Argument */ :
      case 4 /* UserDataSource.ArrayArgument */ :
        return false;

      default:
        throw l(40011, {
            dataSource: e
        });
    }
}

/** A "context" object passed around while parsing user data. */ class ParseContextImpl {
    /**
     * Initializes a ParseContext with the given source and path.
     *
     * @param settings - The settings for the parser.
     * @param databaseId - The database ID of the Firestore instance.
     * @param serializer - The serializer to use to generate the Value proto.
     * @param ignoreUndefinedProperties - Whether to ignore undefined properties
     * rather than throw.
     * @param fieldTransforms - A mutable list of field transforms encountered
     * while parsing the data.
     * @param fieldMask - A mutable list of field paths encountered while parsing
     * the data.
     *
     * TODO(b/34871131): We don't support array paths right now, so path can be
     * null to indicate the context represents any location within an array (in
     * which case certain features will not work and errors will be somewhat
     * compromised).
     */
    constructor(e, t, n, r, i, s) {
        this.settings = e, this.databaseId = t, this.serializer = n, this.ignoreUndefinedProperties = r, 
        // Minor hack: If fieldTransforms is undefined, we assume this is an
        // external call and we need to validate the entire path.
        void 0 === i && this.validatePath(), this.fieldTransforms = i || [], this.fieldMask = s || [];
    }
    get path() {
        return this.settings.path;
    }
    get dataSource() {
        return this.settings.dataSource;
    }
    /** Returns a new context with the specified settings overwritten. */    contextWith(e) {
        return new ParseContextImpl({
            ...this.settings,
            ...e
        }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);
    }
    childContextForField(e) {
        const t = this.path?.child(e), n = this.contextWith({
            path: t,
            arrayElement: false
        });
        return n.validatePathSegment(e), n;
    }
    childContextForFieldPath(e) {
        const t = this.path?.child(e), n = this.contextWith({
            path: t,
            arrayElement: false
        });
        return n.validatePath(), n;
    }
    childContextForArray(e) {
        // TODO(b/34871131): We don't support array paths right now; so make path
        // undefined.
        return this.contextWith({
            path: void 0,
            arrayElement: true
        });
    }
    createError(e) {
        return createError(e, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc);
    }
    /** Returns 'true' if 'fieldPath' was traversed when creating this context. */    contains(e) {
        return void 0 !== this.fieldMask.find((t => e.isPrefixOf(t))) || void 0 !== this.fieldTransforms.find((t => e.isPrefixOf(t.field)));
    }
    validatePath() {
        // TODO(b/34871131): Remove null check once we have proper paths for fields
        // within arrays.
        if (this.path) for (let e = 0; e < this.path.length; e++) this.validatePathSegment(this.path.get(e));
    }
    validatePathSegment(e) {
        if (0 === e.length) throw this.createError("Document fields must not be empty");
        if (__PRIVATE_isWrite(this.dataSource) && xt.test(e)) throw this.createError('Document fields cannot begin and end with "__"');
    }
}

/**
 * Helper for parsing raw user input (provided via the API) into internal model
 * classes.
 */ class UserDataReader {
    constructor(e, t, n) {
        this.databaseId = e, this.ignoreUndefinedProperties = t, this.serializer = n || __PRIVATE_newSerializer(e);
    }
    /** Creates a new top-level parse context. */    createContext(e, t, n, r = false) {
        return new ParseContextImpl({
            dataSource: e,
            methodName: t,
            targetDoc: n,
            path: Oe.emptyPath(),
            arrayElement: false,
            hasConverter: r
        }, this.databaseId, this.serializer, this.ignoreUndefinedProperties);
    }
}

function la(e) {
    const t = e._freezeSettings(), n = __PRIVATE_newSerializer(e._databaseId);
    return new UserDataReader(e._databaseId, !!t.ignoreUndefinedProperties, n);
}

/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(e, t, n, r, i, _ = {}) {
    const o = e.createContext(_.merge || _.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , t, n, i);
    __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, r);
    const a = __PRIVATE_parseObject(r, o);
    let u, c;
    if (_.merge) u = new FieldMask(o.fieldMask), c = o.fieldTransforms; else if (_.mergeFields) {
        const e = [];
        for (const r of _.mergeFields) {
            const i = ta(t, r, n);
            if (!o.contains(i)) throw new s(aa.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);
            __PRIVATE_fieldMaskContains(e, i) || e.push(i);
        }
        u = new FieldMask(e), c = o.fieldTransforms.filter((e => u.covers(e.field)));
    } else u = null, c = o.fieldTransforms;
    return new ParsedSetData(new ObjectValue(a), u, c);
}

class __PRIVATE_DeleteFieldValueImpl extends FieldValue {
    _toFieldTransform(e) {
        if (2 /* UserDataSource.MergeSet */ !== e.dataSource) throw 1 /* UserDataSource.Update */ === e.dataSource ? e.createError(`${this._methodName}() can only appear at the top level of your update data`) : e.createError(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);
        // No transform to add for a delete, but we need to add it to our
        // fieldMask so it gets deleted.
        return e.fieldMask.push(e.path), null;
    }
    isEqual(e) {
        return e instanceof __PRIVATE_DeleteFieldValueImpl;
    }
}

/**
 * Creates a child context for parsing SerializableFieldValues.
 *
 * This is different than calling `ParseContext.contextWith` because it keeps
 * the fieldTransforms and fieldMask separate.
 *
 * The created context has its `dataSource` set to `UserDataSource.Argument`.
 * Although these values are used with writes, any elements in these FieldValues
 * are not considered writes since they cannot contain any FieldValue sentinels,
 * etc.
 *
 * @param fieldValue - The sentinel FieldValue for which to create a child
 *     context.
 * @param context - The parent context.
 * @param arrayElement - Whether or not the FieldValue has an array.
 */ function __PRIVATE_createSentinelChildContext(e, t, n) {
    return new ParseContextImpl({
        dataSource: 3 /* UserDataSource.Argument */ ,
        targetDoc: t.settings.targetDoc,
        methodName: e._methodName,
        arrayElement: n
    }, t.databaseId, t.serializer, t.ignoreUndefinedProperties);
}

class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue {
    _toFieldTransform(e) {
        return new FieldTransform(e.path, new __PRIVATE_ServerTimestampTransform);
    }
    isEqual(e) {
        return e instanceof __PRIVATE_ServerTimestampFieldValueImpl;
    }
}

class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue {
    constructor(e, t) {
        super(e), this._r = t;
    }
    _toFieldTransform(e) {
        const t = __PRIVATE_createSentinelChildContext(this, e, 
        /*array=*/ true), n = this._r.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayUnionTransformOperation(n);
        return new FieldTransform(e.path, r);
    }
    isEqual(e) {
        return e instanceof __PRIVATE_ArrayUnionFieldValueImpl && util.deepEqual(this._r, e._r);
    }
}

class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue {
    constructor(e, t) {
        super(e), this._r = t;
    }
    _toFieldTransform(e) {
        const t = __PRIVATE_createSentinelChildContext(this, e, 
        /*array=*/ true), n = this._r.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayRemoveTransformOperation(n);
        return new FieldTransform(e.path, r);
    }
    isEqual(e) {
        return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl && util.deepEqual(this._r, e._r);
    }
}

class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue {
    constructor(e, t) {
        super(e), this.ar = t;
    }
    _toFieldTransform(e) {
        const t = new __PRIVATE_NumericIncrementTransformOperation(e.serializer, toNumber(e.serializer, this.ar));
        return new FieldTransform(e.path, t);
    }
    isEqual(e) {
        return e instanceof __PRIVATE_NumericIncrementFieldValueImpl && (this.ar === e.ar || Number.isNaN(this.ar) && Number.isNaN(e.ar));
    }
}

class __PRIVATE_NumericMinimumFieldValueImpl extends FieldValue {
    constructor(e, t) {
        super(e), this.ar = t;
    }
    _toFieldTransform(e) {
        const t = new __PRIVATE_NumericMinimumTransformOperation(e.serializer, toNumber(e.serializer, this.ar));
        return new FieldTransform(e.path, t);
    }
    isEqual(e) {
        return e instanceof __PRIVATE_NumericMinimumFieldValueImpl && (this.ar === e.ar || Number.isNaN(this.ar) && Number.isNaN(e.ar));
    }
}

class __PRIVATE_NumericMaximumFieldValueImpl extends FieldValue {
    constructor(e, t) {
        super(e), this.ar = t;
    }
    _toFieldTransform(e) {
        const t = new __PRIVATE_NumericMaximumTransformOperation(e.serializer, toNumber(e.serializer, this.ar));
        return new FieldTransform(e.path, t);
    }
    isEqual(e) {
        return e instanceof __PRIVATE_NumericMaximumFieldValueImpl && (this.ar === e.ar || Number.isNaN(this.ar) && Number.isNaN(e.ar));
    }
}

/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(e, t, n, r) {
    const i = e.createContext(1 /* UserDataSource.Update */ , t, n);
    __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, r);
    const s = [], _ = ObjectValue.empty();
    forEach(r, ((e, r) => {
        const o = __PRIVATE_fieldPathFromDotSeparatedString(t, e, n);
        // For Compat types, we have to "extract" the underlying types before
        // performing validation.
                r = util.getModularInstance(r);
        const a = i.childContextForFieldPath(o);
        if (r instanceof __PRIVATE_DeleteFieldValueImpl) 
        // Add it to the field mask, but don't add anything to updateData.
        s.push(o); else {
            const e = __PRIVATE_parseData(r, a);
            null != e && (s.push(o), _.set(o, e));
        }
    }));
    const o = new FieldMask(s);
    return new ParsedUpdateData(_, o, i.fieldTransforms);
}

/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(e, t, n, r, i, _) {
    const o = e.createContext(1 /* UserDataSource.Update */ , t, n), a = [ ta(t, r, n) ], u = [ i ];
    if (_.length % 2 != 0) throw new s(aa.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`);
    for (let e = 0; e < _.length; e += 2) a.push(ta(t, _[e])), u.push(_[e + 1]);
    const c = [], l = ObjectValue.empty();
    // We iterate in reverse order to pick the last value for a field if the
    // user specified the field multiple times.
    for (let e = a.length - 1; e >= 0; --e) if (!__PRIVATE_fieldMaskContains(c, a[e])) {
        const t = a[e];
        let n = u[e];
        // For Compat types, we have to "extract" the underlying types before
        // performing validation.
                n = util.getModularInstance(n);
        const r = o.childContextForFieldPath(t);
        if (n instanceof __PRIVATE_DeleteFieldValueImpl) 
        // Add it to the field mask, but don't add anything to updateData.
        c.push(t); else {
            const e = __PRIVATE_parseData(n, r);
            null != e && (c.push(t), l.set(t, e));
        }
    }
    const E = new FieldMask(c);
    return new ParsedUpdateData(l, E, o.fieldTransforms);
}

/**
 * Parse a "query value" (e.g. value in a where filter or a value in a cursor
 * bound).
 *
 * @param allowArrays - Whether the query value is an array that may directly
 * contain additional arrays (e.g. the operand of an `in` query).
 */ function __PRIVATE_parseQueryValue(e, t, n, r = false) {
    return __PRIVATE_parseData(n, e.createContext(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , t));
}

/**
 * Parses user data to Protobuf Values.
 *
 * @param input - Data to be parsed.
 * @param context - A context object representing the current path being parsed,
 * the source of the data being parsed, etc.
 * @returns The parsed value, or null if the value was a FieldValue sentinel
 * that should not be included in the resulting parsed data.
 */ function __PRIVATE_parseData(e, t, r) {
    if (__PRIVATE_looksLikeJsonObject(
    // Unwrap the API type from the Compat SDK. This will return the API type
    // from firestore-exp.
    e = util.getModularInstance(e))) return __PRIVATE_validatePlainObject("Unsupported field value:", t, e), 
    __PRIVATE_parseObject(e, t);
    if (e instanceof FieldValue) 
    // FieldValues usually parse into transforms (except deleteField())
    // in which case we do not want to include this field in our parsed data
    // (as doing so will overwrite the field directly prior to the transform
    // trying to transform it). So we don't add this location to
    // context.fieldMask and we return null as our parsing result.
    /**
 * "Parses" the provided FieldValueImpl, adding any necessary transforms to
 * context.fieldTransforms.
 */
    return function __PRIVATE_parseSentinelFieldValue(e, t) {
        // Sentinels are only supported with writes, and not within arrays.
        if (!__PRIVATE_isWrite(t.dataSource)) throw t.createError(`${e._methodName}() can only be used with update() and set()`);
        if (!t.path) throw t.createError(`${e._methodName}() is not currently supported inside arrays`);
        const n = e._toFieldTransform(t);
        n && t.fieldTransforms.push(n);
    }
    /**
 * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
 *
 * @returns The parsed value
 */ (e, t), null;
    if (void 0 === e && t.ignoreUndefinedProperties) 
    // If the input is undefined it can never participate in the fieldMask, so
    // don't handle this below. If `ignoreUndefinedProperties` is false,
    // `parseScalarValue` will reject an undefined value.
    return null;
    if (
    // If context.path is null we are inside an array and we don't support
    // field mask paths more granular than the top-level array.
    t.path && t.fieldMask.push(t.path), e instanceof Array) {
        // TODO(b/34871131): Include the path containing the array in the error
        // message.
        // In the case of IN queries, the parsed data is an array (representing
        // the set of values to be included for the IN query) that may directly
        // contain additional arrays (each representing an individual field
        // value), so we disable this validation.
        if (t.settings.arrayElement && 4 /* UserDataSource.ArrayArgument */ !== t.dataSource) throw t.createError("Nested arrays are not supported");
        return function __PRIVATE_parseArray(e, t) {
            const n = [];
            let r = 0;
            for (const i of e) {
                let e = __PRIVATE_parseData(i, t.childContextForArray(r));
                null == e && (
                // Just include nulls in the array for fields being replaced with a
                // sentinel.
                e = {
                    nullValue: "NULL_VALUE"
                }), n.push(e), r++;
            }
            return {
                arrayValue: {
                    values: n
                }
            };
        }(e, t);
    }
    return function __PRIVATE_parseScalarValue(e, t, r) {
        if (null === (e = util.getModularInstance(e))) return {
            nullValue: "NULL_VALUE"
        };
        if ("number" == typeof e) return toNumber(t.serializer, e);
        if ("boolean" == typeof e) return {
            booleanValue: e
        };
        if ("string" == typeof e) return {
            stringValue: e
        };
        if (e instanceof Date) {
            const n = Timestamp.fromDate(e);
            return {
                timestampValue: toTimestamp(t.serializer, n)
            };
        }
        if (e instanceof Timestamp) {
            // Firestore backend truncates precision down to microseconds. To ensure
            // offline mode works the same with regards to truncation, perform the
            // truncation immediately without waiting for the backend to do that.
            const n = new Timestamp(e.seconds, 1e3 * Math.floor(e.nanoseconds / 1e3));
            return {
                timestampValue: toTimestamp(t.serializer, n)
            };
        }
        if (e instanceof GeoPoint) return {
            geoPointValue: {
                latitude: e.latitude,
                longitude: e.longitude
            }
        };
        if (e instanceof Bytes) return {
            bytesValue: __PRIVATE_toBytes(t.serializer, e._byteString)
        };
        if (e instanceof X) {
            const n = t.databaseId, r = e.firestore._databaseId;
            if (!r.isEqual(n)) throw t.createError(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`);
            return {
                referenceValue: __PRIVATE_toResourceName(e.firestore._databaseId || t.databaseId, e._key.path)
            };
        }
        if (e instanceof n) 
        /**
 * Creates a new VectorValue proto value (using the internal format).
 */
        return function __PRIVATE_parseVectorValue(e, t) {
            const r = e instanceof n ? e.toArray() : e, i = {
                fields: {
                    [We]: {
                        stringValue: ze
                    },
                    [je]: {
                        arrayValue: {
                            values: r.map((e => {
                                if ("number" != typeof e) throw t.createError("VectorValues must only contain numeric values.");
                                return __PRIVATE_toDouble(t.serializer, e);
                            }))
                        }
                    }
                }
            };
            return {
                mapValue: i
            };
        }
        /**
 * Checks whether an object looks like a JSON object that should be converted
 * into a struct. Normal class/prototype instances are considered to look like
 * JSON objects since they should be converted to a struct value. Arrays, Dates,
 * GeoPoints, etc. are not considered to look like JSON objects since they map
 * to specific FieldValue types other than ObjectValue.
 */ (e, t);
        if (__PRIVATE_isProtoValueSerializable(e)) return e._toProto(t.serializer);
        throw t.createError(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`);
    }(e, t);
}

function __PRIVATE_parseObject(e, t) {
    const n = {};
    return isEmpty(e) ? 
    // If we encounter an empty object, we explicitly add it to the update
    // mask to ensure that the server creates a map entry.
    t.path && t.path.length > 0 && t.fieldMask.push(t.path) : forEach(e, ((e, r) => {
        const i = __PRIVATE_parseData(r, t.childContextForField(e));
        null != i && (n[e] = i);
    })), {
        mapValue: {
            fields: n
        }
    };
}

function __PRIVATE_looksLikeJsonObject(e) {
    return !("object" != typeof e || null === e || e instanceof Array || e instanceof Date || e instanceof Timestamp || e instanceof GeoPoint || e instanceof Bytes || e instanceof X || e instanceof FieldValue || e instanceof n || __PRIVATE_isProtoValueSerializable(e));
}

function __PRIVATE_validatePlainObject(e, t, n) {
    if (!__PRIVATE_looksLikeJsonObject(n) || !p(n)) {
        const r = __PRIVATE_valueDescription(n);
        throw "an object" === r ? t.createError(e + " a custom object") : t.createError(e + " " + r);
    }
}

/**
 * Helper that calls fromDotSeparatedString() but wraps any error thrown.
 */ function ta(e, t, n) {
    if ((
    // If required, replace the FieldPath Compat class with the firestore-exp
    // FieldPath.
    t = util.getModularInstance(t)) instanceof FieldPath) return t._internalPath;
    if ("string" == typeof t) return __PRIVATE_fieldPathFromDotSeparatedString(e, t);
    throw createError("Field path arguments must be of type string or ", e, 
    /* hasConverter= */ false, 
    /* path= */ void 0, n);
}

/**
 * Matches any characters in a field path string that are reserved.
 */ const Ct = new RegExp("[~\\*/\\[\\]]");

/**
 * Wraps fromDotSeparatedString with an error message about the method that
 * was thrown.
 * @param methodName - The publicly visible method name
 * @param path - The dot-separated string form of a field path which will be
 * split on dots.
 * @param targetDoc - The document against which the field path will be
 * evaluated.
 */ function __PRIVATE_fieldPathFromDotSeparatedString(e, t, n) {
    if (t.search(Ct) >= 0) throw createError(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`, e, 
    /* hasConverter= */ false, 
    /* path= */ void 0, n);
    try {
        return new FieldPath(...t.split("."))._internalPath;
    } catch (r) {
        throw createError(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, e, 
        /* hasConverter= */ false, 
        /* path= */ void 0, n);
    }
}

function createError(e, t, n, r, i) {
    const _ = r && !r.isEmpty(), o = void 0 !== i;
    let a = `Function ${t}() called with invalid data`;
    n && (a += " (via `toFirestore()`)"), a += ". ";
    let u = "";
    return (_ || o) && (u += " (found", _ && (u += ` in field ${r}`), o && (u += ` in document ${i}`), 
    u += ")"), new s(aa.INVALID_ARGUMENT, a + e + u);
}

/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(e, t) {
    return e.some((e => e.isEqual(t)));
}

function __PRIVATE_isUserData(e) {
    return "function" == typeof e._readUserData;
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class OptionsUtil {
    constructor(e) {
        this.optionDefinitions = e;
    }
    _getKnownOptions(e, t) {
        const n = ObjectValue.empty();
        // SERIALIZE KNOWN OPTIONS
                for (const r in this.optionDefinitions) if (this.optionDefinitions.hasOwnProperty(r)) {
            const i = this.optionDefinitions[r];
            if (r in e) {
                const s = e[r];
                let _;
                if (i.nestedOptions && p(s)) {
                    _ = {
                        mapValue: {
                            fields: new OptionsUtil(i.nestedOptions).getOptionsProto(t, s)
                        }
                    };
                } else s && (_ = __PRIVATE_parseData(s, t) ?? void 0);
                _ && n.set(Oe.fromServerFormat(i.serverName), _);
            }
        }
        return n;
    }
    getOptionsProto(e, t, n) {
        const r = this._getKnownOptions(t, e);
        // APPLY OPTIONS OVERRIDES
                if (n) {
            const t = new Map(__PRIVATE_mapToArray(n, ((t, n) => [ Oe.fromServerFormat(n), void 0 !== t ? __PRIVATE_parseData(t, e) : null ])));
            r.setAll(t);
        }
        // Return MapValue from `result` or empty map value
                return r.value.mapValue.fields ?? {};
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* eslint @typescript-eslint/no-explicit-any: 0 */ function u(e) {
    return "object" == typeof e && null !== e && !!("nullValue" in e && (null === e.nullValue || "NULL_VALUE" === e.nullValue) || "booleanValue" in e && (null === e.booleanValue || "boolean" == typeof e.booleanValue) || "integerValue" in e && (null === e.integerValue || "number" == typeof e.integerValue || "string" == typeof e.integerValue) || "doubleValue" in e && (null === e.doubleValue || "number" == typeof e.doubleValue) || "timestampValue" in e && (null === e.timestampValue || function __PRIVATE_isITimestamp(e) {
        return "object" == typeof e && null !== e && "seconds" in e && (null === e.seconds || "number" == typeof e.seconds || "string" == typeof e.seconds) && "nanos" in e && (null === e.nanos || "number" == typeof e.nanos);
    }(e.timestampValue)) || "stringValue" in e && (null === e.stringValue || "string" == typeof e.stringValue) || "bytesValue" in e && (null === e.bytesValue || e.bytesValue instanceof Uint8Array) || "referenceValue" in e && (null === e.referenceValue || "string" == typeof e.referenceValue) || "geoPointValue" in e && (null === e.geoPointValue || function __PRIVATE_isILatLng(e) {
        return "object" == typeof e && null !== e && "latitude" in e && (null === e.latitude || "number" == typeof e.latitude) && "longitude" in e && (null === e.longitude || "number" == typeof e.longitude);
    }(e.geoPointValue)) || "arrayValue" in e && (null === e.arrayValue || function __PRIVATE_isIArrayValue(e) {
        return "object" == typeof e && null !== e && !(!("values" in e) || null !== e.values && !Array.isArray(e.values));
    }(e.arrayValue)) || "mapValue" in e && (null === e.mapValue || function __PRIVATE_isIMapValue(e) {
        return "object" == typeof e && null !== e && !(!("fields" in e) || null !== e.fields && !p(e.fields));
    }(e.mapValue)) || "fieldReferenceValue" in e && (null === e.fieldReferenceValue || "string" == typeof e.fieldReferenceValue) || "functionValue" in e && (null === e.functionValue || function __PRIVATE_isIFunction(e) {
        return "object" == typeof e && null !== e && !(!("name" in e) || null !== e.name && "string" != typeof e.name || !("args" in e) || null !== e.args && !Array.isArray(e.args));
    }(e.functionValue)) || "pipelineValue" in e && (null === e.pipelineValue || function __PRIVATE_isIPipeline(e) {
        return "object" == typeof e && null !== e && !(!("stages" in e) || null !== e.stages && !Array.isArray(e.stages));
    }(e.pipelineValue)));
    // Check optional properties and their types
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or
 * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.
 */ function deleteField() {
    return new __PRIVATE_DeleteFieldValueImpl("deleteField");
}

/**
 * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to
 * include a server-generated timestamp in the written data.
 */ function serverTimestamp() {
    return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp");
}

/**
 * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
 * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array
 * value that already exists on the server. Each specified element that doesn't
 * already exist in the array will be added to the end. If the field being
 * modified is not already an array it will be overwritten with an array
 * containing exactly the specified elements.
 *
 * @param elements - The elements to union into the array.
 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
 * `updateDoc()`.
 */ function arrayUnion(...e) {
    // NOTE: We don't actually parse the data until it's used in set() or
    // update() since we'd need the Firestore instance to do this.
    return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", e);
}

/**
 * Returns a special value that can be used with {@link (setDoc:1)} or {@link
 * updateDoc:1} that tells the server to remove the given elements from any
 * array value that already exists on the server. All instances of each element
 * specified will be removed from the array. If the field being modified is not
 * already an array it will be overwritten with an empty array.
 *
 * @param elements - The elements to remove from the array.
 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
 * `updateDoc()`
 */ function arrayRemove(...e) {
    // NOTE: We don't actually parse the data until it's used in set() or
    // update() since we'd need the Firestore instance to do this.
    return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", e);
}

/**
 * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
 * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by
 * the given value.
 *
 * If either the operand or the current field value uses floating point
 * precision, all arithmetic follows IEEE 754 semantics. If both values are
 * integers, values outside of JavaScript's safe number range
 * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to
 * precision loss. Furthermore, once processed by the Firestore backend, all
 * integer operations are capped between -2^63 and 2^63-1.
 *
 * If the current field value is not of type `number`, or if the field does not
 * yet exist, the transformation sets the field to the given value.
 *
 * @param n - The value to increment by.
 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
 * `updateDoc()`
 */ function increment(e) {
    return new __PRIVATE_NumericIncrementFieldValueImpl("increment", e);
}

/**
 * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
 * @firebase/firestore/lite#(updateDoc:1)} that tells the server to set the field to the numeric minimum of the
 * field's current and the given value.
 *
 * @param n - The value to compare to the existing field value.
 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
 * `updateDoc()`
 */ function minimum$1(e) {
    return new __PRIVATE_NumericMinimumFieldValueImpl("minimum", e);
}

/**
 * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link
 * @firebase/firestore/lite#(updateDoc:1)} that tells the server to set the field to the numeric maximum of the
 * field's current and the given value.
 *
 * @param n - The value to compare to the existing field value.
 * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or
 * `updateDoc()`
 */ function maximum$1(e) {
    return new __PRIVATE_NumericMaximumFieldValueImpl("maximum", e);
}

/**
 * Creates a new `VectorValue` constructed with a copy of the given array of numbers.
 *
 * @param values - Create a `VectorValue` instance with a copy of this array of numbers.
 *
 * @returns A new `VectorValue` constructed with a copy of the given array of numbers.
 */ function r(e) {
    return new n(e);
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Converts a value to an Expression, Returning either a Constant, MapFunction,
 * ArrayFunction, or the input itself (if it's already an expression).
 *
 * @private
 * @internal
 * @param value
 */ function __PRIVATE_valueToDefaultExpr(e) {
    let n;
    return e instanceof t ? e : (n = p(e) ? __PRIVATE__map(e) : e instanceof Array ? b(e) : m(e, void 0), 
    n);
}

/**
 * Converts a value to an Expression, Returning either a Constant, MapFunction,
 * ArrayFunction, or the input itself (if it's already an expression).
 *
 * @private
 * @internal
 * @param value
 */ function __PRIVATE_vectorToExpr(e) {
    if (e instanceof t) return e;
    if (e instanceof n) return i(e);
    if (Array.isArray(e)) return i(r(e));
    throw new Error("Unsupported value: " + typeof e);
}

/**
 * Converts a value to an Expression, Returning either a Constant, MapFunction,
 * ArrayFunction, or the input itself (if it's already an expression).
 * If the input is a string, it is assumed to be a field name, and a
 * field(value) is returned.
 *
 * @private
 * @internal
 * @param value
 */ function __PRIVATE_fieldOrExpression(t) {
    if (__PRIVATE_isString$1(t)) {
        return e(t);
    }
    return __PRIVATE_valueToDefaultExpr(t);
}

/**
 *
 * Represents an expression that can be evaluated to a value within the execution of a {@link
 * @firebase/firestore/pipelines#Pipeline}.
 *
 * Expressions are the building blocks for creating complex queries and transformations in
 * Firestore pipelines. They can represent:
 *
 * - **Field references:** Access values from document fields.
 * - **Literals:** Represent constant values (strings, numbers, booleans).
 * - **Function calls:** Apply functions to one or more expressions.
 *
 * The `Expression` class provides a fluent API for building expressions. You can chain together
 * method calls to create complex expressions.
 */ class t {
    constructor() {
        this._protoValueType = "ProtoValue";
    }
    /**
     * Creates an expression that adds this expression to another expression.
     *
     * @example
     * ```typescript
     * // Add the value of the 'quantity' field and the 'reserve' field.
     * field("quantity").add(field("reserve"));
     * ```
     *
     * @param second - The expression or literal to add to this expression.
     * @param others - Optional additional expressions or literals to add to this expression.
     * @returns A new `Expression` representing the addition operation.
     */    add(e) {
        return new x("add", [ this, __PRIVATE_valueToDefaultExpr(e) ], "add");
    }
    /**
     * Wraps the expression in a [BooleanExpression].
     *
     * @returns A [BooleanExpression] representing the same expression.
     */    asBoolean() {
        if (this instanceof BooleanExpression) return this;
        if (this instanceof Constant) return new __PRIVATE_BooleanConstant(this);
        if (this instanceof o) return new __PRIVATE_BooleanField(this);
        if (this instanceof x) return new __PRIVATE_BooleanFunctionExpression(this);
        throw new s("invalid-argument", `Conversion of type ${typeof this} to BooleanExpression not supported.`);
    }
    subtract(e) {
        return new x("subtract", [ this, __PRIVATE_valueToDefaultExpr(e) ], "subtract");
    }
    /**
     * Creates an expression that multiplies this expression by another expression.
     *
     * @example
     * ```typescript
     * // Multiply the 'quantity' field by the 'price' field
     * field("quantity").multiply(field("price"));
     * ```
     *
     * @param second - The second expression or literal to multiply by.
     * @param others - Optional additional expressions or literals to multiply by.
     * @returns A new `Expression` representing the multiplication operation.
     */    multiply(e) {
        return new x("multiply", [ this, __PRIVATE_valueToDefaultExpr(e) ], "multiply");
    }
    divide(e) {
        return new x("divide", [ this, __PRIVATE_valueToDefaultExpr(e) ], "divide");
    }
    mod(e) {
        return new x("mod", [ this, __PRIVATE_valueToDefaultExpr(e) ], "mod");
    }
    equal(e) {
        return new x("equal", [ this, __PRIVATE_valueToDefaultExpr(e) ], "equal").asBoolean();
    }
    notEqual(e) {
        return new x("not_equal", [ this, __PRIVATE_valueToDefaultExpr(e) ], "notEqual").asBoolean();
    }
    lessThan(e) {
        return new x("less_than", [ this, __PRIVATE_valueToDefaultExpr(e) ], "lessThan").asBoolean();
    }
    lessThanOrEqual(e) {
        return new x("less_than_or_equal", [ this, __PRIVATE_valueToDefaultExpr(e) ], "lessThanOrEqual").asBoolean();
    }
    greaterThan(e) {
        return new x("greater_than", [ this, __PRIVATE_valueToDefaultExpr(e) ], "greaterThan").asBoolean();
    }
    greaterThanOrEqual(e) {
        return new x("greater_than_or_equal", [ this, __PRIVATE_valueToDefaultExpr(e) ], "greaterThanOrEqual").asBoolean();
    }
    /**
     * Creates an expression that concatenates an array expression with one or more other arrays.
     *
     * @example
     * ```typescript
     * // Combine the 'items' array with another array field.
     * field("items").arrayConcat(field("otherItems"));
     * ```
     * @param secondArray - Second array expression or array literal to concatenate.
     * @param otherArrays - Optional additional array expressions or array literals to concatenate.
     * @returns A new `Expression` representing the concatenated array.
     */    arrayConcat(e, ...t) {
        const n = [ e, ...t ].map((e => __PRIVATE_valueToDefaultExpr(e)));
        return new x("array_concat", [ this, ...n ], "arrayConcat");
    }
    arrayContains(e) {
        return new x("array_contains", [ this, __PRIVATE_valueToDefaultExpr(e) ], "arrayContains").asBoolean();
    }
    arrayContainsAll(e) {
        const t = Array.isArray(e) ? new __PRIVATE_ListOfExprs(e.map(__PRIVATE_valueToDefaultExpr), "arrayContainsAll") : e;
        return new x("array_contains_all", [ this, t ], "arrayContainsAll").asBoolean();
    }
    arrayContainsAny(e) {
        const t = Array.isArray(e) ? new __PRIVATE_ListOfExprs(e.map(__PRIVATE_valueToDefaultExpr), "arrayContainsAny") : e;
        return new x("array_contains_any", [ this, t ], "arrayContainsAny").asBoolean();
    }
    /**
     * Creates an expression that reverses an array.
     *
     * @example
     * ```typescript
     * // Reverse the value of the 'myArray' field.
     * field("myArray").arrayReverse();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed array.
     */    arrayReverse() {
        return new x("array_reverse", [ this ]);
    }
    /**
     * Creates an expression that calculates the length of an array.
     *
     * @example
     * ```typescript
     * // Get the number of items in the 'cart' array
     * field("cart").arrayLength();
     * ```
     *
     * @returns A new `Expression` representing the length of the array.
     */    arrayLength() {
        return new x("array_length", [ this ], "arrayLength");
    }
    equalAny(e) {
        const t = Array.isArray(e) ? new __PRIVATE_ListOfExprs(e.map(__PRIVATE_valueToDefaultExpr), "equalAny") : e;
        return new x("equal_any", [ this, t ], "equalAny").asBoolean();
    }
    notEqualAny(e) {
        const t = Array.isArray(e) ? new __PRIVATE_ListOfExprs(e.map(__PRIVATE_valueToDefaultExpr), "notEqualAny") : e;
        return new x("not_equal_any", [ this, t ], "notEqualAny").asBoolean();
    }
    /**
     * Creates an expression that checks if a field exists in the document.
     *
     * @example
     * ```typescript
     * // Check if the document has a field named "phoneNumber"
     * field("phoneNumber").exists();
     * ```
     *
     * @returns A new `Expression` representing the 'exists' check.
     */    exists() {
        return new x("exists", [ this ], "exists").asBoolean();
    }
    /**
     * Creates an expression that calculates the character length of a string in UTF-8.
     *
     * @example
     * ```typescript
     * // Get the character length of the 'name' field in its UTF-8 form.
     * field("name").charLength();
     * ```
     *
     * @returns A new `Expression` representing the length of the string.
     */    charLength() {
        return new x("char_length", [ this ], "charLength");
    }
    like(e) {
        return new x("like", [ this, __PRIVATE_valueToDefaultExpr(e) ], "like").asBoolean();
    }
    regexContains(e) {
        return new x("regex_contains", [ this, __PRIVATE_valueToDefaultExpr(e) ], "regexContains").asBoolean();
    }
    regexFind(e) {
        return new x("regex_find", [ this, __PRIVATE_valueToDefaultExpr(e) ], "regexFind");
    }
    regexFindAll(e) {
        return new x("regex_find_all", [ this, __PRIVATE_valueToDefaultExpr(e) ], "regexFindAll");
    }
    regexMatch(e) {
        return new x("regex_match", [ this, __PRIVATE_valueToDefaultExpr(e) ], "regexMatch").asBoolean();
    }
    stringContains(e) {
        return new x("string_contains", [ this, __PRIVATE_valueToDefaultExpr(e) ], "stringContains").asBoolean();
    }
    startsWith(e) {
        return new x("starts_with", [ this, __PRIVATE_valueToDefaultExpr(e) ], "startsWith").asBoolean();
    }
    endsWith(e) {
        return new x("ends_with", [ this, __PRIVATE_valueToDefaultExpr(e) ], "endsWith").asBoolean();
    }
    /**
     * Creates an expression that converts a string to lowercase.
     *
     * @example
     * ```typescript
     * // Convert the 'name' field to lowercase
     * field("name").toLower();
     * ```
     *
     * @returns A new `Expression` representing the lowercase string.
     */    toLower() {
        return new x("to_lower", [ this ], "toLower");
    }
    /**
     * Creates an expression that converts a string to uppercase.
     *
     * @example
     * ```typescript
     * // Convert the 'title' field to uppercase
     * field("title").toUpper();
     * ```
     *
     * @returns A new `Expression` representing the uppercase string.
     */    toUpper() {
        return new x("to_upper", [ this ], "toUpper");
    }
    /**
     * Creates an expression that removes leading and trailing characters from a string or byte array.
     *
     * @example
     * ```typescript
     * // Trim whitespace from the 'userInput' field
     * field("userInput").trim();
     *
     * // Trim quotes from the 'userInput' field
     * field("userInput").trim('"');
     * ```
     * @param valueToTrim - Optional This parameter is treated as a set of characters or bytes that will be
     * trimmed from the input. If not specified, then whitespace will be trimmed.
     * @returns A new `Expression` representing the trimmed string or byte array.
     */    trim(e) {
        const t = [ this ];
        return e && t.push(__PRIVATE_valueToDefaultExpr(e)), new x("trim", t, "trim");
    }
    /**
     * Trims whitespace or a specified set of characters/bytes from the beginning of a string or byte array.
     *
     * @example
     * ```typescript
     * // Trim whitespace from the beginning of the 'userInput' field
     * field("userInput").ltrim();
     *
     * // Trim quotes from the beginning of the 'userInput' field
     * field("userInput").ltrim('"');
     * ```
     *
     * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.
     * If not specified, whitespace will be trimmed.
     * @returns A new `Expression` representing the trimmed string.
     */    ltrim(e) {
        const t = [ this ];
        return e && t.push(__PRIVATE_valueToDefaultExpr(e)), new x("ltrim", t, "ltrim");
    }
    /**
     * Trims whitespace or a specified set of characters/bytes from the end of a string or byte array.
     *
     * @example
     * ```typescript
     * // Trim whitespace from the end of the 'userInput' field
     * field("userInput").rtrim();
     *
     * // Trim quotes from the end of the 'userInput' field
     * field("userInput").rtrim('"');
     * ```
     *
     * @param valueToTrim - Optional. A string or byte array containing the characters/bytes to trim.
     * If not specified, whitespace will be trimmed.
     * @returns A new `Expression` representing the trimmed string or byte array.
     */    rtrim(e) {
        const t = [ this ];
        return e && t.push(__PRIVATE_valueToDefaultExpr(e)), new x("rtrim", t, "rtrim");
    }
    /**
     * Creates an expression that returns the data type of this expression's result, as a string.
     *
     * @remarks
     * This is evaluated on the backend. This means:
     * 1. Generic typed elements (like `array<string>`) evaluate strictly to the primitive `'array'`.
     * 2. Any custom `FirestoreDataConverter` mappings are ignored.
     * 3. For numeric values, the backend does not yield the JavaScript `"number"` type; it evaluates
     *    precisely as `"int64"` or `"float64"`.
     * 4. For date or timestamp objects, the backend evaluates to `"timestamp"`.
     *
     * @example
     * ```typescript
     * // Get the data type of the value in field 'title'
     * field('title').type()
     * ```
     *
     * @returns A new `Expression` representing the data type.
     */    type() {
        return new x("type", [ this ]);
    }
    /**
     * Creates an expression that checks if the result of this expression is of the given type.
     *
     * @remarks Null or undefined fields evaluate to skip/error. Use `ifAbsent()` / `isAbsent()` to evaluate missing data.
     * Supported values for `type` are:
     * `'null'`, `'array'`, `'boolean'`, `'bytes'`, `'timestamp'`, `'geo_point'`, `'number'`,
     * `'int32'`, `'int64'`, `'float64'`, `'decimal128'`, `'map'`, `'reference'`, `'string'`,
     * `'vector'`, `'max_key'`, `'min_key'`, `'object_id'`, `'regex'`, `'request_timestamp'`.
     *
     * @example
     * ```typescript
     * // Check if the 'price' field is specifically an integer (not just 'number')
     * field('price').isType('int64');
     * ```
     *
     * @param type - The type to check for.
     * @returns A new `BooleanExpression` that evaluates to true if the expression's result is of the given type, false otherwise.
     */    isType(e) {
        return new x("is_type", [ this, i(e) ], "isType").asBoolean();
    }
    /**
     * Creates an expression that concatenates string expressions together.
     *
     * @example
     * ```typescript
     * // Combine the 'firstName', " ", and 'lastName' fields into a single string
     * field("firstName").stringConcat(constant(" "), field("lastName"));
     * ```
     *
     * @param secondString - The additional expression or string literal to concatenate.
     * @param otherStrings - Optional additional expressions or string literals to concatenate.
     * @returns A new `Expression` representing the concatenated string.
     */    stringConcat(e, ...t) {
        const n = [ e, ...t ].map(__PRIVATE_valueToDefaultExpr);
        return new x("string_concat", [ this, ...n ], "stringConcat");
    }
    /**
     * Creates an expression that finds the index of the first occurrence of a substring or byte sequence.
     *
     * @example
     * ```typescript
     * // Find the index of "foo" in the 'text' field
     * field("text").stringIndexOf("foo");
     * ```
     *
     * @param search - The substring or byte sequence to search for.
     * @returns A new `Expression` representing the index of the first occurrence.
     */    stringIndexOf(e) {
        return new x("string_index_of", [ this, __PRIVATE_valueToDefaultExpr(e) ], "stringIndexOf");
    }
    /**
     * Creates an expression that repeats a string or byte array a specified number of times.
     *
     * @example
     * ```typescript
     * // Repeat the 'label' field 3 times
     * field("label").stringRepeat(3);
     * ```
     *
     * @param repetitions - The number of times to repeat the string or byte array.
     * @returns A new `Expression` representing the repeated string or byte array.
     */    stringRepeat(e) {
        return new x("string_repeat", [ this, __PRIVATE_valueToDefaultExpr(e) ], "stringRepeat");
    }
    /**
     * Creates an expression that replaces all occurrences of a substring or byte sequence with a replacement.
     *
     * @example
     * ```typescript
     * // Replace all occurrences of "foo" with "bar" in the 'text' field
     * field("text").stringReplaceAll("foo", "bar");
     * ```
     *
     * @param find - The substring or byte sequence to search for.
     * @param replacement - The replacement string or byte sequence.
     * @returns A new `Expression` representing the string or byte array with replacements.
     */    stringReplaceAll(e, t) {
        return new x("string_replace_all", [ this, __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr(t) ], "stringReplaceAll");
    }
    /**
     * Creates an expression that replaces the first occurrence of a substring or byte sequence with a replacement.
     *
     * @example
     * ```typescript
     * // Replace the first occurrence of "foo" with "bar" in the 'text' field
     * field("text").stringReplaceOne("foo", "bar");
     * ```
     *
     * @param find - The substring or byte sequence to search for.
     * @param replacement - The replacement string or byte sequence.
     * @returns A new `Expression` representing the string or byte array with the replacement.
     */    stringReplaceOne(e, t) {
        return new x("string_replace_one", [ this, __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr(t) ], "stringReplaceOne");
    }
    /**
     * Creates an expression that concatenates expression results together.
     *
     * @example
     * ```typescript
     * // Combine the 'firstName', ' ', and 'lastName' fields into a single value.
     * field("firstName").concat(constant(" "), field("lastName"));
     * ```
     *
     * @param second - The additional expression or literal to concatenate.
     * @param others - Optional additional expressions or literals to concatenate.
     * @returns A new `Expression` representing the concatenated value.
     */    concat(e, ...t) {
        const n = [ e, ...t ].map(__PRIVATE_valueToDefaultExpr);
        return new x("concat", [ this, ...n ], "concat");
    }
    /**
     * Creates an expression that reverses this string expression.
     *
     * @example
     * ```typescript
     * // Reverse the value of the 'myString' field.
     * field("myString").reverse();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.
     */    reverse() {
        return new x("reverse", [ this ], "reverse");
    }
    /**
     * Filters the array using a provided alias and predicate expression.
     *
     * @example
     * ```typescript
     * // Filter the 'items' array to only include those where the 'price' is greater than 10
     * field("items").arrayFilter('item', greaterThan(variable('item.price'), 10));
     * ```
     *
     * @param alias - The variable name to use for each element.
     * @param filter - The predicate boolean expression to filter by.
     * @returns A new `Expression` representing the filtered array.
     */    arrayFilter(e, t) {
        return new x("array_filter", [ this, __PRIVATE_valueToDefaultExpr(e), t ], "arrayFilter");
    }
    /**
     * Creates an expression that applies a provided transformation to each element in an array.
     *
     * @example
     * ```typescript
     * // Transform the 'scores' array by multiplying each score by 10
     * field("scores").arrayTransform("score", multiply(variable("score"), 10));
     * ```
     *
     * @param elementAlias - The variable name to use for each element.
     * @param transform - The lambda expression used to transform the elements.
     * @returns A new `Expression` representing the arrayTransform operation.
     */    arrayTransform(e, t) {
        return new x("array_transform", [ this, __PRIVATE_valueToDefaultExpr(e), t ], "arrayTransform");
    }
    /**
     * Creates an expression that applies a provided transformation to each element in an array, providing the element's index to the transformation expression.
     *
     * @example
     * ```typescript
     * // Transform the 'scores' array by adding the index to each score
     * field("scores").arrayTransformWithIndex("score", "i", add(variable("score"), variable("i")));
     * ```
     *
     * @param elementAlias - The variable name to use for each element.
     * @param indexAlias - The variable name to use for the current index.
     * @param transform - The lambda expression used to transform the elements.
     * @returns A new `Expression` representing the arrayTransformWithIndex operation.
     */    arrayTransformWithIndex(e, t, n) {
        return new x("array_transform", [ this, __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr(t), n ], "arrayTransformWithIndex");
    }
    /**
     * Returns a subset of the array.
     *
     * @example
     * ```typescript
     * // Get 5 elements from the 'items' array starting from index 2
     * field("items").arraySlice(2, 5);
     *
     * // Get n number of elements from the 'items' array starting from index 2
     * field("items").arraySlice(2, field("count"));
     * ```
     *
     * @param offset - The starting offset.
     * @param length - The optional length of the slice.
     * @returns A new `Expression` representing the sliced array.
     */    arraySlice(e, t) {
        const n = [ this, __PRIVATE_valueToDefaultExpr(e) ];
        return void 0 !== t && n.push(__PRIVATE_valueToDefaultExpr(t)), new x("array_slice", n, "arraySlice");
    }
    /**
     * Returns the first element of the array.
     *
     * @example
     * ```typescript
     * // Get the first element of the 'myArray' field.
     * field("myArray").arrayFirst();
     * ```
     *
     * @returns A new `Expression` representing the first element.
     */    arrayFirst() {
        return new x("array_first", [ this ], "arrayFirst");
    }
    arrayFirstN(e) {
        return new x("array_first_n", [ this, __PRIVATE_valueToDefaultExpr(e) ], "arrayFirstN");
    }
    /**
     * Returns the last element of the array.
     *
     * @example
     * ```typescript
     * // Get the last element of the 'myArray' field.
     * field("myArray").arrayLast();
     * ```
     *
     * @returns A new `Expression` representing the last element.
     */    arrayLast() {
        return new x("array_last", [ this ], "arrayLast");
    }
    arrayLastN(e) {
        return new x("array_last_n", [ this, __PRIVATE_valueToDefaultExpr(e) ], "arrayLastN");
    }
    /**
     * Returns the maximum value in the array.
     *
     * @example
     * ```typescript
     * // Get the maximum value of the 'myArray' field.
     * field("myArray").arrayMaximum();
     * ```
     *
     * @returns A new `Expression` representing the maximum value.
     */    arrayMaximum() {
        return new x("maximum", [ this ], "arrayMaximum");
    }
    arrayMaximumN(e) {
        return new x("maximum_n", [ this, __PRIVATE_valueToDefaultExpr(e) ], "arrayMaximumN");
    }
    /**
     * Returns the minimum value in the array.
     *
     * @example
     * ```typescript
     * // Get the minimum value of the 'myArray' field.
     * field("myArray").arrayMinimum();
     * ```
     *
     * @returns A new `Expression` representing the minimum value.
     */    arrayMinimum() {
        return new x("minimum", [ this ], "arrayMinimum");
    }
    arrayMinimumN(e) {
        return new x("minimum_n", [ this, __PRIVATE_valueToDefaultExpr(e) ], "arrayMinimumN");
    }
    arrayIndexOf(e) {
        return new x("array_index_of", [ this, __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr("first") ], "arrayIndexOf");
    }
    arrayLastIndexOf(e) {
        return new x("array_index_of", [ this, __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr("last") ], "arrayLastIndexOf");
    }
    arrayIndexOfAll(e) {
        return new x("array_index_of_all", [ this, __PRIVATE_valueToDefaultExpr(e) ], "arrayIndexOfAll");
    }
    /**
     * Creates an expression that calculates the length of this string expression in bytes.
     *
     * @example
     * ```typescript
     * // Calculate the length of the 'myString' field in bytes.
     * field("myString").byteLength();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the string in bytes.
     */    byteLength() {
        return new x("byte_length", [ this ], "byteLength");
    }
    /**
     * Creates an expression that computes the ceiling of a numeric value.
     *
     * @example
     * ```typescript
     * // Compute the ceiling of the 'price' field.
     * field("price").ceil();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the ceiling of the numeric value.
     */    ceil() {
        return new x("ceil", [ this ]);
    }
    /**
     * Creates an expression that computes the floor of a numeric value.
     *
     * @example
     * ```typescript
     * // Compute the floor of the 'price' field.
     * field("price").floor();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the floor of the numeric value.
     */    floor() {
        return new x("floor", [ this ]);
    }
    /**
     * Creates an expression that computes the absolute value of a numeric value.
     *
     * @example
     * ```typescript
     * // Compute the absolute value of the 'price' field.
     * field("price").abs();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the absolute value of the numeric value.
     */    abs() {
        return new x("abs", [ this ]);
    }
    /**
     * Creates an expression that computes e to the power of this expression.
     *
     * @example
     * ```typescript
     * // Compute e to the power of the 'value' field.
     * field("value").exp();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the exp of the numeric value.
     */    exp() {
        return new x("exp", [ this ]);
    }
    /**
     * Accesses a value from a map (object) field using the provided key.
     *
     * @example
     * ```typescript
     * // Get the 'city' value from the 'address' map field
     * field("address").mapGet("city");
     * ```
     *
     * @param subfield - The key to access in the map.
     * @returns A new `Expression` representing the value associated with the given key in the map.
     */    mapGet(e) {
        return new x("map_get", [ this, i(e) ], "mapGet");
    }
    /**
     * Creates an expression that returns a new map with the specified entries added or updated.
     *
     * @remarks
     * Note that `mapSet` only performs shallow updates to the map. Setting a value to `null`
     * will retain the key with a `null` value. To remove a key entirely, use `mapRemove`.
     *
     * @example
     * ```typescript
     * // Set the 'city' to "San Francisco" in the 'address' map
     * field("address").mapSet("city", "San Francisco");
     * ```
     *
     * @param key - The key to set. Must be a string or a constant string expression.
     * @param value - The value to set.
     * @param moreKeyValues - Additional key-value pairs to set.
     * @returns A new `Expression` representing the map with the entries set.
     */    mapSet(e, t, ...n) {
        const r = [ this, __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr(t), ...n.map(__PRIVATE_valueToDefaultExpr) ];
        return new x("map_set", r, "mapSet");
    }
    /**
     * Creates an expression that returns the keys of a map.
     *
     * @remarks
     * While the backend generally preserves insertion order, relying on the
     * order of the output array is not guaranteed and should be avoided.
     *
     * @example
     * ```typescript
     * // Get the keys of the 'address' map
     * field("address").mapKeys();
     * ```
     *
     * @returns A new `Expression` representing the keys of the map.
     */    mapKeys() {
        return new x("map_keys", [ this ], "mapKeys");
    }
    /**
     * Creates an expression that returns the values of a map.
     *
     * @remarks
     * While the backend generally preserves insertion order, relying on the
     * order of the output array is not guaranteed and should be avoided.
     *
     * @example
     * ```typescript
     * // Get the values of the 'address' map
     * field("address").mapValues();
     * ```
     *
     * @returns A new `Expression` representing the values of the map.
     */    mapValues() {
        return new x("map_values", [ this ], "mapValues");
    }
    /**
     * Creates an expression that returns the entries of a map as an array of maps,
     * where each map contains a `"k"` property for the key and a `"v"` property for the value.
     * For example: `[{ k: "key1", v: "value1" }, ...]`.
     *
     * @example
     * ```typescript
     * // Get the entries of the 'address' map
     * field("address").mapEntries();
     * ```
     *
     * @returns A new `Expression` representing the entries of the map.
     */    mapEntries() {
        return new x("map_entries", [ this ], "mapEntries");
    }
    /**
     * @public
     * Creates an expression that returns the value of a field from the document that results from the evaluation of this expression.
     *
     * @example
     * ```typescript
     * // Get the value of the "city" field in the "address" document.
     * field("address").getField("city")
     * ```
     *
     * @param key The field to access in the document.
     * @returns A new `Expression` representing the value of the field in the document.
     */    getField(e) {
        return new x("get_field", [ this, __PRIVATE_valueToDefaultExpr(e) ], "get_field");
    }
    /**
     * Creates an aggregation that counts the number of stage inputs with valid evaluations of the
     * expression or field.
     *
     * @example
     * ```typescript
     * // Count the total number of products
     * field("productId").count().as("totalProducts");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'count' aggregation.
     */    count() {
        return k._create("count", [ this ], "count");
    }
    /**
     * Creates an aggregation that calculates the sum of a numeric field across multiple stage inputs.
     *
     * @example
     * ```typescript
     * // Calculate the total revenue from a set of orders
     * field("orderAmount").sum().as("totalRevenue");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'sum' aggregation.
     */    sum() {
        return k._create("sum", [ this ], "sum");
    }
    /**
     * Creates an aggregation that calculates the average (mean) of a numeric field across multiple
     * stage inputs.
     *
     * @example
     * ```typescript
     * // Calculate the average age of users
     * field("age").average().as("averageAge");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'average' aggregation.
     */    average() {
        return k._create("average", [ this ], "average");
    }
    /**
     * Creates an aggregation that finds the minimum value of a field across multiple stage inputs.
     *
     * @example
     * ```typescript
     * // Find the lowest price of all products
     * field("price").minimum().as("lowestPrice");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'minimum' aggregation.
     */    minimum() {
        return k._create("minimum", [ this ], "minimum");
    }
    /**
     * Creates an aggregation that finds the maximum value of a field across multiple stage inputs.
     *
     * @example
     * ```typescript
     * // Find the highest score in a leaderboard
     * field("score").maximum().as("highestScore");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'maximum' aggregation.
     */    maximum() {
        return k._create("maximum", [ this ], "maximum");
    }
    /**
     * Creates an aggregation that finds the first value of an expression across multiple stage inputs.
     *
     * @example
     * ```typescript
     * // Find the first value of the 'rating' field
     * field("rating").first().as("firstRating");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'first' aggregation.
     */    first() {
        return k._create("first", [ this ], "first");
    }
    /**
     * Creates an aggregation that finds the last value of an expression across multiple stage inputs.
     *
     * @example
     * ```typescript
     * // Find the last value of the 'rating' field
     * field("rating").last().as("lastRating");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'last' aggregation.
     */    last() {
        return k._create("last", [ this ], "last");
    }
    /**
     * Creates an aggregation that collects all values of an expression across multiple stage inputs
     * into an array.
     *
     * @remarks
     * If the expression resolves to an absent value, it is converted to `null`.
     * The order of elements in the output array is not stable and shouldn't be relied upon.
     *
     * @example
     * ```typescript
     * // Collect all tags from books into an array
     * field("tags").arrayAgg().as("allTags");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'array_agg' aggregation.
     */    arrayAgg() {
        return k._create("array_agg", [ this ], "arrayAgg");
    }
    /**
     * Creates an aggregation that collects all distinct values of an expression across multiple stage
     * inputs into an array.
     *
     * @remarks
     * If the expression resolves to an absent value, it is converted to `null`.
     * The order of elements in the output array is not stable and shouldn't be relied upon.
     *
     * @example
     * ```typescript
     * // Collect all distinct tags from books into an array
     * field("tags").arrayAggDistinct().as("allDistinctTags");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'array_agg_distinct' aggregation.
     */    arrayAggDistinct() {
        return k._create("array_agg_distinct", [ this ], "arrayAggDistinct");
    }
    /**
     * Creates an aggregation that counts the number of distinct values of the expression or field.
     *
     * @example
     * ```typescript
     * // Count the distinct number of products
     * field("productId").countDistinct().as("distinctProducts");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation.
     */    countDistinct() {
        return k._create("count_distinct", [ this ], "countDistinct");
    }
    /**
     * Creates an expression that returns the larger value between this expression and another expression, based on Firestore's value type ordering.
     *
     * @example
     * ```typescript
     * // Returns the larger value between the 'timestamp' field and the current timestamp.
     * field("timestamp").logicalMaximum(currentTimestamp());
     * ```
     *
     * @param second - The second expression or literal to compare with.
     * @param others - Optional additional expressions or literals to compare with.
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical maximum operation.
     */    logicalMaximum(e, ...t) {
        const n = [ e, ...t ];
        return new x("maximum", [ this, ...n.map(__PRIVATE_valueToDefaultExpr) ], "logicalMaximum");
    }
    /**
     * Creates an expression that returns the smaller value between this expression and another expression, based on Firestore's value type ordering.
     *
     * @example
     * ```typescript
     * // Returns the smaller value between the 'timestamp' field and the current timestamp.
     * field("timestamp").logicalMinimum(currentTimestamp());
     * ```
     *
     * @param second - The second expression or literal to compare with.
     * @param others - Optional additional expressions or literals to compare with.
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical minimum operation.
     */    logicalMinimum(e, ...t) {
        const n = [ e, ...t ];
        return new x("minimum", [ this, ...n.map(__PRIVATE_valueToDefaultExpr) ], "minimum");
    }
    /**
     * Creates an expression that calculates the length (number of dimensions) of this Firestore Vector expression.
     *
     * @example
     * ```typescript
     * // Get the vector length (dimension) of the field 'embedding'.
     * field("embedding").vectorLength();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the length of the vector.
     */    vectorLength() {
        return new x("vector_length", [ this ], "vectorLength");
    }
    cosineDistance(e) {
        return new x("cosine_distance", [ this, __PRIVATE_vectorToExpr(e) ], "cosineDistance");
    }
    dotProduct(e) {
        return new x("dot_product", [ this, __PRIVATE_vectorToExpr(e) ], "dotProduct");
    }
    euclideanDistance(e) {
        return new x("euclidean_distance", [ this, __PRIVATE_vectorToExpr(e) ], "euclideanDistance");
    }
    /**
     * Creates an expression that interprets this expression as the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC)
     * and returns a timestamp.
     *
     * @example
     * ```typescript
     * // Interpret the 'microseconds' field as microseconds since epoch.
     * field("microseconds").unixMicrosToTimestamp();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.
     */    unixMicrosToTimestamp() {
        return new x("unix_micros_to_timestamp", [ this ], "unixMicrosToTimestamp");
    }
    /**
     * Creates an expression that converts this timestamp expression to the number of microseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
     *
     * @example
     * ```typescript
     * // Convert the 'timestamp' field to microseconds since epoch.
     * field("timestamp").timestampToUnixMicros();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of microseconds since epoch.
     */    timestampToUnixMicros() {
        return new x("timestamp_to_unix_micros", [ this ], "timestampToUnixMicros");
    }
    /**
     * Creates an expression that interprets this expression as the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC)
     * and returns a timestamp.
     *
     * @example
     * ```typescript
     * // Interpret the 'milliseconds' field as milliseconds since epoch.
     * field("milliseconds").unixMillisToTimestamp();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.
     */    unixMillisToTimestamp() {
        return new x("unix_millis_to_timestamp", [ this ], "unixMillisToTimestamp");
    }
    /**
     * Creates an expression that converts this timestamp expression to the number of milliseconds since the Unix epoch (1970-01-01 00:00:00 UTC).
     *
     * @example
     * ```typescript
     * // Convert the 'timestamp' field to milliseconds since epoch.
     * field("timestamp").timestampToUnixMillis();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of milliseconds since epoch.
     */    timestampToUnixMillis() {
        return new x("timestamp_to_unix_millis", [ this ], "timestampToUnixMillis");
    }
    /**
     * Creates an expression that interprets this expression as the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC)
     * and returns a timestamp.
     *
     * @example
     * ```typescript
     * // Interpret the 'seconds' field as seconds since epoch.
     * field("seconds").unixSecondsToTimestamp();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the timestamp.
     */    unixSecondsToTimestamp() {
        return new x("unix_seconds_to_timestamp", [ this ], "unixSecondsToTimestamp");
    }
    /**
     * Creates an expression that converts this timestamp expression to the number of seconds since the Unix epoch (1970-01-01 00:00:00 UTC).
     *
     * @example
     * ```typescript
     * // Convert the 'timestamp' field to seconds since epoch.
     * field("timestamp").timestampToUnixSeconds();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the number of seconds since epoch.
     */    timestampToUnixSeconds() {
        return new x("timestamp_to_unix_seconds", [ this ], "timestampToUnixSeconds");
    }
    timestampAdd(e, t) {
        return new x("timestamp_add", [ this, __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr(t) ], "timestampAdd");
    }
    timestampSubtract(e, t) {
        return new x("timestamp_subtract", [ this, __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr(t) ], "timestampSubtract");
    }
    timestampDiff(e, t) {
        return new x("timestamp_diff", [ this, __PRIVATE_fieldOrExpression(e), __PRIVATE_valueToDefaultExpr(t) ], "timestampDiff");
    }
    timestampExtract(e, t) {
        const n = [ this, __PRIVATE_valueToDefaultExpr(e) ];
        return t && n.push(__PRIVATE_valueToDefaultExpr(t)), new x("timestamp_extract", n, "timestampExtract");
    }
    /**
     *
     * Creates an expression that returns the document ID from a path.
     *
     * @example
     * ```typescript
     * // Get the document ID from a path.
     * field("__path__").documentId();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the documentId operation.
     */    documentId() {
        return new x("document_id", [ this ], "documentId");
    }
    /**
     *
     * Creates an expression that returns the parent document reference of a document reference.
     *
     * @example
     * ```typescript
     * // Get the parent document reference of a document reference.
     * field("__path__").parent();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the parent operation.
     */    parent() {
        return new x("parent", [ this ], "parent");
    }
    substring(e, t) {
        const n = __PRIVATE_valueToDefaultExpr(e);
        return new x("substring", void 0 === t ? [ this, n ] : [ this, n, __PRIVATE_valueToDefaultExpr(t) ], "substring");
    }
    arrayGet(e) {
        return new x("array_get", [ this, __PRIVATE_valueToDefaultExpr(e) ], "arrayGet");
    }
    /**
     *
     * Creates an expression that checks if a given expression produces an error.
     *
     * @example
     * ```typescript
     * // Check if the result of a calculation is an error
     * field("title").arrayContains(1).isError();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isError' check.
     */    isError() {
        return new x("is_error", [ this ], "isError").asBoolean();
    }
    ifError(e) {
        const t = new x("if_error", [ this, __PRIVATE_valueToDefaultExpr(e) ], "ifError");
        return e instanceof BooleanExpression ? t.asBoolean() : t;
    }
    /**
     *
     * Creates an expression that returns `true` if the result of this expression
     * is absent. Otherwise, returns `false` even if the value is `null`.
     *
     * @example
     * ```typescript
     * // Check if the field `value` is absent.
     * field("value").isAbsent();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the 'isAbsent' check.
     */    isAbsent() {
        return new x("is_absent", [ this ], "isAbsent").asBoolean();
    }
    mapRemove(e) {
        return new x("map_remove", [ this, __PRIVATE_valueToDefaultExpr(e) ], "mapRemove");
    }
    /**
     *
     * Creates an expression that merges multiple map values.
     *
     * @example
     * ```
     * // Merges the map in the settings field with, a map literal, and a map in
     * // that is conditionally returned by another expression
     * field('settings').mapMerge({ enabled: true }, conditional(field('isAdmin'), { admin: true}, {})
     * ```
     *
     * @param secondMap - A required second map to merge. Represented as a literal or
     * an expression that returns a map.
     * @param otherMaps - Optional additional maps to merge. Each map is represented
     * as a literal or an expression that returns a map.
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'mapMerge' operation.
     */    mapMerge(e, ...t) {
        const n = __PRIVATE_valueToDefaultExpr(e), r = t.map(__PRIVATE_valueToDefaultExpr);
        return new x("map_merge", [ this, n, ...r ], "mapMerge");
    }
    pow(e) {
        return new x("pow", [ this, __PRIVATE_valueToDefaultExpr(e) ]);
    }
    trunc(e) {
        return void 0 === e ? new x("trunc", [ this ]) : new x("trunc", [ this, __PRIVATE_valueToDefaultExpr(e) ], "trunc");
    }
    round(e) {
        return void 0 === e ? new x("round", [ this ]) : new x("round", [ this, __PRIVATE_valueToDefaultExpr(e) ], "round");
    }
    /**
     * Creates an expression that returns the collection ID from a path.
     *
     * @example
     * ```typescript
     * // Get the collection ID from a path.
     * field("__path__").collectionId();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the collectionId operation.
     */    collectionId() {
        return new x("collection_id", [ this ]);
    }
    /**
     * Creates an expression that calculates the length of a string, array, map, vector, or bytes.
     *
     * @example
     * ```typescript
     * // Get the length of the 'name' field.
     * field("name").length();
     *
     * // Get the number of items in the 'cart' array.
     * field("cart").length();
     * ```
     *
     * @returns A new `Expression` representing the length of the string, array, map, vector, or bytes.
     */    length() {
        return new x("length", [ this ]);
    }
    /**
     * Creates an expression that computes the natural logarithm of a numeric value.
     *
     * @example
     * ```typescript
     * // Compute the natural logarithm of the 'value' field.
     * field("value").ln();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the natural logarithm of the numeric value.
     */    ln() {
        return new x("ln", [ this ]);
    }
    /**
     * Creates an expression that computes the square root of a numeric value.
     *
     * @example
     * ```typescript
     * // Compute the square root of the 'value' field.
     * field("value").sqrt();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the square root of the numeric value.
     */    sqrt() {
        return new x("sqrt", [ this ]);
    }
    /**
     * Creates an expression that reverses a string.
     *
     * @example
     * ```typescript
     * // Reverse the value of the 'myString' field.
     * field("myString").stringReverse();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the reversed string.
     */    stringReverse() {
        return new x("string_reverse", [ this ]);
    }
    ifAbsent(e) {
        return new x("if_absent", [ this, __PRIVATE_valueToDefaultExpr(e) ], "ifAbsent");
    }
    ifNull(e) {
        return new x("if_null", [ this, __PRIVATE_valueToDefaultExpr(e) ], "ifNull");
    }
    /**
     * Creates an expression that returns the first non-null, non-absent argument, without evaluating
     * the rest of the arguments. When all arguments are null or absent, returns the last argument.
     *
     * @example
     * ```typescript
     * // Returns the value of the first non-null, non-absent field among 'preferredName', 'fullName',
     * // or the last argument if all previous fields are null.
     * field("preferredName").coalesce(field("fullName"), "Anonymous");
     * ```
     *
     * @param replacement - The value to use if this expression evaluates to null.
     * @param others - Optional additional values to check if previous values are null.
     * @returns A new `Expression` representing the coalesce operation.
     */    coalesce(e, ...t) {
        return new x("coalesce", [ this, __PRIVATE_valueToDefaultExpr(e), ...t.map(__PRIVATE_valueToDefaultExpr) ], "coalesce");
    }
    join(e) {
        return new x("join", [ this, __PRIVATE_valueToDefaultExpr(e) ], "join");
    }
    /**
     * Creates an expression that computes the base-10 logarithm of a numeric value.
     *
     * @example
     * ```typescript
     * // Compute the base-10 logarithm of the 'value' field.
     * field("value").log10();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the base-10 logarithm of the numeric value.
     */    log10() {
        return new x("log10", [ this ]);
    }
    /**
     * Creates an expression that computes the sum of the elements in an array.
     *
     * @example
     * ```typescript
     * // Compute the sum of the elements in the 'scores' field.
     * field("scores").arraySum();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the sum of the elements in the array.
     */    arraySum() {
        return new x("sum", [ this ]);
    }
    split(e) {
        return new x("split", [ this, __PRIVATE_valueToDefaultExpr(e) ]);
    }
    timestampTruncate(e, t) {
        const n = [ this, __PRIVATE_valueToDefaultExpr(e) ];
        return t && n.push(__PRIVATE_valueToDefaultExpr(t)), new x("timestamp_trunc", n);
    }
    // TODO(search) enable with backend support
    // /**
    //  * Evaluates if the result of this `expression` is between
    //  * the `lowerBound` (inclusive) and `upperBound` (inclusive).
    //  *
    //  * @example
    //  * ```
    //  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4
    //  * field('tireWidth').between(constant(2.2), constant(2.4))
    //  *
    //  * // This is functionally equivalent to
    //  * and(field('tireWidth').greaterThanOrEqual(contant(2.2)), field('tireWidth').lessThanOrEqual(constant(2.4)))
    //  * ```
    //  *
    //  * @param lowerBound - Lower bound (inclusive) of the range.
    //  * @param upperBound - Upper bound (inclusive) of the range.
    //  */
    // between(lowerBound: Expression, upperBound: Expression): BooleanExpression;
    // /**
    //  * Evaluates if the result of this `expression` is between
    //  * the `lowerBound` (inclusive) and `upperBound` (inclusive).
    //  *
    //  * @example
    //  * ```
    //  * // Evaluate if the 'tireWidth' is between 2.2 and 2.4
    //  * field('tireWidth').between(2.2, 2.4)
    //  *
    //  * // This is functionally equivalent to
    //  * and(field('tireWidth').greaterThanOrEqual(2.2), field('tireWidth').lessThanOrEqual(2.4))
    //  * ```
    //  *
    //  * @param lowerBound - Lower bound (inclusive) of the range.
    //  * @param upperBound - Upper bound (inclusive) of the range.
    //  */
    // between(lowerBound: unknown, upperBound: unknown): BooleanExpression;
    // between(lowerBound: unknown, upperBound: unknown): BooleanExpression {
    //   return new FunctionExpression('between', [
    //     this,
    //     valueToDefaultExpr(lowerBound),
    //     valueToDefaultExpr(upperBound)
    //   ]).asBoolean();
    // }
    // TODO(search) enable with backend support
    // /**
    //  * Evaluates to an HTML-formatted text snippet that renders terms matching
    //  * the search query in `<b>bold</b>`.
    //  *
    //  * @remarks This Expression can only be used within a `search` stage.
    //  *
    //  * @param rquery Define the search query using the search domain-specific language (DSL).
    //  */
    // snippet(rquery: string): Expression;
    // /**
    //  * Evaluates to an HTML-formatted text snippet that renders terms matching
    //  * the search query in `<b>bold</b>`.
    //  *
    //  * @remarks This Expression can only be used within a `search` stage.
    //  *
    //  * @param options Define how snippeting behaves.
    //  */
    // snippet(options: SnippetOptions): Expression;
    // snippet(queryOrOptions: string | SnippetOptions): Expression {
    //   const options: SnippetOptions = isString(queryOrOptions)
    //     ? { rquery: queryOrOptions }
    //     : queryOrOptions;
    //   const rquery = options.rquery;
    //   const internalOptions = {
    //     maxSnippetWidth: options.maxSnippetWidth,
    //     maxSnippets: options.maxSnippets,
    //     separator: options.separator
    //   };
    //   return new SnippetExpression([this, constant(rquery)], internalOptions);
    // }
    // TODO(new-expression): Add new expression method definitions above this line
    /**
     * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in ascending order based on this expression.
     *
     * @example
     * ```typescript
     * // Sort documents by the 'name' field in ascending order
     * firestore.pipeline().collection("users")
     *   .sort(field("name").ascending());
     * ```
     *
     * @returns A new `Ordering` for ascending sorting.
     */
    ascending() {
        return ascending(this);
    }
    /**
     * Creates an {@link @firebase/firestore/pipelines#Ordering} that sorts documents in descending order based on this expression.
     *
     * @example
     * ```typescript
     * // Sort documents by the 'createdAt' field in descending order
     * firestore.pipeline().collection("users")
     *   .sort(field("createdAt").descending());
     * ```
     *
     * @returns A new `Ordering` for descending sorting.
     */    descending() {
        return descending(this);
    }
    /**
     * Assigns an alias to this expression.
     *
     * Aliases are useful for renaming fields in the output of a stage or for giving meaningful
     * names to calculated values.
     *
     * @example
     * ```typescript
     * // Calculate the total price and assign it the alias "totalPrice" and add it to the output.
     * firestore.pipeline().collection("items")
     *   .addFields(field("price").multiply(field("quantity")).as("totalPrice"));
     * ```
     *
     * @param name - The alias to assign to this expression.
     * @returns A new {@link @firebase/firestore/pipelines#AliasedExpression} that wraps this
     *     expression and associates it with the provided alias.
     */    as(e) {
        return new c(this, e, "as");
    }
}

/**
 *
 * A class that represents an aggregate function.
 */ class k {
    constructor(e, t) {
        this.name = e, this.params = t, this.exprType = "AggregateFunction", this._protoValueType = "ProtoValue";
    }
    /**
     * @internal
     * @private
     */    static _create(e, t, n) {
        const r = new k(e, t);
        return r._methodName = n, r;
    }
    /**
     * Assigns an alias to this AggregateFunction. The alias specifies the name that
     * the aggregated value will have in the output document.
     *
     * @example
     * ```typescript
     * // Calculate the average price of all items and assign it the alias "averagePrice".
     * firestore.pipeline().collection("items")
     *   .aggregate(field("price").average().as("averagePrice"));
     * ```
     *
     * @param name - The alias to assign to this AggregateFunction.
     * @returns A new {@link @firebase/firestore/pipelines#AliasedAggregate} that wraps this
     *     AggregateFunction and associates it with the provided alias.
     */    as(e) {
        return new AliasedAggregate(this, e, "as");
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        return {
            functionValue: {
                name: this.name,
                args: this.params.map((t => t._toProto(e)))
            }
        };
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {
        e = this._methodName ? e.contextWith({
            methodName: this._methodName
        }) : e, this.params.forEach((t => t._readUserData(e)));
    }
}

/**
 *
 * An AggregateFunction with alias.
 */ class AliasedAggregate {
    constructor(e, t, n) {
        this.aggregate = e, this.alias = t, this._methodName = n;
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {
        this.aggregate._readUserData(e);
    }
}

class c {
    constructor(e, t, n) {
        this.expr = e, this.alias = t, this._methodName = n, this.exprType = "AliasedExpression", 
        this.selectable = true;
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {
        this.expr._readUserData(e);
    }
}

/**
 * @internal
 */ class __PRIVATE_ListOfExprs extends t {
    constructor(e, t) {
        super(), this.ur = e, this._methodName = t, this.expressionType = "ListOfExpressions";
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        return {
            arrayValue: {
                values: this.ur.map((t => t._toProto(e)))
            }
        };
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {
        this.ur.forEach((t => t._readUserData(e)));
    }
}

/**
 *
 * Represents a reference to a field in a Firestore document, or outputs of a {@link @firebase/firestore/pipelines#Pipeline} stage.
 *
 * <p>Field references are used to access document field values in expressions and to specify fields
 * for sorting, filtering, and projecting data in Firestore pipelines.
 *
 * <p>You can create a `Field` instance using the static {@link @firebase/firestore/pipelines#field} method:
 *
 * @example
 * ```typescript
 * // Create a Field instance for the 'name' field
 * const nameField = field("name");
 *
 * // Create a Field instance for a nested field 'address.city'
 * const cityField = field("address.city");
 * ```
 */ class o extends t {
    /**
     * @internal
     * @private
     * @hideconstructor
     * @param fieldPath
     */
    constructor(e, t) {
        super(), this.fieldPath = e, this._methodName = t, this.expressionType = "Field", 
        this.selectable = true;
    }
    get _fieldPath() {
        return this.fieldPath;
    }
    get fieldName() {
        return this.fieldPath.canonicalString();
    }
    get alias() {
        return this.fieldName;
    }
    get expr() {
        return this;
    }
    // TODO(search) enable with backend support
    // /**
    //  * Perform a full-text search on this field.
    //  *
    //  * @remarks This Expression can only be used within a `search` stage.
    //  *
    //  * @param rquery Define the search query using the search domain-specific language (DSL).
    //  */
    // matches(rquery: string | Expression): BooleanExpression {
    //   return new FunctionExpression(
    //     'matches',
    //     [this, valueToDefaultExpr(rquery)],
    //     'matches'
    //   ).asBoolean();
    // }
    /**
     * @beta
     * Evaluates to the distance in meters between the location specified
     * by this field and the query location.
     *
     * @remarks This Expression can only be used within a `search` stage.
     *
     * @param location - Compute distance to this GeoPoint.
     */
    geoDistance(e) {
        return new x("geo_distance", [ this, __PRIVATE_valueToDefaultExpr(e) ], "geoDistance");
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        return {
            fieldReferenceValue: this.fieldPath.canonicalString()
        };
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {}
}

function e(e) {
    return G(e, "field");
}

function G(e, t) {
    return new o("string" == typeof e ? Ce === e ? documentId$1()._internalPath : ta("field", e) : e._internalPath, t);
}

/**
 * @internal
 *
 * Represents a constant value that can be used in a Firestore pipeline expression.
 *
 * You can create a `Constant` instance using the static {@link @firebase/firestore/pipelines#field} method:
 *
 * @example
 * ```typescript
 * // Create a Constant instance for the number 10
 * const ten = constant(10);
 *
 * // Create a Constant instance for the string "hello"
 * const hello = constant("hello");
 * ```
 */ class Constant extends t {
    /**
     * @private
     * @internal
     * @hideconstructor
     * @param value - The value of the constant.
     */
    constructor(e, t) {
        super(), this.value = e, this._methodName = t, this.expressionType = "Constant";
    }
    /**
     * @private
     * @internal
     */    static _fromProto(e) {
        const t = new Constant(e, void 0);
        return t._protoValue = e, t;
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        return __PRIVATE_hardAssert(void 0 !== this._protoValue, 237), this._protoValue;
    }
    _getValue() {
        return this._protoValue;
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {
        e = this._methodName ? e.contextWith({
            methodName: this._methodName
        }) : e, u(this._protoValue) || (this._protoValue = __PRIVATE_parseData(this.value, e));
    }
}

function i(e, t) {
    return m(e, "constant");
}

/**
 * @internal
 * @private
 * @param value
 * @param methodName
 */ function m(e, t) {
    const n = new Constant(e, t);
    return "boolean" == typeof e ? new __PRIVATE_BooleanConstant(n) : n;
}

/**
 * Internal only
 * @internal
 * @private
 */ class MapValue extends t {
    constructor(e, t) {
        super(), this.cr = e, this._methodName = t, this.expressionType = "Constant";
    }
    _readUserData(e) {
        e = this._methodName ? e.contextWith({
            methodName: this._methodName
        }) : e, this.cr.forEach((t => {
            t._readUserData(e);
        }));
    }
    _toProto(e) {
        return toMapValue(e, this.cr);
    }
}

/**
 *
 * This class defines the base class for Firestore {@link @firebase/firestore/pipelines#Pipeline} functions, which can be evaluated within pipeline
 * execution.
 *
 * Typically, you would not use this class or its children directly. Use either the functions like {@link @firebase/firestore/pipelines#and}, {@link @firebase/firestore/pipelines#(equal:1)},
 * or the methods on {@link @firebase/firestore/pipelines#Expression} ({@link @firebase/firestore/pipelines#Expression.(equal:1)}, {@link @firebase/firestore/pipelines#Expression.(lessThan:1)}, etc.) to construct new Function instances.
 */ class x extends t {
    /**
     * @hideconstructor
     */
    constructor(e, t, n, r) {
        super(), this.name = e, this.params = t, this.expressionType = "Function", 
        /**
         * @private
         * @internal
         */
        this._optionsProto = void 0, void 0 !== n && (this._methodName = n), void 0 !== r && (this._options = r);
    }
    /**
     * @private
     * @internal
     */    get _optionsUtil() {
        return new OptionsUtil({});
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        const t = {
            functionValue: {
                name: this.name,
                args: this.params.map((t => t._toProto(e)))
            }
        };
        return this._optionsProto && (t.functionValue.options = this._optionsProto), t;
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {
        e = this._methodName ? e.contextWith({
            methodName: this._methodName
        }) : e, this.params.forEach((t => t._readUserData(e))), this._options && (this._optionsProto = this._optionsUtil.getOptionsProto(e, this._options));
    }
}

/**
 *
 * An interface that represents a filter condition.
 */ class BooleanExpression extends t {
    get _methodName() {
        return this._expr._methodName;
    }
    /**
     * Creates an aggregation that finds the count of input documents satisfying
     * this boolean expression.
     *
     * @example
     * ```typescript
     * // Find the count of documents with a score greater than 90
     * field("score").greaterThan(90).countIf().as("highestScore");
     * ```
     *
     * @returns A new `AggregateFunction` representing the 'countIf' aggregation.
     */    countIf() {
        return k._create("count_if", [ this ], "countIf");
    }
    /**
     * Creates an expression that negates this boolean expression.
     *
     * @example
     * ```typescript
     * // Find documents where the 'tags' field does not contain 'completed'
     * field("tags").arrayContains("completed").not();
     * ```
     *
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition.
     */    not() {
        return new x("not", [ this ], "not").asBoolean();
    }
    /**
     * Creates a conditional expression that evaluates to the 'then' expression
     * if `this` expression evaluates to `true`,
     * or evaluates to the 'else' expression if `this` expressions evaluates `false`.
     *
     * @example
     * ```typescript
     * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor".
     * field("age").greaterThanOrEqual(18).conditional(constant("Adult"), constant("Minor"));
     * ```
     *
     * @param thenExpr - The expression to evaluate if the condition is true.
     * @param elseExpr - The expression to evaluate if the condition is false.
     * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression.
     */    conditional(e, t) {
        return new x("conditional", [ this, e, t ], "conditional");
    }
    ifError(e) {
        const t = __PRIVATE_valueToDefaultExpr(e), n = new x("if_error", [ this, t ], "ifError");
        return t instanceof BooleanExpression ? n.asBoolean() : n;
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        return this._expr._toProto(e);
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {
        this._expr._readUserData(e);
    }
}

class __PRIVATE_BooleanFunctionExpression extends BooleanExpression {
    constructor(e) {
        super(), this._expr = e, this.expressionType = "Function";
    }
}

class __PRIVATE_BooleanConstant extends BooleanExpression {
    constructor(e) {
        super(), this._expr = e, this.expressionType = "Constant";
    }
    _getValue() {
        return this._expr._getValue();
    }
}

class __PRIVATE_BooleanField extends BooleanExpression {
    constructor(e) {
        super(), this._expr = e, this.expressionType = "Field";
    }
}

/**
 * Creates an aggregation that counts the number of stage inputs where the provided
 * boolean expression evaluates to true.
 *
 * @example
 * ```typescript
 * // Count the number of documents where 'is_active' field equals true
 * countIf(field("is_active").equal(true)).as("numActiveDocuments");
 * ```
 *
 * @param booleanExpr - The boolean expression to evaluate on each input.
 * @returns A new `AggregateFunction` representing the 'countIf' aggregation.
 */ function countIf(e) {
    return e.countIf();
}

function arrayGet(e, t) {
    return __PRIVATE_fieldOrExpression(e).arrayGet(__PRIVATE_valueToDefaultExpr(t));
}

/**
 *
 * Creates an expression that checks if a given expression produces an error.
 *
 * @example
 * ```typescript
 * // Check if the result of a calculation is an error
 * isError(field("title").arrayContains(1));
 * ```
 *
 * @param value - The expression to check.
 * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the 'isError' check.
 */ function isError(e) {
    return e.isError().asBoolean();
}

function ifError(e, t) {
    return e instanceof BooleanExpression && t instanceof BooleanExpression ? e.ifError(t).asBoolean() : e.ifError(__PRIVATE_valueToDefaultExpr(t));
}

function isAbsent(e) {
    return __PRIVATE_fieldOrExpression(e).isAbsent();
}

function mapRemove(e, t) {
    return __PRIVATE_fieldOrExpression(e).mapRemove(__PRIVATE_valueToDefaultExpr(t));
}

function mapMerge(e, t, ...n) {
    const r = __PRIVATE_valueToDefaultExpr(t), i = n.map(__PRIVATE_valueToDefaultExpr);
    return __PRIVATE_fieldOrExpression(e).mapMerge(r, ...i);
}

function documentId(e) {
    return __PRIVATE_valueToDefaultExpr(e).documentId();
}

function parent(e) {
    return __PRIVATE_valueToDefaultExpr(e).parent();
}

function substring(e, t, n) {
    const r = __PRIVATE_fieldOrExpression(e), i = __PRIVATE_valueToDefaultExpr(t), s = void 0 === n ? void 0 : __PRIVATE_valueToDefaultExpr(n);
    return r.substring(i, s);
}

function add(e, t) {
    return __PRIVATE_fieldOrExpression(e).add(__PRIVATE_valueToDefaultExpr(t));
}

function subtract(t, n) {
    const r = "string" == typeof t ? e(t) : t, i = __PRIVATE_valueToDefaultExpr(n);
    return r.subtract(i);
}

function multiply(e, t) {
    return __PRIVATE_fieldOrExpression(e).multiply(__PRIVATE_valueToDefaultExpr(t));
}

function divide(t, n) {
    const r = "string" == typeof t ? e(t) : t, i = __PRIVATE_valueToDefaultExpr(n);
    return r.divide(i);
}

function mod(t, n) {
    const r = "string" == typeof t ? e(t) : t, i = __PRIVATE_valueToDefaultExpr(n);
    return r.mod(i);
}

/**
 *
 * Creates an expression that creates a Firestore map value from an input object.
 *
 * @example
 * ```typescript
 * // Create a map from the input object and reference the 'baz' field value from the input document.
 * map({foo: 'bar', baz: field('baz')}).as('data');
 * ```
 *
 * @param elements - The input map to evaluate in the expression.
 * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the map function.
 */ function h(e) {
    return __PRIVATE__map(e);
}

function __PRIVATE__map(e, t) {
    const n = [];
    for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) {
        const r = e[t];
        n.push(i(t)), n.push(__PRIVATE_valueToDefaultExpr(r));
    }
    return new x("map", n, "map");
}

/**
 * Internal use only
 * Converts a plainObject to a mapValue in the proto representation,
 * rather than a functionValue+map that is the result of the map(...) function.
 * This behaves different from constant(plainObject) because it
 * traverses the input object, converts values in the object to expressions,
 * and calls _readUserData on each of these expressions.
 * @private
 * @internal
 * @param plainObject
 */ function B(e) {
    const t = new Map;
    for (const n in e) if (Object.prototype.hasOwnProperty.call(e, n)) {
        const r = e[n];
        t.set(n, __PRIVATE_valueToDefaultExpr(r));
    }
    return new MapValue(t, void 0);
}

/**
 *
 * Creates an expression that creates a Firestore array value from an input array.
 *
 * @example
 * ```typescript
 * // Create an array value from the input array and reference the 'baz' field value from the input document.
 * array(['bar', field('baz')]).as('foo');
 * ```
 *
 * @param elements - The input array to evaluate in the expression.
 * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the array function.
 */ function b(e) {
    return function __PRIVATE__array(e, t) {
        return new x("array", e.map((e => __PRIVATE_valueToDefaultExpr(e))), t);
    }(e, "array");
}

function equal(n, r) {
    const i = n instanceof t ? n : e(n), s = __PRIVATE_valueToDefaultExpr(r);
    return i.equal(s);
}

function notEqual(n, r) {
    const i = n instanceof t ? n : e(n), s = __PRIVATE_valueToDefaultExpr(r);
    return i.notEqual(s);
}

function lessThan(n, r) {
    const i = n instanceof t ? n : e(n), s = __PRIVATE_valueToDefaultExpr(r);
    return i.lessThan(s);
}

function lessThanOrEqual(n, r) {
    const i = n instanceof t ? n : e(n), s = __PRIVATE_valueToDefaultExpr(r);
    return i.lessThanOrEqual(s);
}

function greaterThan(n, r) {
    const i = n instanceof t ? n : e(n), s = __PRIVATE_valueToDefaultExpr(r);
    return i.greaterThan(s);
}

function greaterThanOrEqual(n, r) {
    const i = n instanceof t ? n : e(n), s = __PRIVATE_valueToDefaultExpr(r);
    return i.greaterThanOrEqual(s);
}

function arrayConcat(e, t, ...n) {
    const r = n.map((e => __PRIVATE_valueToDefaultExpr(e)));
    return __PRIVATE_fieldOrExpression(e).arrayConcat(__PRIVATE_fieldOrExpression(t), ...r);
}

function arrayContains(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_valueToDefaultExpr(t);
    return n.arrayContains(r);
}

function arrayContainsAny(e, t) {
    // @ts-ignore implementation accepts both types
    return __PRIVATE_fieldOrExpression(e).arrayContainsAny(t);
}

function arrayContainsAll(e, t) {
    // @ts-ignore implementation accepts both types
    return __PRIVATE_fieldOrExpression(e).arrayContainsAll(t);
}

function arrayLength(e) {
    return __PRIVATE_fieldOrExpression(e).arrayLength();
}

function equalAny(e, t) {
    // @ts-ignore implementation accepts both types
    return __PRIVATE_fieldOrExpression(e).equalAny(t);
}

function notEqualAny(e, t) {
    // @ts-ignore implementation accepts both types
    return __PRIVATE_fieldOrExpression(e).notEqualAny(t);
}

/**
 *
 * Creates an expression that performs a logical 'XOR' (exclusive OR) operation on multiple BooleanExpressions.
 *
 * @example
 * ```typescript
 * // Check if only one of the conditions is true: 'age' greater than 18, 'city' is "London",
 * // or 'status' is "active".
 * const condition = xor(
 *     greaterThan("age", 18),
 *     equal("city", "London"),
 *     equal("status", "active"));
 * ```
 *
 * @param first - The first condition.
 * @param second - The second condition.
 * @param additionalConditions - Additional conditions to 'XOR' together.
 * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'XOR' operation.
 */ function xor(e, t, ...n) {
    return new x("xor", [ e, t, ...n ], "xor").asBoolean();
}

/**
 *
 * Creates a conditional expression that evaluates to a 'then' expression if a condition is true
 * and an 'else' expression if the condition is false.
 *
 * @example
 * ```typescript
 * // If 'age' is greater than 18, return "Adult"; otherwise, return "Minor".
 * conditional(
 *     greaterThan("age", 18), constant("Adult"), constant("Minor"));
 * ```
 *
 * @param condition - The condition to evaluate.
 * @param thenExpr - The expression to evaluate if the condition is true.
 * @param elseExpr - The expression to evaluate if the condition is false.
 * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the conditional expression.
 */ function conditional(e, t, n) {
    return new x("conditional", [ e, t, n ], "conditional");
}

/**
 *
 * Creates an expression that negates a filter condition.
 *
 * @example
 * ```typescript
 * // Find documents where the 'completed' field is NOT true
 * not(equal("completed", true));
 * ```
 *
 * @param booleanExpr - The filter condition to negate.
 * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the negated filter condition.
 */ function not(e) {
    return e.not();
}

function logicalMaximum(e, t, ...n) {
    return __PRIVATE_fieldOrExpression(e).logicalMaximum(__PRIVATE_valueToDefaultExpr(t), ...n.map((e => __PRIVATE_valueToDefaultExpr(e))));
}

function logicalMinimum(e, t, ...n) {
    return __PRIVATE_fieldOrExpression(e).logicalMinimum(__PRIVATE_valueToDefaultExpr(t), ...n.map((e => __PRIVATE_valueToDefaultExpr(e))));
}

function exists(e) {
    return __PRIVATE_fieldOrExpression(e).exists();
}

function reverse(e) {
    return __PRIVATE_fieldOrExpression(e).reverse();
}

function byteLength(e) {
    return __PRIVATE_fieldOrExpression(e).byteLength();
}

function exp(e) {
    return __PRIVATE_fieldOrExpression(e).exp();
}

function ceil(e) {
    return __PRIVATE_fieldOrExpression(e).ceil();
}

function floor(e) {
    return __PRIVATE_fieldOrExpression(e).floor();
}

/**
 * Creates an aggregation that counts the number of distinct values of a field.
 *
 * @param expr - The expression or field to count distinct values of.
 * @returns A new `AggregateFunction` representing the 'count_distinct' aggregation.
 */ function countDistinct(e) {
    return __PRIVATE_fieldOrExpression(e).countDistinct();
}

function charLength(e) {
    return __PRIVATE_fieldOrExpression(e).charLength();
}

function like(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_valueToDefaultExpr(t);
    return n.like(r);
}

function regexContains(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_valueToDefaultExpr(t);
    return n.regexContains(r);
}

function arrayFilter(e, t, n) {
    return __PRIVATE_fieldOrExpression(e).arrayFilter(t, n);
}

function arrayTransform(e, t, n) {
    return __PRIVATE_fieldOrExpression(e).arrayTransform(t, n);
}

function arrayTransformWithIndex(e, t, n, r) {
    return __PRIVATE_fieldOrExpression(e).arrayTransformWithIndex(t, n, r);
}

function arraySlice(e, t, n) {
    return __PRIVATE_fieldOrExpression(e).arraySlice(t, n);
}

function arrayFirst(e) {
    return __PRIVATE_fieldOrExpression(e).arrayFirst();
}

function arrayFirstN(e, t) {
    return __PRIVATE_fieldOrExpression(e).arrayFirstN(__PRIVATE_valueToDefaultExpr(t));
}

function arrayLast(e) {
    return __PRIVATE_fieldOrExpression(e).arrayLast();
}

function arrayLastN(e, t) {
    return __PRIVATE_fieldOrExpression(e).arrayLastN(__PRIVATE_valueToDefaultExpr(t));
}

function arrayMaximum(e) {
    return __PRIVATE_fieldOrExpression(e).arrayMaximum();
}

function arrayMaximumN(e, t) {
    return __PRIVATE_fieldOrExpression(e).arrayMaximumN(__PRIVATE_valueToDefaultExpr(t));
}

function arrayMinimum(e) {
    return __PRIVATE_fieldOrExpression(e).arrayMinimum();
}

function arrayMinimumN(e, t) {
    return __PRIVATE_fieldOrExpression(e).arrayMinimumN(__PRIVATE_valueToDefaultExpr(t));
}

function arrayIndexOf(e, t) {
    return __PRIVATE_fieldOrExpression(e).arrayIndexOf(__PRIVATE_valueToDefaultExpr(t));
}

function arrayLastIndexOf(e, t) {
    return __PRIVATE_fieldOrExpression(e).arrayLastIndexOf(__PRIVATE_valueToDefaultExpr(t));
}

function arrayIndexOfAll(e, t) {
    return __PRIVATE_fieldOrExpression(e).arrayIndexOfAll(__PRIVATE_valueToDefaultExpr(t));
}

function regexFind(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_valueToDefaultExpr(t);
    return n.regexFind(r);
}

function regexFindAll(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_valueToDefaultExpr(t);
    return n.regexFindAll(r);
}

function regexMatch(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_valueToDefaultExpr(t);
    return n.regexMatch(r);
}

function stringContains(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_valueToDefaultExpr(t);
    return n.stringContains(r);
}

function startsWith(e, t) {
    return __PRIVATE_fieldOrExpression(e).startsWith(__PRIVATE_valueToDefaultExpr(t));
}

function endsWith(e, t) {
    return __PRIVATE_fieldOrExpression(e).endsWith(__PRIVATE_valueToDefaultExpr(t));
}

function toLower(e) {
    return __PRIVATE_fieldOrExpression(e).toLower();
}

function toUpper(e) {
    return __PRIVATE_fieldOrExpression(e).toUpper();
}

function trim(e, t) {
    return __PRIVATE_fieldOrExpression(e).trim(t);
}

function ltrim(e, t) {
    return __PRIVATE_fieldOrExpression(e).ltrim(t);
}

function rtrim(e, t) {
    return __PRIVATE_fieldOrExpression(e).rtrim(t);
}

function type(e) {
    return __PRIVATE_fieldOrExpression(e).type();
}

function isType(e, t) {
    return __PRIVATE_fieldOrExpression(e).isType(t);
}

function stringConcat(e, t, ...n) {
    return __PRIVATE_fieldOrExpression(e).stringConcat(__PRIVATE_valueToDefaultExpr(t), ...n.map(__PRIVATE_valueToDefaultExpr));
}

function stringIndexOf(e, t) {
    return __PRIVATE_fieldOrExpression(e).stringIndexOf(t);
}

function stringRepeat(e, t) {
    return __PRIVATE_fieldOrExpression(e).stringRepeat(t);
}

function stringReplaceAll(e, t, n) {
    return __PRIVATE_fieldOrExpression(e).stringReplaceAll(t, n);
}

function stringReplaceOne(e, t, n) {
    return __PRIVATE_fieldOrExpression(e).stringReplaceOne(t, n);
}

function mapGet(e, t) {
    return __PRIVATE_fieldOrExpression(e).mapGet(t);
}

function mapSet(e, t, n, ...r) {
    return __PRIVATE_fieldOrExpression(e).mapSet(t, n, ...r);
}

function mapKeys(e) {
    return __PRIVATE_fieldOrExpression(e).mapKeys();
}

function mapValues(e) {
    return __PRIVATE_fieldOrExpression(e).mapValues();
}

function mapEntries(e) {
    return __PRIVATE_fieldOrExpression(e).mapEntries();
}

/**
 * Creates an aggregation that counts the total number of stage inputs.
 *
 * @example
 * ```typescript
 * // Count the total number of input documents
 * countAll().as("totalDocument");
 * ```
 *
 * @returns A new {@link @firebase/firestore/pipelines#AggregateFunction} representing the 'countAll' aggregation.
 */ function countAll() {
    return k._create("count", [], "count");
}

function count(e) {
    return __PRIVATE_fieldOrExpression(e).count();
}

function sum(e) {
    return __PRIVATE_fieldOrExpression(e).sum();
}

function average(e) {
    return __PRIVATE_fieldOrExpression(e).average();
}

function minimum(e) {
    return __PRIVATE_fieldOrExpression(e).minimum();
}

function maximum(e) {
    return __PRIVATE_fieldOrExpression(e).maximum();
}

function first(e) {
    return __PRIVATE_fieldOrExpression(e).first();
}

function last(e) {
    return __PRIVATE_fieldOrExpression(e).last();
}

function arrayAgg(e) {
    return __PRIVATE_fieldOrExpression(e).arrayAgg();
}

function arrayAggDistinct(e) {
    return __PRIVATE_fieldOrExpression(e).arrayAggDistinct();
}

function cosineDistance(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_vectorToExpr(t);
    return n.cosineDistance(r);
}

function dotProduct(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_vectorToExpr(t);
    return n.dotProduct(r);
}

function euclideanDistance(e, t) {
    const n = __PRIVATE_fieldOrExpression(e), r = __PRIVATE_vectorToExpr(t);
    return n.euclideanDistance(r);
}

function vectorLength(e) {
    return __PRIVATE_fieldOrExpression(e).vectorLength();
}

function unixMicrosToTimestamp(e) {
    return __PRIVATE_fieldOrExpression(e).unixMicrosToTimestamp();
}

function timestampToUnixMicros(e) {
    return __PRIVATE_fieldOrExpression(e).timestampToUnixMicros();
}

function unixMillisToTimestamp(e) {
    return __PRIVATE_fieldOrExpression(e).unixMillisToTimestamp();
}

function timestampToUnixMillis(e) {
    return __PRIVATE_fieldOrExpression(e).timestampToUnixMillis();
}

function unixSecondsToTimestamp(e) {
    return __PRIVATE_fieldOrExpression(e).unixSecondsToTimestamp();
}

function timestampToUnixSeconds(e) {
    return __PRIVATE_fieldOrExpression(e).timestampToUnixSeconds();
}

function timestampAdd(e, t, n) {
    const r = __PRIVATE_fieldOrExpression(e), i = __PRIVATE_valueToDefaultExpr(t), s = __PRIVATE_valueToDefaultExpr(n);
    return r.timestampAdd(i, s);
}

function timestampSubtract(e, t, n) {
    const r = __PRIVATE_fieldOrExpression(e), i = __PRIVATE_valueToDefaultExpr(t), s = __PRIVATE_valueToDefaultExpr(n);
    return r.timestampSubtract(i, s);
}

/**
 *
 * Creates an expression that evaluates to the current server timestamp.
 *
 * @example
 * ```typescript
 * // Get the current server timestamp
 * currentTimestamp()
 * ```
 *
 * @returns A new Expression representing the current server timestamp.
 */ function currentTimestamp() {
    return new x("current_timestamp", [], "currentTimestamp");
}

/**
 *
 * Creates an expression that performs a logical 'AND' operation on multiple filter conditions.
 *
 * @example
 * ```typescript
 * // Check if the 'age' field is greater than 18 AND the 'city' field is "London" AND
 * // the 'status' field is "active"
 * const condition = and(greaterThan("age", 18), equal("city", "London"), equal("status", "active"));
 * ```
 *
 * @param first - The first filter condition.
 * @param second - The second filter condition.
 * @param more - Additional filter conditions to 'AND' together.
 * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'AND' operation.
 */ function and(e, t, ...n) {
    return new x("and", [ e, t, ...n ], "and").asBoolean();
}

/**
 *
 * Creates an expression that performs a logical 'OR' operation on multiple filter conditions.
 *
 * @example
 * ```typescript
 * // Check if the 'age' field is greater than 18 OR the 'city' field is "London" OR
 * // the 'status' field is "active"
 * const condition = or(greaterThan("age", 18), equal("city", "London"), equal("status", "active"));
 * ```
 *
 * @param first - The first filter condition.
 * @param second - The second filter condition.
 * @param more - Additional filter conditions to 'OR' together.
 * @returns A new {@link @firebase/firestore/pipelines#Expression} representing the logical 'OR' operation.
 */ function or(e, t, ...n) {
    return new x("or", [ e, t, ...n ], "xor").asBoolean();
}

/**
 *
 * Creates an expression that performs a logical 'NOR' operation on multiple filter conditions.
 *
 * @example
 * ```typescript
 * // Check if neither the 'age' field is greater than 18 nor the 'city' field is "London"
 * const condition = nor(
 *   greaterThan("age", 18),
 *   equal("city", "London")
 * );
 * ```
 *
 * @param first - The first filter condition.
 * @param second - The second filter condition.
 * @param more - Additional filter conditions to 'NOR' together.
 * @returns A new {@link @firebase/firestore/pipelines#BooleanExpression} representing the logical 'NOR' operation.
 */ function nor(e, t, ...n) {
    return new x("nor", [ e, t, ...n ], "nor").asBoolean();
}

function pow(e, t) {
    return __PRIVATE_fieldOrExpression(e).pow(t);
}

/**
 *
 * Creates an expression that generates a random number between 0.0 and 1.0 but not including 1.0.
 *
 * @example
 * ```typescript
 * // Generate a random number between 0.0 and 1.0.
 * rand();
 * ```
 *
 * @returns A new `Expression` representing the rand operation.
 */ function rand() {
    return new x("rand", [], "rand");
}

function round(e, t) {
    return void 0 === t ? __PRIVATE_fieldOrExpression(e).round() : __PRIVATE_fieldOrExpression(e).round(__PRIVATE_valueToDefaultExpr(t));
}

function trunc(e, t) {
    return void 0 === t ? __PRIVATE_fieldOrExpression(e).trunc() : __PRIVATE_fieldOrExpression(e).trunc(__PRIVATE_valueToDefaultExpr(t));
}

function collectionId(e) {
    return __PRIVATE_fieldOrExpression(e).collectionId();
}

function length(e) {
    return __PRIVATE_fieldOrExpression(e).length();
}

function ln(e) {
    return __PRIVATE_fieldOrExpression(e).ln();
}

function log(e, t) {
    return new x("log", [ __PRIVATE_fieldOrExpression(e), __PRIVATE_valueToDefaultExpr(t) ]);
}

function sqrt(e) {
    return __PRIVATE_fieldOrExpression(e).sqrt();
}

function stringReverse(e) {
    return __PRIVATE_fieldOrExpression(e).stringReverse();
}

function concat(e, t, ...n) {
    return new x("concat", [ __PRIVATE_fieldOrExpression(e), __PRIVATE_valueToDefaultExpr(t), ...n.map(__PRIVATE_valueToDefaultExpr) ]);
}

function abs(e) {
    return __PRIVATE_fieldOrExpression(e).abs();
}

function ifAbsent(e, t) {
    return __PRIVATE_fieldOrExpression(e).ifAbsent(__PRIVATE_valueToDefaultExpr(t));
}

function ifNull(e, t) {
    return __PRIVATE_fieldOrExpression(e).ifNull(t);
}

function coalesce(e, t, ...n) {
    return __PRIVATE_fieldOrExpression(e).coalesce(t, ...n);
}

/**
 * Creates an expression that evaluates to the result corresponding to the first true condition.
 *
 * @remarks
 * This function behaves like a `switch` statement. It accepts an alternating sequence of conditions
 * and their corresponding results.
 * If an odd number of arguments is provided, the final argument serves as a default fallback result.
 * If no default is provided and no condition evaluates to true, it throws an error.
 *
 * @example
 * ```typescript
 * // Return "Active" if field "status" is 1, "Pending" if field "status" is 2,
 * // and default to "Unknown" if none of the conditions are true.
 * switchOn(
 *   equal(field("status"), 1), constant("Active"),
 *   equal(field("status"), 2), constant("Pending"),
 *   constant("Unknown")
 * )
 * ```
 *
 * @param condition - The first condition to check.
 * @param result - The result if the first condition is true.
 * @param others - Additional conditions and results, and optionally a default value.
 * @returns A new Expression representing the switch operation.
 */ function switchOn(e, t, ...n) {
    return new x("switch_on", [ __PRIVATE_valueToDefaultExpr(e), __PRIVATE_valueToDefaultExpr(t), ...n.map(__PRIVATE_valueToDefaultExpr) ], "switchOn");
}

function join(e, t) {
    return __PRIVATE_fieldOrExpression(e).join(__PRIVATE_valueToDefaultExpr(t));
}

function log10(e) {
    return __PRIVATE_fieldOrExpression(e).log10();
}

function arraySum(e) {
    return __PRIVATE_fieldOrExpression(e).arraySum();
}

function split(e, t) {
    return __PRIVATE_fieldOrExpression(e).split(__PRIVATE_valueToDefaultExpr(t));
}

function timestampTruncate(e, t, n) {
    const r = __PRIVATE_isString$1(t) ? __PRIVATE_valueToDefaultExpr(t) : t;
    return __PRIVATE_fieldOrExpression(e).timestampTruncate(r, n);
}

/**
 * @public
 * Creates an expression that retrieves the value of a variable bound via `define()`.
 *
 * @example
 * ```typescript
 * db.pipeline().collection("products")
 *   .define(
 *     field("price").multiply(0.9).as("discountedPrice"),
 *     field("stock").add(10).as("newStock")
 *   )
 *   .where(variable("discountedPrice").lessThan(100))
 *   .select(field("name"), variable("newStock"));
 * ```
 *
 * @param name - The name of the variable to retrieve.
 * @returns An {@link @firebase/firestore/pipelines#Expression} representing the variable's value.
 */ function variable(e) {
    return new __PRIVATE_VariableExpression(e);
}

/**
 * @internal
 *
 * Expression representing a variable reference. This evaluates to the value of a variable
 * defined in a pipeline.
 */ class __PRIVATE_VariableExpression extends t {
    /**
     * @hideconstructor
     */
    constructor(e) {
        super(), this.name = e, this.expressionType = "Variable";
    }
    /**
     * @internal
     */    _toProto(e) {
        return {
            variableReferenceValue: this.name
        };
    }
    /**
     * @internal
     */    _readUserData(e) {}
}

/**
 * @public
 * Creates an expression that represents the current document being processed.
 *
 * @example
 * ```typescript
 * // Define the current document as a variable "doc"
 * firestore.pipeline().collection("books")
 *     .define(currentDocument().as("doc"))
 *     // Access a field from the defined document variable
 *     .select(variable("doc").mapGet("title"));
 * ```
 *
 * @returns An {@link @firebase/firestore/pipelines#Expression} representing the current document.
 */ function currentDocument() {
    return new x("current_document", []);
}

/**
 * @internal
 */ function d(e) {
    return new __PRIVATE_PipelineValueExpression(e);
}

/**
 * @internal
 */ class __PRIVATE_PipelineValueExpression extends t {
    /**
     * @hideconstructor
     */
    constructor(e) {
        super(), this.pipeline = e, this.expressionType = "PipelineValue";
    }
    /**
     * @internal
     */    _toProto(e) {
        return __PRIVATE_toPipelineValue(this.pipeline._toProto(e));
    }
    /**
     * @internal
     */    _readUserData(e) {
        this.pipeline._readUserData(e);
    }
}

function timestampDiff(e, t, n) {
    const r = __PRIVATE_fieldOrExpression(e), i = __PRIVATE_fieldOrExpression(t), s = __PRIVATE_valueToDefaultExpr(n);
    return r.timestampDiff(i, s);
}

function timestampExtract(e, t, n) {
    return __PRIVATE_fieldOrExpression(e).timestampExtract(__PRIVATE_valueToDefaultExpr(t), n);
}

// TODO(search) enable with backend support
// /**
//  * Perform a full-text search on the specified field.
//  *
//  * @remarks This Expression can only be used within a `search` stage.
//  *
//  * @example
//  * ```typescript
//  * db.pipeline().collection('restaurants').search({
//  *   query: matches('menu', 'waffles')
//  * })
//  * ```
//  *
//  * @param searchField Search the specified field.
//  * @param rquery Define the search query using the search domain-specific language (DSL).
//  */
// export function matches(
//   searchField: string | Field,
//   rquery: string | Expression
// ): BooleanExpression {
//   return toField(searchField).matches(rquery);
// }
/**
 * @beta
 * Perform a full-text search on all indexed search fields in the document.
 *
 * @remarks This Expression can only be used within a `search` stage.
 *
 * @example
 * ```typescript
 * db.pipeline().collection('restaurants').search({
 *   query: documentMatches('waffles OR pancakes')
 * })
 * ```
 *
 * @param rquery Define the search query using the search domain-specific language (DSL).
 */ function q(e) {
    return new x("document_matches", [ __PRIVATE_valueToDefaultExpr(e) ], "documentMatches").asBoolean();
}

/**
 * @beta
 *
 * Evaluates to the search score that reflects the topicality of the document
 * to all of the text predicates (for example: `documentMatches`)
 * in the search query. If `SearchOptions.query` is not set or does not contain
 * any text predicates, then this topicality score will always be `0`.
 *
 * @example
 * ```typescript
 * db.pipeline().collection('restaurants').search({
 *   query: 'waffles',
 *   sort: score().descending()
 * })
 * ```
 *
 * @remarks This Expression can only be used within a `search` stage.
 */ function score() {
    return new x("score", [], "score");
}

// TODO(search) enable with backend support
// /**
//  * Options defining how a snippet expression is evaluated.
//  */
// export interface SnippetOptions {
//   /**
//    * Define the search query using the search domain-specific language (DSL).
//    */
//   rquery: string;

//   /**
//    * The maximum width of the string estimated for a variable width font. The
//    * unit is tenths of ems. The default is `160`.
//    */
//   maxSnippetWidth?: number;

//   /**
//    * The maximum number of non-contiguous pieces of text in the returned snippet.
//    * The default is `1`.
//    */
//   maxSnippets?: number;

//   /**
//    * The string to join the pieces. The default value is '\n'
//    */
//   separator?: string;
// }

// /**
//  * Evaluates to an HTML-formatted text snippet that highlights terms matching
//  * the search query in `<b>bold</b>`.
//  *
//  * @remarks This Expression can only be used within a `search` stage.
//  *
//  * @example
//  * ```typescript
//  * db.pipeline().collection('restaurants').search({
//  *   query: 'waffles',
//  *   addFields: { snippet: snippet('menu', 'waffles') }
//  * })
//  * ```
//  *
//  * @param searchField Search the specified field for matching terms.
//  * @param rquery Define the search query using the search domain-specific language (DSL).
//  */
// export function snippet(
//   searchField: string | Field,
//   rquery: string
// ): Expression;

// /**
//  * Evaluates to an HTML-formatted text snippet that highlights terms matching
//  * the search query in `<b>bold</b>`.
//  *
//  * @remarks This Expression can only be used within a `search` stage.
//  *
//  * @param searchField Search the specified field for matching terms.
//  * @param options Define the search query using the search domain-specific language (DSL).
//  */
// export function snippet(
//   searchField: string | Field,
//   options: SnippetOptions
// ): Expression;
// export function snippet(
//   field: string | Field,
//   queryOrOptions: string | SnippetOptions
// ): Expression {
//   return toField(field).snippet(
//     isString(queryOrOptions) ? { rquery: queryOrOptions } : queryOrOptions
//   );
// }
/**
 * @beta
 * Evaluates to the distance in meters between the location in the specified
 * field and the query location.
 *
 * @remarks This Expression can only be used within a `search` stage.
 *
 * @example
 * ```typescript
 * db.pipeline().collection('restaurants').search({
 *   query: 'waffles',
 *   sort: geoDistance('location', new GeoPoint(37.0, -122.0)).ascending()
 * })
 * ```
 *
 * @param fieldName - Specifies the field in the document which contains
 * the first GeoPoint for distance computation.
 * @param location - Compute distance to this GeoPoint.
 */ function geoDistance(e, t) {
    return S(e).geoDistance(t);
}

function ascending(e) {
    return new Ordering(__PRIVATE_fieldOrExpression(e), "ascending", "ascending");
}

function descending(e) {
    return new Ordering(__PRIVATE_fieldOrExpression(e), "descending", "descending");
}

/**
 *
 * Represents an ordering criterion for sorting documents in a Firestore pipeline.
 *
 * You create `Ordering` instances using the `ascending` and `descending` helper functions.
 */ class Ordering {
    constructor(e, t, n) {
        this.expr = e, this.direction = t, this._methodName = n, this._protoValueType = "ProtoValue";
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        return {
            mapValue: {
                fields: {
                    direction: __PRIVATE_toStringValue(this.direction),
                    expression: this.expr._toProto(e)
                }
            }
        };
    }
    /**
     * @private
     * @internal
     */    _readUserData(e) {
        this.expr._readUserData(e);
    }
}

function f(e) {
    const t = e;
    return t.selectable && __PRIVATE_isString$1(t.alias) && j(t.expr);
}

function F(e) {
    const t = e;
    return null != t && j(t.expr) && ("ascending" === t.direction || "descending" === t.direction);
}

function O(e) {
    const t = e;
    return __PRIVATE_isString$1(t.alias) && t.aggregate instanceof k;
}

function j(e) {
    return e instanceof t;
}

function E(e) {
    return e instanceof BooleanExpression;
}

function T(e) {
    return e instanceof c;
}

function g(e) {
    return e instanceof o;
}

function S(t) {
    if (__PRIVATE_isString$1(t)) {
        return e(t);
    }
    return t;
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class Stage {
    constructor(e) {
        /**
         * Store _optionsProto parsed by _readUserData.
         * @private
         * @internal
         * @protected
         */
        this.optionsProto = void 0, ({rawOptions: this.rawOptions, ...this.knownOptions} = e);
    }
    _readUserData(e) {
        this.optionsProto = this._optionsUtil.getOptionsProto(e, this.knownOptions, this.rawOptions);
    }
    _toProto(e) {
        return {
            name: this._name,
            options: this.optionsProto
        };
    }
}

class w extends Stage {
    get _name() {
        return "add_fields";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.fields = e;
    }
    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ toMapValue(e, this.fields) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.fields, e);
    }
}

class _ extends Stage {
    get _name() {
        return "remove_fields";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.fields = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: this.fields.map((t => t._toProto(e)))
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.fields, e);
    }
}

/**
 * @public
 */ class P extends Stage {
    get _name() {
        return "let";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.lr = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ toMapValue(e, this.lr) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.lr, e);
    }
}

class V extends Stage {
    get _name() {
        return "aggregate";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t, n) {
        super(n), this.groups = e, this.accumulators = t;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ toMapValue(e, this.accumulators), toMapValue(e, this.groups) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.groups, e), __PRIVATE_readUserDataHelper(this.accumulators, e);
    }
}

class M extends Stage {
    get _name() {
        return "distinct";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.groups = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ toMapValue(e, this.groups) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.groups, e);
    }
}

class H extends Stage {
    get _name() {
        return "collection";
    }
    get _optionsUtil() {
        return new OptionsUtil({
            forceIndex: {
                serverName: "force_index"
            }
        });
    }
    constructor(e, t) {
        super(t), 
        // prepend slash to collection string
        this.Er = e.startsWith("/") ? e : "/" + e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ {
                referenceValue: this.Er
            } ]
        };
    }
    _readUserData(e) {
        super._readUserData(e);
    }
}

class J extends Stage {
    get _name() {
        return "collection_group";
    }
    get _optionsUtil() {
        return new OptionsUtil({
            forceIndex: {
                serverName: "force_index"
            }
        });
    }
    constructor(e, t) {
        super(t), this.collectionId = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ {
                referenceValue: ""
            }, {
                stringValue: this.collectionId
            } ]
        };
    }
    _readUserData(e) {
        super._readUserData(e);
    }
}

class sa extends Stage {
    get _name() {
        return "subcollection";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.path = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ {
                stringValue: this.path
            } ]
        };
    }
    _readUserData(e) {
        super._readUserData(e);
    }
}

class Q extends Stage {
    get _name() {
        return "database";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e)
        };
    }
    _readUserData(e) {
        super._readUserData(e);
    }
}

class Y extends Stage {
    get _name() {
        return "documents";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        if (super(t), !e || 0 === e.length) throw new s(aa.INVALID_ARGUMENT, "Empty document paths are not allowed in DocumentsSource");
        const n = e.map((e => e.startsWith("/") ? e : "/" + e)), r = new Set(n);
        if (r.size !== n.length) throw new s(aa.INVALID_ARGUMENT, "Duplicate document paths are not allowed in DocumentsSource");
        this.hr = n, this.Tr = r;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: this.hr.map((e => ({
                referenceValue: e
            })))
        };
    }
    _readUserData(e) {
        super._readUserData(e);
    }
}

class A extends Stage {
    get _name() {
        return "where";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.condition = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ this.condition._toProto(e) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.condition, e);
    }
}

class D extends Stage {
    get _name() {
        return "find_nearest";
    }
    get _optionsUtil() {
        return new OptionsUtil({
            limit: {
                serverName: "limit"
            },
            distanceField: {
                serverName: "distance_field"
            }
        });
    }
    constructor(e, t, n, r) {
        super(r), this.vectorValue = e, this.field = t, this.distanceMeasure = n;
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ this.field._toProto(e), this.vectorValue._toProto(e), __PRIVATE_toStringValue(this.distanceMeasure) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.vectorValue, e), __PRIVATE_readUserDataHelper(this.field, e);
    }
}

class v extends Stage {
    get _name() {
        return "limit";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        __PRIVATE_hardAssert(!isNaN(e) && e !== 1 / 0 && e !== -1 / 0, 34860), super(t), 
        this.limit = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ toNumber(e, this.limit) ]
        };
    }
}

class I extends Stage {
    get _name() {
        return "offset";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.offset = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ toNumber(e, this.offset) ]
        };
    }
}

class y extends Stage {
    get _name() {
        return "select";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.selections = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ toMapValue(e, this.selections) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.selections, e);
    }
}

class L extends Stage {
    get _name() {
        return "sort";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.orderings = e;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: this.orderings.map((t => t._toProto(e)))
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.orderings, e);
    }
}

class N extends Stage {
    get _name() {
        return "sample";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t, n) {
        super(n), this.rate = e, this.mode = t;
    }
    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ toNumber(e, this.rate), __PRIVATE_toStringValue(this.mode) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e);
    }
}

class U extends Stage {
    get _name() {
        return "union";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.other = e;
    }
    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ __PRIVATE_toPipelineValue(this.other._toProto(e)) ]
        };
    }
    _readUserData(e) {
        this.other._readUserData(e), super._readUserData(e);
    }
}

class W extends Stage {
    get _name() {
        return "unnest";
    }
    get _optionsUtil() {
        return new OptionsUtil({
            indexField: {
                serverName: "index_field"
            }
        });
    }
    constructor(e, t, n) {
        super(n), this.alias = e, this.expr = t;
    }
    _toProto(t) {
        return {
            ...super._toProto(t),
            args: [ this.expr._toProto(t), e(this.alias)._toProto(t) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.expr, e);
    }
}

class $ extends Stage {
    get _name() {
        return "replace_with";
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
    constructor(e, t) {
        super(t), this.map = e;
    }
    _toProto(e) {
        return {
            ...super._toProto(e),
            args: [ this.map._toProto(e), __PRIVATE_toStringValue($.Pr) ]
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.map, e);
    }
}

$.Pr = "full_replace";

/**
 * @beta
 */
class C extends Stage {
    constructor(e) {
        super(e), this.Rr = e;
    }
    get _name() {
        return "search";
    }
    get _optionsUtil() {
        return new OptionsUtil({
            query: {
                serverName: "query"
            },
            limit: {
                serverName: "limit"
            },
            retrievalDepth: {
                serverName: "retrieval_depth"
            },
            sort: {
                serverName: "sort"
            },
            addFields: {
                serverName: "add_fields"
            },
            select: {
                serverName: "select"
            },
            offset: {
                serverName: "offset"
            },
            Ir: {
                serverName: "query_enhancement"
            },
            languageCode: {
                serverName: "language_code"
            }
        });
    }
    /**
     * @private
     * @internal
     */    _toProto(e) {
        return {
            ...super._toProto(e),
            args: []
        };
    }
    _readUserData(e) {
        __PRIVATE_readUserDataHelper(this.Rr.query, e), this.Rr.addFields && __PRIVATE_readUserDataHelper(this.Rr.addFields, e), 
        this.Rr.select && __PRIVATE_readUserDataHelper(this.Rr.select, e), this.Rr.sort && __PRIVATE_readUserDataHelper(this.Rr.sort, e), 
        super._readUserData(e);
    }
}

/**
 * @beta
 */ class K extends Stage {
    /**
     * @private
     * @internal
     */
    constructor(e, t, n) {
        super({
            rawOptions: n
        }), this.name = e, this.params = t;
    }
    /**
     * @internal
     * @private
     */    _toProto(e) {
        return {
            name: this.name,
            args: this.params.map((t => t._toProto(e))),
            options: this.optionsProto
        };
    }
    _readUserData(e) {
        super._readUserData(e), __PRIVATE_readUserDataHelper(this.params, e);
    }
    get _name() {
        return this.name;
    }
    get _optionsUtil() {
        return new OptionsUtil({});
    }
}

/**
 * Helper to read user data across a number of different formats.
 * @param name - Name of the calling function. Used for error messages when invalid user data is encountered.
 * @param expressionMap
 * @returns the expressionMap argument.
 * @private
 */ function __PRIVATE_readUserDataHelper(e, t) {
    return __PRIVATE_isUserData(e) ? e._readUserData(t) : Array.isArray(e) ? e.forEach((e => e._readUserData(t))) : e instanceof Map ? e.forEach((e => e._readUserData(t))) : Object.values(e).forEach((e => e._readUserData(t))), 
    e;
}

/**
 * @license
 * Copyright 2026 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @beta
 * @internal
 *
 * The RealtimePipeline class provides a flexible and expressive framework for building complex data
 * transformation and query pipelines that can be used with Firestore's real-time and offline capabilities.
 *
 * A RealtimePipeline takes data sources, such as Firestore collections or collection groups, and applies
 * a series of stages that are chained together. Each stage takes the output from the previous stage
 * (or the data source) and produces an output for the next stage (or as the final output of the
 * pipeline).
 *
 * Expressions can be used within each stage to filter and transform data through the stage.
 *
 * NOTE: Both the initial and subsequent snapshots for RealtimePipeline take the consideration of the SDK's cache.
 * They might include results that have not been synchronized with the server yet, and wait for subsequent snapshots
 * to reflect the latest server state, this is the same as classic Firestore {@link Query}.
 * This behavior is different from the {@link Pipeline} class, which does not take the consideration of the SDK's cache.
 *
 * Usage Examples:
 *
 * ```typescript
 * const db: Firestore; // Assumes a valid firestore instance.
 *
 * // Example 1: Listen to books published after 1980
 * const unsubscribe = onRealtimePipelineSnapshot(db.realtimePipeline()
 *     .collection("books")
 *     .where(field("published").gt(1980)),
 *     (snapshot) => {
 *       // Handle the snapshot
 *     }
 * );
 * ```
 */
// TODO(pipeline): Add more examples to showcase functions
class __PRIVATE_RealtimePipeline {
    /**
     * @internal
     * @private
     * @param _db
     * @param userDataReader
     * @param _userDataWriter
     * @param _documentReferenceFactory
     * @param stages
     */
    constructor(
    /**
     * @internal
     * @private
     */
    e, 
    /**
     * @internal
     * @private
     */
    t, 
    /**
     * @internal
     * @private
     */
    n, r) {
        this._db = e, this.userDataReader = t, this._userDataWriter = n, this.stages = r;
    }
    /**
     * Reads user data for each expression in the expressionMap.
     * @param name Name of the calling function. Used for error messages when invalid user data is encountered.
     * @param expressionMap
     * @return the expressionMap argument.
     * @private
     * @internal
     */    Ar(e, t) {
        const n = this.userDataReader.createContext(3 /* UserDataSource.Argument */ , e);
        return __PRIVATE_isUserData(t) ? t._readUserData(n) : Array.isArray(t) ? t.forEach((e => e._readUserData(n))) : t.forEach((e => e._readUserData(n))), 
        t;
    }
    where(e) {
        const t = this.stages.map((e => e));
        return this.Ar("where", e), t.push(new A(e, {})), new __PRIVATE_RealtimePipeline(this._db, this.userDataReader, this._userDataWriter, t);
    }
    limit(e) {
        const t = this.stages.map((e => e));
        return t.push(new v(e, {})), new __PRIVATE_RealtimePipeline(this._db, this.userDataReader, this._userDataWriter, t);
    }
    sort(e, ...t) {
        const n = this.stages.map((e => e));
        // Option object
                return "orderings" in e ? n.push(new L(this.Ar("sort", e.orderings), {})) : 
        // Ordering object
        n.push(new L(this.Ar("sort", [ e, ...t ]), {})), new __PRIVATE_RealtimePipeline(this._db, this.userDataReader, this._userDataWriter, n);
    }
    /**
     * @internal
     * @private
     */    Vr(e) {
        return {
            pipeline: {
                stages: this.stages.map((t => t._toProto(e)))
            }
        };
    }
}

// Copyright 2024 Google LLC* @license
// Copyright 2024 Google LLC

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//      http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
class __PRIVATE_EvaluateResult {
    constructor(e, t) {
        this.type = e, this.value = t;
    }
    static dr() {
        return new __PRIVATE_EvaluateResult("ERROR", void 0);
    }
    static mr() {
        return new __PRIVATE_EvaluateResult("UNSET", void 0);
    }
    static pr() {
        return new __PRIVATE_EvaluateResult("NULL", He);
    }
    static newValue(e) {
        return __PRIVATE_isNullValue(e) ? new __PRIVATE_EvaluateResult("NULL", He) : function __PRIVATE_isBoolean(e) {
            return !!e && "booleanValue" in e;
        }(e) ? new __PRIVATE_EvaluateResult("BOOLEAN", e) : isInteger(e) ? new __PRIVATE_EvaluateResult("INT", e) : __PRIVATE_isDouble(e) ? new __PRIVATE_EvaluateResult("DOUBLE", e) : function __PRIVATE_isTimestampValue(e) {
            return !!e && "timestampValue" in e && !!e.timestampValue;
        }(e) ? new __PRIVATE_EvaluateResult("TIMESTAMP", e) : function __PRIVATE_isString(e) {
            return !!e && "stringValue" in e;
        }
        /** Returns true if `value` is an BytesValue. */ (e) ? new __PRIVATE_EvaluateResult("STRING", e) : function __PRIVATE_isBytes(e) {
            return !!e && "bytesValue" in e;
        }(e) ? new __PRIVATE_EvaluateResult("BYTES", e) : e.referenceValue ? new __PRIVATE_EvaluateResult("REFERENCE", e) : e.geoPointValue ? new __PRIVATE_EvaluateResult("GEO_POINT", e) : isArray(e) ? new __PRIVATE_EvaluateResult("ARRAY", e) : __PRIVATE_isVectorValue(e) ? new __PRIVATE_EvaluateResult("VECTOR", e) : __PRIVATE_isMapValue(e) ? new __PRIVATE_EvaluateResult("MAP", e) : new __PRIVATE_EvaluateResult("ERROR", void 0);
    }
    gr() {
        return "ERROR" === this.type || "UNSET" === this.type;
    }
    yr() {
        return "NULL" === this.type;
    }
}

function __PRIVATE_valueOrUndefined(e) {
    if (!e.gr()) return e.value;
}

function __PRIVATE_unwrapExpression(e) {
    return e instanceof BooleanExpression ? e._expr : e;
}

function __PRIVATE_toEvaluable(e) {
    if ((e = __PRIVATE_unwrapExpression(e)) instanceof o) return new __PRIVATE_CoreField(e);
    if (e instanceof Constant) return new __PRIVATE_CoreConstant(e);
    if (e instanceof __PRIVATE_ListOfExprs) return new __PRIVATE_CoreListOfExprs(e);
    if (e instanceof x) {
        // TODO(pipeline): We should define all supported function names as constants somewhere instead of magic strings.
        if ("add" === e.name) return new __PRIVATE_CoreAdd(e);
        if ("subtract" === e.name) return new __PRIVATE_CoreSubtract(e);
        if ("multiply" === e.name) return new __PRIVATE_CoreMultiply(e);
        if ("divide" === e.name) return new __PRIVATE_CoreDivide(e);
        if ("mod" === e.name) return new __PRIVATE_CoreMod(e);
        if ("and" === e.name) return new __PRIVATE_CoreAnd(e);
        if ("equal" === e.name) return new __PRIVATE_CoreEq(e);
        if ("not_equal" === e.name) return new __PRIVATE_CoreNeq(e);
        if ("less_than" === e.name) return new __PRIVATE_CoreLt(e);
        if ("less_than_or_equal" === e.name) return new __PRIVATE_CoreLte(e);
        if ("greater_than" === e.name) return new __PRIVATE_CoreGt(e);
        if ("greater_than_or_equal" === e.name) return new __PRIVATE_CoreGte(e);
        if ("array_concat" === e.name) return new __PRIVATE_CoreArrayConcat(e);
        if ("array_reverse" === e.name) return new __PRIVATE_CoreArrayReverse(e);
        if ("array_contains" === e.name) return new __PRIVATE_CoreArrayContains(e);
        if ("array_contains_all" === e.name) return new __PRIVATE_CoreArrayContainsAll(e);
        if ("array_contains_any" === e.name) return new __PRIVATE_CoreArrayContainsAny(e);
        if ("array_length" === e.name) return new __PRIVATE_CoreArrayLength(e);
        if ("array_element" === e.name) return new __PRIVATE_CoreArrayElement(e);
        if ("equal_any" === e.name) return new __PRIVATE_CoreEqAny(e);
        if ("not_equal_any" === e.name) return new __PRIVATE_CoreNotEqAny(e);
        if ("is_nan" === e.name) return new __PRIVATE_CoreIsNan(e);
        if ("is_not_nan" === e.name) return new __PRIVATE_CoreIsNotNan(e);
        if ("is_null" === e.name) return new __PRIVATE_CoreIsNull(e);
        if ("is_not_null" === e.name) return new __PRIVATE_CoreIsNotNull(e);
        if ("is_error" === e.name) return new __PRIVATE_CoreIsError(e);
        if ("exists" === e.name) return new __PRIVATE_CoreExists(e);
        if ("not" === e.name) return new __PRIVATE_CoreNot(e);
        if ("or" === e.name) return new __PRIVATE_CoreOr(e);
        if ("xor" === e.name) return new __PRIVATE_CoreXor(e);
        if ("conditional" === e.name) return new __PRIVATE_CoreCond(e);
        if ("maximum" === e.name) return new __PRIVATE_CoreLogicalMaximum(e);
        if ("minimum" === e.name) return new __PRIVATE_CoreLogicalMinimum(e);
        if ("reverse" === e.name) return new __PRIVATE_CoreReverse(e);
        if ("replace_first" === e.name) return new __PRIVATE_CoreReplaceFirst(e);
        if ("replace_all" === e.name) return new __PRIVATE_CoreReplaceAll(e);
        if ("char_length" === e.name) return new __PRIVATE_CoreCharLength(e);
        if ("byte_length" === e.name) return new __PRIVATE_CoreByteLength(e);
        if ("like" === e.name) return new __PRIVATE_CoreLike(e);
        if ("regex_contains" === e.name) return new __PRIVATE_CoreRegexContains(e);
        if ("regex_match" === e.name) return new __PRIVATE_CoreRegexMatch(e);
        if ("string_contains" === e.name) return new __PRIVATE_CoreStrContains(e);
        if ("starts_with" === e.name) return new __PRIVATE_CoreStartsWith(e);
        if ("ends_with" === e.name) return new __PRIVATE_CoreEndsWith(e);
        if ("to_lower" === e.name) return new __PRIVATE_CoreToLower(e);
        if ("to_upper" === e.name) return new __PRIVATE_CoreToUpper(e);
        if ("trim" === e.name) return new __PRIVATE_CoreTrim(e);
        if ("string_concat" === e.name) return new __PRIVATE_CoreStrConcat(e);
        if ("map_get" === e.name) return new __PRIVATE_CoreMapGet(e);
        if ("cosine_distance" === e.name) return new __PRIVATE_CoreCosineDistance(e);
        if ("dot_product" === e.name) return new __PRIVATE_CoreDotProduct(e);
        if ("euclidean_distance" === e.name) return new __PRIVATE_CoreEuclideanDistance(e);
        if ("vector_length" === e.name) return new __PRIVATE_CoreVectorLength(e);
        if ("unix_micros_to_timestamp" === e.name) return new __PRIVATE_CoreUnixMicrosToTimestamp(e);
        if ("timestamp_to_unix_micros" === e.name) return new __PRIVATE_CoreTimestampToUnixMicros(e);
        if ("unix_millis_to_timestamp" === e.name) return new __PRIVATE_CoreUnixMillisToTimestamp(e);
        if ("timestamp_to_unix_millis" === e.name) return new __PRIVATE_CoreTimestampToUnixMillis(e);
        if ("unix_seconds_to_timestamp" === e.name) return new __PRIVATE_CoreUnixSecondsToTimestamp(e);
        if ("timestamp_to_unix_seconds" === e.name) return new __PRIVATE_CoreTimestampToUnixSeconds(e);
        if ("timestamp_add" === e.name) return new __PRIVATE_CoreTimestampAdd(e);
        if ("timestamp_subtract" === e.name) return new __PRIVATE_CoreTimestampSub(e);
    }
    throw new Error(`Unknown Expr : ${e}`);
}

class __PRIVATE_CoreField {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        if (this.expr.fieldName === Ce) return __PRIVATE_EvaluateResult.newValue({
            referenceValue: __PRIVATE_toName(e.serializer, t.key)
        });
        if ("__update_time__" === this.expr.fieldName) return __PRIVATE_EvaluateResult.newValue({
            timestampValue: __PRIVATE_toVersion(e.serializer, t.version)
        });
        if ("__create_time__" === this.expr.fieldName) return __PRIVATE_EvaluateResult.newValue({
            timestampValue: __PRIVATE_toVersion(e.serializer, t.createTime)
        });
        // Return 'UNSET' if the field doesn't exist, otherwise the Value.
                const n = t.data.field(this.expr._fieldPath);
        return n ? __PRIVATE_isServerTimestamp(n) ? __PRIVATE_EvaluateResult.newValue(function __PRIVATE_getServerTimestampValue(e, t) {
            if ("estimate" === e.serverTimestampBehavior) return {
                timestampValue: __PRIVATE_toVersion(e.serializer, SnapshotVersion.fromTimestamp(__PRIVATE_getLocalWriteTime(t)))
            };
            if ("previous" === e.serverTimestampBehavior) {
                const e = __PRIVATE_getPreviousValue(t);
                if (e) return e;
            }
            return {
                nullValue: "NULL_VALUE"
            };
        }(e, n)) : __PRIVATE_EvaluateResult.newValue(n) : __PRIVATE_EvaluateResult.mr();
    }
}

class __PRIVATE_CoreConstant {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        return __PRIVATE_EvaluateResult.newValue(this.expr._getValue());
    }
}

class __PRIVATE_CoreListOfExprs {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        const n = this.expr.ur.map((n => __PRIVATE_toEvaluable(n).evaluate(e, t)));
        // If any sub-expression resulted in error or was unset, the list evaluation fails.
                return n.some((e => e.gr())) ? __PRIVATE_EvaluateResult.dr() : __PRIVATE_EvaluateResult.newValue({
            arrayValue: {
                values: n.map((e => e.value))
            }
        });
    }
}

function __PRIVATE_asDouble(e) {
    return __PRIVATE_isDouble(e) ? Number(e.doubleValue) : Number(e.integerValue);
}

function __PRIVATE_asBigInt(e) {
    return BigInt(e.integerValue);
}

const Ft = BigInt("0x7fffffffffffffff"), Ot = -BigInt("0x8000000000000000");

class __PRIVATE_BigIntOrDoubleArithmetics {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(this.expr.params.length >= 2, 24778);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t), r = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        let i = this.wr(n, r);
        for (const n of this.expr.params.slice(2)) {
            const r = __PRIVATE_toEvaluable(n).evaluate(e, t);
            i = this.wr(i, r);
        }
        return i;
    }
    wr(e, t) {
        // If any operand is error or unset, the result is error.
        if (e.gr() || t.gr()) return __PRIVATE_EvaluateResult.dr();
        if (e.yr() || t.yr()) return __PRIVATE_EvaluateResult.pr();
        // Type check: Both must be numbers (integer or double).
        // We know left and right are Value here due to the check above.
                const n = e.value, r = t.value;
        if (!__PRIVATE_isDouble(n) && !isInteger(n) || !__PRIVATE_isDouble(r) && !isInteger(r)) return __PRIVATE_EvaluateResult.dr(); // Type error
        // Perform arithmetic based on types.
                if (__PRIVATE_isDouble(n) || __PRIVATE_isDouble(r)) {
            const e = this.br(n, r);
            return e ? __PRIVATE_EvaluateResult.newValue(e) : __PRIVATE_EvaluateResult.dr();
        }
        if (isInteger(n) && isInteger(r)) {
            // Pass the narrowed Value types
            const e = this.vr(n, r);
            return void 0 === e ? __PRIVATE_EvaluateResult.dr() : "number" == typeof e ? __PRIVATE_EvaluateResult.newValue({
                doubleValue: e
            }) : e < Ot || e > Ft ? __PRIVATE_EvaluateResult.dr() : __PRIVATE_EvaluateResult.newValue({
                integerValue: `${e}`
            });
        }
        // Should not be reached due to initial type checks
                return __PRIVATE_EvaluateResult.dr();
    }
}

function __PRIVATE_strictValueEquals(e, t) {
    return __PRIVATE_typeOrder(e) !== __PRIVATE_typeOrder(t) ? "TYPE_MISMATCH" : __PRIVATE_isNanValue(e) || __PRIVATE_isNanValue(t) ? "NOT_EQ" : __PRIVATE_isNullValue(e) && __PRIVATE_isNullValue(t) ? "EQ" : __PRIVATE_isNullValue(e) || __PRIVATE_isNullValue(t) ? "NULL" : isArray(e) && isArray(t) ? function __PRIVATE_strictArrayValueEquals(e, t) {
        if (e.values?.length !== t.values?.length) return "NOT_EQ";
        let n = false;
        for (let r = 0; r < (e.values?.length ?? 0); r++) {
            const i = e.values[r], s = t.values[r];
            switch (__PRIVATE_strictValueEquals(i, s)) {
              case "EQ":
                break;

              case "NOT_EQ":
              case "TYPE_MISMATCH":
                return "NOT_EQ";

              case "NULL":
                n = true;
                break;

              default:
                l(44609, {
                    Sr: i,
                    Dr: s
                });
            }
        }
        if (n) return "NULL";
        return "EQ";
    }(e.arrayValue, t.arrayValue) : __PRIVATE_isVectorValue(e) && __PRIVATE_isVectorValue(t) || __PRIVATE_isMapValue(e) && __PRIVATE_isMapValue(t) ? function __PRIVATE_strictObjectValueEquals(e, t) {
        const n = e.fields || {}, r = t.fields || {};
        if (__PRIVATE_objectSize(n) !== __PRIVATE_objectSize(r)) return "NOT_EQ";
        let i = false;
        for (const e in n) if (n.hasOwnProperty(e)) {
            if (void 0 === r[e]) return "NOT_EQ";
            switch (__PRIVATE_strictValueEquals(n[e], r[e])) {
              case "NOT_EQ":
              case "TYPE_MISMATCH":
                return "NOT_EQ";

              case "NULL":
                i = true;
            }
        }
        if (i) return "NULL";
        return "EQ";
    }(e.mapValue, t.mapValue) : function __PRIVATE_valueEquals(e, t) {
        return __PRIVATE_valueEquals$1(e, t, {
            o: false,
            t: true,
            i: true
        });
    }(e, t) ? "EQ" : "NOT_EQ";
}

class __PRIVATE_CoreAdd extends __PRIVATE_BigIntOrDoubleArithmetics {
    vr(e, t) {
        return __PRIVATE_asBigInt(e) + __PRIVATE_asBigInt(t);
    }
    br(e, t) {
        return {
            doubleValue: __PRIVATE_asDouble(e) + __PRIVATE_asDouble(t)
        };
    }
}

class __PRIVATE_CoreSubtract extends __PRIVATE_BigIntOrDoubleArithmetics {
    constructor(e) {
        super(e), this.expr = e;
    }
    vr(e, t) {
        return __PRIVATE_asBigInt(e) - __PRIVATE_asBigInt(t);
    }
    br(e, t) {
        return {
            doubleValue: __PRIVATE_asDouble(e) - __PRIVATE_asDouble(t)
        };
    }
}

class __PRIVATE_CoreMultiply extends __PRIVATE_BigIntOrDoubleArithmetics {
    constructor(e) {
        super(e), this.expr = e;
    }
    vr(e, t) {
        return __PRIVATE_asBigInt(e) * __PRIVATE_asBigInt(t);
    }
    br(e, t) {
        return {
            doubleValue: __PRIVATE_asDouble(e) * __PRIVATE_asDouble(t)
        };
    }
}

class __PRIVATE_CoreDivide extends __PRIVATE_BigIntOrDoubleArithmetics {
    constructor(e) {
        super(e), this.expr = e;
    }
    vr(e, t) {
        const n = __PRIVATE_asBigInt(t);
        if (n !== BigInt(0)) return __PRIVATE_asBigInt(e) / n;
    }
    br(e, t) {
        const n = __PRIVATE_asDouble(t);
        return 0 === n ? {
            doubleValue: __PRIVATE_isNegativeZero(n) ? Number.NEGATIVE_INFINITY : Number.POSITIVE_INFINITY
        } : {
            doubleValue: __PRIVATE_asDouble(e) / n
        };
    }
}

class __PRIVATE_CoreMod extends __PRIVATE_BigIntOrDoubleArithmetics {
    constructor(e) {
        super(e), this.expr = e;
    }
    vr(e, t) {
        const n = __PRIVATE_asBigInt(t);
        if (n !== BigInt(0)) return __PRIVATE_asBigInt(e) % n;
    }
    br(e, t) {
        const n = __PRIVATE_asDouble(t);
        if (0 !== n) return {
            doubleValue: __PRIVATE_asDouble(e) % n
        };
    }
}

class __PRIVATE_CoreAnd {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        let n = false, r = false;
        for (const i of this.expr.params) {
            const s = __PRIVATE_toEvaluable(i).evaluate(e, t);
            switch (s.type) {
              case "BOOLEAN":
                if (!s.value?.booleanValue) return __PRIVATE_EvaluateResult.newValue(Ye);
                break;

              case "NULL":
                r = true;
                break;

              default:
                n = true;
            }
        }
        return n ? __PRIVATE_EvaluateResult.dr() : r ? __PRIVATE_EvaluateResult.pr() : __PRIVATE_EvaluateResult.newValue(Je);
    }
}

class __PRIVATE_CoreNot {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 9634);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "BOOLEAN":
            return __PRIVATE_EvaluateResult.newValue({
                booleanValue: !n.value?.booleanValue
            });

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreOr {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        let n = false, r = false;
        for (const i of this.expr.params) {
            const s = __PRIVATE_toEvaluable(i).evaluate(e, t);
            switch (s.type) {
              case "BOOLEAN":
                if (s.value?.booleanValue) return __PRIVATE_EvaluateResult.newValue(Je);
                break;

              case "NULL":
                r = true;
                break;

              default:
                n = true;
            }
        }
        return n ? __PRIVATE_EvaluateResult.dr() : r ? __PRIVATE_EvaluateResult.pr() : __PRIVATE_EvaluateResult.newValue(Ye);
    }
}

class __PRIVATE_CoreXor {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        let n = false, r = false;
        for (const i of this.expr.params) {
            const s = __PRIVATE_toEvaluable(i).evaluate(e, t);
            switch (s.type) {
              case "BOOLEAN":
                n = __PRIVATE_CoreXor.xor(n, !!s.value?.booleanValue);
                break;

              case "NULL":
                r = true;
                break;

              default:
                return __PRIVATE_EvaluateResult.dr();
            }
        }
        return r ? __PRIVATE_EvaluateResult.pr() : __PRIVATE_EvaluateResult.newValue({
            booleanValue: n
        });
    }
    // XOR(a, b) is equivalent to (a OR b) AND NOT(a AND b)
    // It is required to evaluate all arguments to ensure that the correct error semantics are
    // applied.
    static xor(e, t) {
        return (e || t) && !(e && t);
    }
}

class __PRIVATE_CoreEqAny {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(2 === this.expr.params.length, 55094);
        let n = false;
        const r = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (r.type) {
          case "NULL":
            n = true;
            break;

          case "ERROR":
          case "UNSET":
            return __PRIVATE_EvaluateResult.dr();
        }
        const i = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        switch (i.type) {
          case "ARRAY":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        if (n) return __PRIVATE_EvaluateResult.pr();
        for (const e of i.value?.arrayValue?.values ?? []) {
            switch (__PRIVATE_isNullValue(r.value) && __PRIVATE_isNullValue(e) ? "EQ" : __PRIVATE_strictValueEquals(r.value, e)) {
              case "EQ":
                return __PRIVATE_EvaluateResult.newValue(Je);

              case "NOT_EQ":
              case "TYPE_MISMATCH":
                break;

              case "NULL":
                n = true;
                break;

              default:
                l(44608, {
                    value: r.value,
                    candidate: e
                });
            }
        }
        return n ? __PRIVATE_EvaluateResult.pr() : __PRIVATE_EvaluateResult.newValue(Ye);
    }
}

class __PRIVATE_CoreNotEqAny {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        return new __PRIVATE_CoreNot(new x("not", [ new x("equal_any", this.expr.params) ])).evaluate(e, t);
    }
}

class __PRIVATE_CoreIsNan {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 23322);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "INT":
            return __PRIVATE_EvaluateResult.newValue(Ye);

          case "DOUBLE":
            return __PRIVATE_EvaluateResult.newValue({
                booleanValue: isNaN(__PRIVATE_asDouble(n.value))
            });

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreIsNotNan {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 50406);
        return new __PRIVATE_CoreNot(new x("not", [ new x("is_nan", this.expr.params) ])).evaluate(e, t);
    }
}

class __PRIVATE_CoreIsNull {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 23123);
        switch (__PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t).type) {
          case "NULL":
            return __PRIVATE_EvaluateResult.newValue(Je);

          case "UNSET":
          case "ERROR":
            return __PRIVATE_EvaluateResult.dr();

          default:
            return __PRIVATE_EvaluateResult.newValue(Ye);
        }
    }
}

class __PRIVATE_CoreIsNotNull {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 23167);
        return new __PRIVATE_CoreNot(new x("not", [ new x("is_null", this.expr.params) ])).evaluate(e, t);
    }
}

class __PRIVATE_CoreIsError {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 5228);
        return "ERROR" === __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t).type ? __PRIVATE_EvaluateResult.newValue(Je) : __PRIVATE_EvaluateResult.newValue(Ye);
    }
}

class __PRIVATE_CoreExists {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 6877);
        switch (__PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t).type) {
          case "ERROR":
            return __PRIVATE_EvaluateResult.dr();

          case "UNSET":
            return __PRIVATE_EvaluateResult.newValue(Ye);

          default:
            return __PRIVATE_EvaluateResult.newValue(Je);
        }
    }
}

class __PRIVATE_CoreCond {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(3 === this.expr.params.length, 11706);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "BOOLEAN":
            return n.value?.booleanValue ? __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t) : __PRIVATE_toEvaluable(this.expr.params[2]).evaluate(e, t);

          case "NULL":
            return __PRIVATE_toEvaluable(this.expr.params[2]).evaluate(e, t);

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreLogicalMaximum {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        const n = this.expr.params.map((n => __PRIVATE_toEvaluable(n).evaluate(e, t)));
        let r;
        for (const e of n) switch (e.type) {
          case "ERROR":
          case "UNSET":
          case "NULL":
            continue;

          default:
            r = void 0 === r || __PRIVATE_valueCompare(e.value, r.value) > 0 ? e : r;
        }
        return void 0 === r ? __PRIVATE_EvaluateResult.pr() : r;
    }
}

class __PRIVATE_CoreLogicalMinimum {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        const n = this.expr.params.map((n => __PRIVATE_toEvaluable(n).evaluate(e, t)));
        let r;
        for (const e of n) switch (e.type) {
          case "ERROR":
          case "UNSET":
          case "NULL":
            continue;

          default:
            r = void 0 === r || __PRIVATE_valueCompare(e.value, r.value) < 0 ? e : r;
        }
        return void 0 === r ? __PRIVATE_EvaluateResult.pr() : r;
    }
}

class __PRIVATE_ComparisonBase {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(2 === this.expr.params.length, 31033, `${this.expr.name}() function should have exactly 2 params`);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "ERROR":
          case "UNSET":
            return __PRIVATE_EvaluateResult.dr();
        }
        const r = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        switch (r.type) {
          case "ERROR":
          case "UNSET":
            return __PRIVATE_EvaluateResult.dr();
        }
        return this.Cr(n, r);
    }
}

class __PRIVATE_CoreEq extends __PRIVATE_ComparisonBase {
    constructor(e) {
        super(e), this.expr = e;
    }
    Cr(e, t) {
        if (e.yr() && t.yr()) return __PRIVATE_EvaluateResult.newValue(Je);
        if (e.yr() || t.yr()) return __PRIVATE_EvaluateResult.newValue(Ye);
        if (__PRIVATE_isNanValue(e.value) || __PRIVATE_isNanValue(t.value)) return __PRIVATE_EvaluateResult.newValue(Ye);
        if (__PRIVATE_typeOrder(e.value) !== __PRIVATE_typeOrder(t.value)) return __PRIVATE_EvaluateResult.newValue(Ye);
        switch (__PRIVATE_strictValueEquals(e.value, t.value)) {
          case "EQ":
            return __PRIVATE_EvaluateResult.newValue(Je);

          case "NOT_EQ":
            return __PRIVATE_EvaluateResult.newValue(Ye);

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            l(44615, {
                left: e,
                right: t
            });
        }
    }
}

class __PRIVATE_CoreNeq extends __PRIVATE_ComparisonBase {
    constructor(e) {
        super(e), this.expr = e;
    }
    Cr(e, t) {
        switch (__PRIVATE_strictValueEquals(e.value, t.value)) {
          case "EQ":
            return __PRIVATE_EvaluateResult.newValue(Ye);

          case "NOT_EQ":
          case "TYPE_MISMATCH":
            return __PRIVATE_EvaluateResult.newValue(Je);

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            l(44614, {
                left: e,
                right: t
            });
        }
    }
}

class __PRIVATE_CoreLt extends __PRIVATE_ComparisonBase {
    constructor(e) {
        super(e), this.expr = e;
    }
    Cr(e, t) {
        return __PRIVATE_typeOrder(e.value) !== __PRIVATE_typeOrder(t.value) || __PRIVATE_isNanValue(e.value) || __PRIVATE_isNanValue(t.value) ? __PRIVATE_EvaluateResult.newValue(Ye) : __PRIVATE_EvaluateResult.newValue({
            booleanValue: __PRIVATE_valueCompare(e.value, t.value) < 0
        });
    }
}

class __PRIVATE_CoreLte extends __PRIVATE_ComparisonBase {
    constructor(e) {
        super(e), this.expr = e;
    }
    Cr(e, t) {
        return __PRIVATE_typeOrder(e.value) !== __PRIVATE_typeOrder(t.value) || __PRIVATE_isNanValue(e.value) || __PRIVATE_isNanValue(t.value) ? __PRIVATE_EvaluateResult.newValue(Ye) : "EQ" === __PRIVATE_strictValueEquals(e.value, t.value) ? __PRIVATE_EvaluateResult.newValue(Je) : __PRIVATE_EvaluateResult.newValue({
            booleanValue: __PRIVATE_valueCompare(e.value, t.value) < 0
        });
    }
}

class __PRIVATE_CoreGt extends __PRIVATE_ComparisonBase {
    constructor(e) {
        super(e), this.expr = e;
    }
    Cr(e, t) {
        return __PRIVATE_typeOrder(e.value) !== __PRIVATE_typeOrder(t.value) || __PRIVATE_isNanValue(e.value) || __PRIVATE_isNanValue(t.value) ? __PRIVATE_EvaluateResult.newValue(Ye) : __PRIVATE_EvaluateResult.newValue({
            booleanValue: __PRIVATE_valueCompare(e.value, t.value) > 0
        });
    }
}

class __PRIVATE_CoreGte extends __PRIVATE_ComparisonBase {
    constructor(e) {
        super(e), this.expr = e;
    }
    Cr(e, t) {
        return __PRIVATE_typeOrder(e.value) !== __PRIVATE_typeOrder(t.value) || __PRIVATE_isNanValue(e.value) || __PRIVATE_isNanValue(t.value) ? __PRIVATE_EvaluateResult.newValue(Ye) : "EQ" === __PRIVATE_strictValueEquals(e.value, t.value) ? __PRIVATE_EvaluateResult.newValue(Je) : __PRIVATE_EvaluateResult.newValue({
            booleanValue: __PRIVATE_valueCompare(e.value, t.value) > 0
        });
    }
}

class __PRIVATE_CoreArrayConcat {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        throw new Error("Unimplemented");
    }
}

class __PRIVATE_CoreArrayReverse {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 216);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          case "ARRAY":
            {
                const e = n.value.arrayValue?.values ?? [];
                return __PRIVATE_EvaluateResult.newValue({
                    arrayValue: {
                        values: [ ...e ].reverse()
                    }
                });
            }

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreArrayContains {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        return __PRIVATE_hardAssert(2 === this.expr.params.length, 52884), new __PRIVATE_CoreEqAny(new x("eq_any", [ this.expr.params[1], this.expr.params[0] ])).evaluate(e, t);
    }
}

class __PRIVATE_CoreArrayContainsAll {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(2 === this.expr.params.length, 1392);
        let n = false;
        const r = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (r.type) {
          case "ARRAY":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        const i = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        switch (i.type) {
          case "ARRAY":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        if (n) return __PRIVATE_EvaluateResult.pr();
        const s = i.value?.arrayValue?.values ?? [], _ = r.value?.arrayValue?.values ?? [];
        for (const e of s) {
            let t = false;
            n = false;
            for (const r of _) {
                switch (__PRIVATE_isNullValue(e) && __PRIVATE_isNullValue(r) ? "EQ" : __PRIVATE_strictValueEquals(e, r)) {
                  case "EQ":
                    t = true;
                    break;

                  case "NOT_EQ":
                  case "TYPE_MISMATCH":
                    break;

                  case "NULL":
                    n = true;
                    break;

                  default:
                    l(44613, {
                        value: r,
                        search: e
                    });
                }
                if (t) 
                // short circuit
                break;
            }
            if (!t) 
            // false case - we didn't find a match, short circuit
            return __PRIVATE_EvaluateResult.newValue(Ye);
        }
        return __PRIVATE_EvaluateResult.newValue(Je);
    }
}

class __PRIVATE_CoreArrayContainsAny {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(2 === this.expr.params.length, 2680);
        let n = false;
        const r = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (r.type) {
          case "ARRAY":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        const i = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        switch (i.type) {
          case "ARRAY":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        if (n) return __PRIVATE_EvaluateResult.pr();
        const s = i.value?.arrayValue?.values ?? [], _ = r.value?.arrayValue?.values ?? [];
        for (const e of _) for (const t of s) {
            switch (__PRIVATE_isNullValue(e) && __PRIVATE_isNullValue(t) ? "EQ" : __PRIVATE_strictValueEquals(e, t)) {
              case "EQ":
                return __PRIVATE_EvaluateResult.newValue(Je);

              case "NOT_EQ":
              case "TYPE_MISMATCH":
                break;

              case "NULL":
                n = true;
                break;

              default:
                l(60403, {
                    value: e,
                    search: t
                });
            }
        }
        return n ? __PRIVATE_EvaluateResult.pr() : __PRIVATE_EvaluateResult.newValue(Ye);
    }
}

class __PRIVATE_CoreArrayLength {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 38605);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          case "ARRAY":
            return __PRIVATE_EvaluateResult.newValue({
                integerValue: `${n.value?.arrayValue?.values?.length ?? 0}`
            });

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreArrayElement {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        throw new Error("Unimplemented");
    }
}

class __PRIVATE_CoreReverse {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 1508);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          case "BYTES":
            {
                const e = n.value?.bytesValue;
                if ("string" == typeof e) {
                    const t = ByteString.fromBase64String(e).toUint8Array();
                    return t.reverse(), __PRIVATE_EvaluateResult.newValue({
                        bytesValue: ByteString.fromUint8Array(t).toBase64()
                    });
                }
                return __PRIVATE_EvaluateResult.newValue({
                    bytesValue: new Uint8Array(e).reverse()
                });
            }

          case "STRING":
            {
                const e = n.value?.stringValue, t = new Intl.__PRIVATE_Segmenter(void 0, {
                    granularity: "grapheme"
                }).segment(e), r = Array.from(t, (e => e.segment)).reverse();
                return __PRIVATE_EvaluateResult.newValue({
                    stringValue: r.join("")
                });
            }

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreReplaceFirst {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        throw new Error("Unimplemented");
    }
}

class __PRIVATE_CoreReplaceAll {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        throw new Error("Unimplemented");
    }
}

class __PRIVATE_CoreCharLength {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 19400);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          case "STRING":
            {
                const e = function __PRIVATE_getUnicodePointCount(e) {
                    let t = 0;
                    for (let n = 0; n < e.length; n++) {
                        const r = e.codePointAt(n);
                        if (void 0 === r) return; // Should not happen with valid JS strings
                        // BMP character (including lone surrogates, which count as 1)
                                                if (r <= 65535) 
                        // Check specifically for lone surrogates which are invalid UTF-16 sequences
                        if (r >= 55296 && r <= 57343) 
                        // High surrogate: check if followed by low surrogate
                        if (r <= 56319) {
                            const r = e.codePointAt(n + 1);
                            void 0 !== r && r >= 56320 && r <= 57343 ? (
                            // Valid surrogate pair (counts as one character)
                            t += 1, n++) : 
                            // Lone high surrogate - treat as one character for length, but invalid for byte length
                            t += 1;
                        } else 
                        // Lone low surrogate - treat as one character
                        t += 1; else 
                        // Regular BMP character
                        t += 1; else {
                            if (!(r <= 1114111)) return;
 // Invalid code point
                                                        t += 1, n++;
                        }
                    }
                    return t;
                }(n.value.stringValue);
                // If counting failed (e.g., invalid sequence), return error
                                return void 0 === e ? __PRIVATE_EvaluateResult.dr() : __PRIVATE_EvaluateResult.newValue({
                    integerValue: e
                });
            }

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreByteLength {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 8486);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "BYTES":
            {
                const e = n.value?.bytesValue;
                return "string" == typeof e ? __PRIVATE_EvaluateResult.newValue({
                    integerValue: ByteString.fromBase64String(e).toUint8Array().length
                }) : __PRIVATE_EvaluateResult.newValue({
                    integerValue: new Uint8Array(e).length
                });
            }

          case "STRING":
            {
                // return the number of bytes in the string
                const e = function __PRIVATE_getUtf8ByteLength(e) {
                    let t = 0;
                    for (let n = 0; n < e.length; n++) {
                        const r = e.codePointAt(n);
                        // Check for out of range of lone surrogate
                                                if (void 0 === r) return;
                        if (r >= 55296 && r <= 57343) {
                            // If it is a high surrogate, check if a low surrogate follows
                            if (!(r <= 56319)) return;
 // Lone low surrogate
                                                        {
                                const r = e.codePointAt(n + 1);
                                if (void 0 === r || !(r >= 56320 && r <= 57343)) return; // Lone high surrogate
                                // Valid surrogate pair
                                                                t += 4, n++;
                            }
                        } else if (r <= 127) t += 1; else if (r <= 2047) t += 2; else if (r <= 65535) t += 3; else {
                            if (!(r <= 1114111)) return;
 // Invalid code point (should not normally happen)
                                                        t += 4, n++;
                        }
                    }
                    return t;
                }(n.value?.stringValue);
                return void 0 === e ? __PRIVATE_EvaluateResult.dr() : __PRIVATE_EvaluateResult.newValue({
                    integerValue: e
                });
            }

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_StringSearchFunctionBase {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(2 === this.expr.params.length, 39773, `${this.expr.name}() function should have exactly two parameters`);
        let n = false;
        const r = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (r.type) {
          case "STRING":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        const i = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        switch (i.type) {
          case "STRING":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        return n ? __PRIVATE_EvaluateResult.pr() : this.Fr(r.value?.stringValue, i.value?.stringValue);
    }
}

class __PRIVATE_CoreLike extends __PRIVATE_StringSearchFunctionBase {
    Fr(e, t) {
        try {
            const n = function __PRIVATE_likeToRegex(e) {
                let t = "";
                for (let n = 0; n < e.length; n++) {
                    const r = e.charAt(n);
                    switch (r) {
                      case "_":
                        t += ".";
                        break;

                      case "%":
                        t += ".*";
                        break;

                        // Escape regex special characters
                                              case "\\":
 // Need to escape backslash itself
                                              case ".":
                      case "*":
                      case "?":
                      case "+":
                      case "^":
                      case "$":
                      case "|":
                      case "(":
                      case ")":
                      case "[":
                      case "]":
                      case "{":
                      case "}":
                        t += "\\" + r;
                        break;

                      default:
                        t += r;
                    }
                }
                // Anchor the regex to match the entire string
                                return "^" + t + "$";
            }(t), r = re2js.RE2JS.compile(n);
            return __PRIVATE_EvaluateResult.newValue({
                booleanValue: r.matches(e)
            });
        } catch (e) {
            return __PRIVATE_logWarn(`Invalid LIKE pattern converted to regex: ${t}, returning error. Error: ${e}`), 
            __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreRegexContains extends __PRIVATE_StringSearchFunctionBase {
    Fr(e, t) {
        try {
            const n = re2js.RE2JS.compile(t);
            return __PRIVATE_EvaluateResult.newValue({
                booleanValue: n.test(e)
            });
        } catch (e) {
            return __PRIVATE_logWarn(`Invalid regex pattern found in regex_contains: ${t}, returning error`), 
            __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreRegexMatch extends __PRIVATE_StringSearchFunctionBase {
    Fr(e, t) {
        try {
            // Use matches() for full string match semantics
            return __PRIVATE_EvaluateResult.newValue({
                booleanValue: re2js.RE2JS.compile(t).matches(e)
            });
        } catch (e) {
            return __PRIVATE_logWarn(`Invalid regex pattern found in regex_match: ${t}, returning error`), 
            __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreStrContains extends __PRIVATE_StringSearchFunctionBase {
    Fr(e, t) {
        return __PRIVATE_EvaluateResult.newValue({
            booleanValue: e.includes(t)
        });
    }
}

class __PRIVATE_CoreStartsWith extends __PRIVATE_StringSearchFunctionBase {
    Fr(e, t) {
        return __PRIVATE_EvaluateResult.newValue({
            booleanValue: e.startsWith(t)
        });
    }
}

class __PRIVATE_CoreEndsWith extends __PRIVATE_StringSearchFunctionBase {
    Fr(e, t) {
        return __PRIVATE_EvaluateResult.newValue({
            booleanValue: e.endsWith(t)
        });
    }
}

class __PRIVATE_CoreToLower {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 29079);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "STRING":
            return __PRIVATE_EvaluateResult.newValue({
                stringValue: n.value?.stringValue?.toLowerCase()
            });

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreToUpper {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 60487);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "STRING":
            return __PRIVATE_EvaluateResult.newValue({
                stringValue: n.value?.stringValue?.toUpperCase()
            });

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreTrim {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 28544);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "STRING":
            return __PRIVATE_EvaluateResult.newValue({
                stringValue: n.value?.stringValue?.trim()
            });

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreStrConcat {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        const n = this.expr.params.map((n => __PRIVATE_toEvaluable(n).evaluate(e, t)));
        // If any part is error or unset, or not a string (and not null), result is error
        // If any part is null, result is null
                let r = "", i = false;
        for (const e of n) switch (e.type) {
          case "STRING":
            r += e.value.stringValue;
            break;

          case "NULL":
            i = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        return i ? __PRIVATE_EvaluateResult.pr() : __PRIVATE_EvaluateResult.newValue({
            stringValue: r
        });
    }
}

class __PRIVATE_CoreMapGet {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(2 === this.expr.params.length, 4483);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "UNSET":
            return __PRIVATE_EvaluateResult.mr();

          case "MAP":
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        const r = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        if ("STRING" !== r.type) return __PRIVATE_EvaluateResult.dr();
        const i = n.value?.mapValue?.fields?.[r.value?.stringValue];
        return void 0 === i ? __PRIVATE_EvaluateResult.mr() : __PRIVATE_EvaluateResult.newValue(i);
    }
}

class __PRIVATE_DistanceBase {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(2 === this.expr.params.length, 25231, `${this.expr.name}() function should have exactly 2 params`);
        let n = false;
        const r = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (r.type) {
          case "VECTOR":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        const i = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        switch (i.type) {
          case "VECTOR":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        if (n) return __PRIVATE_EvaluateResult.pr();
        const s = __PRIVATE_getVectorValue(r.value), _ = __PRIVATE_getVectorValue(i.value);
        // Mismatched lengths or undefined vectors result in error
        if (void 0 === s || void 0 === _ || s.values?.length !== _.values?.length) return __PRIVATE_EvaluateResult.dr();
        const o = this.Or(s, _);
        // NaN or undefined distance calculation results in error
                return void 0 === o || isNaN(o) ? __PRIVATE_EvaluateResult.dr() : __PRIVATE_EvaluateResult.newValue({
            doubleValue: o
        });
    }
}

class __PRIVATE_CoreCosineDistance extends __PRIVATE_DistanceBase {
    Or(e, t) {
        const n = e?.values ?? [], r = t?.values ?? [];
        if (0 === n.length) return;
 // Distance undefined for empty vectors
                let i = 0, s = 0, _ = 0;
        for (let e = 0; e < n.length; e++) {
            // Error if any element is not a number
            if (!R(n[e]) || !R(r[e])) return;
            const t = __PRIVATE_asDouble(n[e]), o = __PRIVATE_asDouble(r[e]);
            i += t * o, s += t * t, _ += o * o;
        }
        const o = Math.sqrt(s) * Math.sqrt(_);
        // Distance undefined if either vector has zero magnitude
                if (0 === o) return;
        // Clamp cosine similarity to [-1, 1] due to potential floating point inaccuracies
                return 1 - Math.max(-1, Math.min(1, i / o));
    }
}

class __PRIVATE_CoreDotProduct extends __PRIVATE_DistanceBase {
    Or(e, t) {
        const n = e?.values ?? [], r = t?.values ?? [];
        if (0 === n.length) return 0;
 // Dot product of empty vectors is 0
                let i = 0;
        for (let e = 0; e < n.length; e++) {
            // Error if any element is not a number
            if (!R(n[e]) || !R(r[e])) return;
            i += __PRIVATE_asDouble(n[e]) * __PRIVATE_asDouble(r[e]);
        }
        return i;
    }
}

class __PRIVATE_CoreEuclideanDistance extends __PRIVATE_DistanceBase {
    Or(e, t) {
        const n = e?.values ?? [], r = t?.values ?? [];
        if (0 === n.length) return 0;
 // Distance between empty vectors is 0
                let i = 0;
        for (let e = 0; e < n.length; e++) {
            // Error if any element is not a number
            if (!R(n[e]) || !R(r[e])) return;
            const t = __PRIVATE_asDouble(n[e]), s = __PRIVATE_asDouble(r[e]);
            i += Math.pow(t - s, 2);
        }
        return Math.sqrt(i);
    }
}

class __PRIVATE_CoreVectorLength {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 39044);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "VECTOR":
            {
                const e = __PRIVATE_getVectorValue(n.value);
                return __PRIVATE_EvaluateResult.newValue({
                    integerValue: e?.values?.length ?? 0
                });
            }

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

// 0001-01-01T00:00:00Z
const Mt = BigInt(-62135596800), Nt = BigInt(253402300799), Lt = BigInt(1e3), Bt = BigInt(1e6), Ut = Mt * Lt, kt = Nt * Lt + BigInt(999), qt = Mt * Bt, $t = Nt * Bt + BigInt(999999);

// 9999-12-31T23:59:59Z - but the max timestamp has 999,999,999 nanoseconds
// Max sub-second micros
function __PRIVATE_isMicrosInBounds(e) {
    return e >= qt && e <= $t;
}

function __PRIVATE_isSecondsInBounds(e) {
    return e >= Mt && e <= Nt;
}

function __PRIVATE_isTimestampInBounds(e, t) {
    const n = BigInt(e);
    return !(n < Mt || n > Nt) && (
    // Nanos must be non-negative and less than 1 second
    !(t < 0 || t >= 1e9) && (
    // Additional check for min/max boundaries
    (n !== Mt || 0 === t) && !(n === Nt && t > 999999999)));
}

// Helper function to adjust timestamp for negative nanoseconds
function __PRIVATE_adjustTimestamp(e, t) {
    return t < 0 ? {
        seconds: e - 1,
        nanos: t + 1e9
    } : {
        seconds: e,
        nanos: t
    };
}

function __PRIVATE_timestampToMicros(e) {
    return BigInt(e.seconds) * Bt + 
    // Integer division truncates towards zero
    BigInt(Math.trunc(e.nanoseconds / 1e3));
}

class __PRIVATE_UnixToTimestamp {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 49262, `${this.expr.name}() function should have exactly one parameter`);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "INT":
            return this.toTimestamp(BigInt(n.value.integerValue));

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
    }
}

class __PRIVATE_CoreUnixMicrosToTimestamp extends __PRIVATE_UnixToTimestamp {
    toTimestamp(e) {
        if (!__PRIVATE_isMicrosInBounds(e)) return __PRIVATE_EvaluateResult.dr();
        let t = Number(e / Bt), n = Number(e % Bt * BigInt(1e3));
        // Note: BigInt modulo can result in negative values if the dividend is negative.
                // Adjust for negative nanoseconds
        const r = __PRIVATE_adjustTimestamp(t, n);
        // Final bounds check after adjustment
        return t = r.seconds, n = r.nanos, __PRIVATE_isTimestampInBounds(t, n) ? __PRIVATE_EvaluateResult.newValue({
            timestampValue: {
                seconds: t,
                nanos: n
            }
        }) : __PRIVATE_EvaluateResult.dr();
    }
}

class __PRIVATE_CoreUnixMillisToTimestamp extends __PRIVATE_UnixToTimestamp {
    toTimestamp(e) {
        if (!function __PRIVATE_isMillisInBounds(e) {
            return e >= Ut && e <= kt;
        }(e)) return __PRIVATE_EvaluateResult.dr();
        let t = Number(e / Lt), n = Number(e % Lt * BigInt(1e6));
        // Adjust for negative nanoseconds
        const r = __PRIVATE_adjustTimestamp(t, n);
        // Final bounds check after adjustment
        return t = r.seconds, n = r.nanos, __PRIVATE_isTimestampInBounds(t, n) ? __PRIVATE_EvaluateResult.newValue({
            timestampValue: {
                seconds: t,
                nanos: n
            }
        }) : __PRIVATE_EvaluateResult.dr();
    }
}

class __PRIVATE_CoreUnixSecondsToTimestamp extends __PRIVATE_UnixToTimestamp {
    toTimestamp(e) {
        if (!__PRIVATE_isSecondsInBounds(e)) return __PRIVATE_EvaluateResult.dr();
        const t = Number(e);
        return __PRIVATE_EvaluateResult.newValue({
            timestampValue: {
                seconds: t,
                nanos: 0
            }
        });
    }
}

class __PRIVATE_TimestampToUnix {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(1 === this.expr.params.length, 1265, `${this.expr.name}() function should have exactly one parameter`);
        const n = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (n.type) {
          case "TIMESTAMP":
            break;

          case "NULL":
            return __PRIVATE_EvaluateResult.pr();

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        const r = fromTimestamp(n.value.timestampValue);
        // Check if the input timestamp is within valid bounds
                return __PRIVATE_isTimestampInBounds(r.seconds, r.nanoseconds) ? this.Mr(r) : __PRIVATE_EvaluateResult.dr();
    }
}

class __PRIVATE_CoreTimestampToUnixMicros extends __PRIVATE_TimestampToUnix {
    Mr(e) {
        const t = __PRIVATE_timestampToMicros(e);
        // Check if the resulting micros are within representable bounds
                return __PRIVATE_isMicrosInBounds(t) ? __PRIVATE_EvaluateResult.newValue({
            integerValue: `${t.toString()}`
        }) : __PRIVATE_EvaluateResult.dr();
    }
}

class __PRIVATE_CoreTimestampToUnixMillis extends __PRIVATE_TimestampToUnix {
    Mr(e) {
        const t = __PRIVATE_timestampToMicros(e), n = t / BigInt(1e3), r = t % BigInt(1e3);
        // Perform division, truncating towards zero (default JS BigInt division)
                return n > BigInt(0) || r === BigInt(0) ? __PRIVATE_EvaluateResult.newValue({
            integerValue: n.toString()
        }) : __PRIVATE_EvaluateResult.newValue({
            integerValue: (n - BigInt(1)).toString()
        });
    }
}

class __PRIVATE_CoreTimestampToUnixSeconds extends __PRIVATE_TimestampToUnix {
    Mr(e) {
        // Seconds are directly available
        const t = BigInt(e.seconds);
        // Check if the resulting seconds are within representable bounds
                return __PRIVATE_isSecondsInBounds(t) ? __PRIVATE_EvaluateResult.newValue({
            integerValue: t.toString()
        }) : __PRIVATE_EvaluateResult.dr();
    }
}

class __PRIVATE_TimestampArithmetic {
    constructor(e) {
        this.expr = e;
    }
    evaluate(e, t) {
        __PRIVATE_hardAssert(3 === this.expr.params.length, 2775, `${this.expr.name}() function should have exactly 3 parameters`);
        let n = false;
        const r = __PRIVATE_toEvaluable(this.expr.params[0]).evaluate(e, t);
        switch (r.type) {
          case "TIMESTAMP":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        const i = __PRIVATE_toEvaluable(this.expr.params[1]).evaluate(e, t);
        let s;
        switch (i.type) {
          case "STRING":
            if (s = function __PRIVATE_asTimeUnit(e) {
                switch (e) {
                  case "microsecond":
                    return "microsecond";

                  case "millisecond":
                    return "millisecond";

                  case "second":
                    return "second";

                  case "minute":
                    return "minute";

                  case "hour":
                    return "hour";

                  case "day":
                    return "day";

                  default:
                    return;
                }
            }(i.value.stringValue), void 0 === s) return __PRIVATE_EvaluateResult.dr();
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        const _ = __PRIVATE_toEvaluable(this.expr.params[2]).evaluate(e, t);
        switch (_.type) {
          case "INT":
            break;

          case "NULL":
            n = true;
            break;

          default:
            return __PRIVATE_EvaluateResult.dr();
        }
        if (n) return __PRIVATE_EvaluateResult.pr();
        const o = BigInt(_.value.integerValue);
        let a;
        try {
            switch (s) {
              case "microsecond":
                a = o;
                break;

              case "millisecond":
                a = o * BigInt(1e3);
                break;

              case "second":
                a = o * BigInt(1e6);
                break;

              case "minute":
                a = o * BigInt(6e7);
                break;

              case "hour":
                a = o * BigInt(36e8);
                break;

              case "day":
                a = o * BigInt(864e8);
                break;

              default:
                return __PRIVATE_EvaluateResult.dr();
            }
            // Check for potential overflow during multiplication
                        if ("microsecond" !== s && o !== BigInt(0) && a / o !== BigInt(this.Nr(s))) return __PRIVATE_EvaluateResult.dr();
        } catch (e) {
            // Catch potential BigInt errors (though unlikely with isInteger check)
            return __PRIVATE_logWarn(`Error during timestamp arithmetic: ${e}`), __PRIVATE_EvaluateResult.dr();
        }
        const u = fromTimestamp(r.value.timestampValue);
        // Check initial timestamp bounds
                if (!__PRIVATE_isTimestampInBounds(u.seconds, u.nanoseconds)) return __PRIVATE_EvaluateResult.dr();
        const c = __PRIVATE_timestampToMicros(u), l = this.Lr(c, a);
        // Check final microsecond bounds
        if (!__PRIVATE_isMicrosInBounds(l)) return __PRIVATE_EvaluateResult.dr();
        // Convert back to seconds and nanos
                const E = Number(l / Bt), h = l % Bt, T = Number((h < 0 ? h + Bt : h) * BigInt(1e3)), P = h < 0 ? E - 1 : E;
        // Final check on calculated timestamp bounds
        return __PRIVATE_isTimestampInBounds(P, T) ? __PRIVATE_EvaluateResult.newValue({
            timestampValue: {
                seconds: P,
                nanos: T
            }
        }) : __PRIVATE_EvaluateResult.dr();
    }
    Nr(e) {
        switch (e) {
          case "millisecond":
            return 1e3;

          case "second":
            return 1e6;

          case "minute":
            return 6e7;

          case "hour":
            return 36e8;

          case "day":
            return 864e8;

          default:
            return 1;
 // microsecond
                }
    }
}

class __PRIVATE_CoreTimestampAdd extends __PRIVATE_TimestampArithmetic {
    Lr(e, t) {
        return e + t;
    }
}

class __PRIVATE_CoreTimestampSub extends __PRIVATE_TimestampArithmetic {
    Lr(e, t) {
        return e - t;
    }
}

// Copyright 2024 Google LLC* @license
// Copyright 2024 Google LLC

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//      http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
class CorePipeline {
    constructor(e, t, n) {
        this.serializer = e, this.stages = t, this.listenOptions = n, this.isCorePipeline = true;
    }
    getPipelineCollection() {
        return getPipelineCollection(this);
    }
    getPipelineCollectionGroup() {
        return getPipelineCollectionGroup(this);
    }
    getPipelineCollectionId() {
        return getPipelineCollectionId(this);
    }
    getPipelineDocuments() {
        return getPipelineDocuments(this);
    }
    getPipelineFlavor() {
        return function getPipelineFlavor(e) {
            let t = "exact";
            return e.stages.forEach(((n, r) => {
                n._name !== M.name && n._name !== V.name || (t = "keyless"), n._name === y.name && "exact" === t && (t = "augmented"), 
                // TODO(pipeline): verify the last stage is addFields, and it is added by the SDK.
                n._name === w.name && r < e.stages.length - 1 && "exact" === t && (t = "augmented");
            })), t;
        }
        /**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
        /* eslint @typescript-eslint/no-explicit-any: 0 */ (this);
    }
    getPipelineSourceType() {
        return getPipelineSourceType(this);
    }
}

function getPipelineSourceType(e) {
    const t = e.stages[0];
    return t instanceof H || t instanceof J || t instanceof Q || t instanceof Y ? t._name : "unknown";
}

function getPipelineCollection(e) {
    if ("collection" === getPipelineSourceType(e)) return e.stages[0].Er;
}

function getPipelineCollectionGroup(e) {
    if ("collection_group" === getPipelineSourceType(e)) return e.stages[0].collectionId;
}

function getPipelineCollectionId(e) {
    switch (getPipelineSourceType(e)) {
      case "collection":
        return ResourcePath.fromString(getPipelineCollection(e)).lastSegment();

      case "collection_group":
        return getPipelineCollectionGroup(e);

      default:
        return;
    }
}

function getPipelineDocuments(e) {
    if ("documents" === getPipelineSourceType(e)) return e.stages[0].hr;
}

function __PRIVATE_toPipelineBooleanExpr(t) {
    if (t instanceof FieldFilter) {
        const n = e(t.field.toString()), r = t.value;
        // Comparison filters
                switch (t.op) {
          case "<" /* Operator.LESS_THAN */ :
            return and(n.exists(), n.lessThan(Constant._fromProto(r)));

          case "<=" /* Operator.LESS_THAN_OR_EQUAL */ :
            return and(n.exists(), n.lessThanOrEqual(Constant._fromProto(r)));

          case ">" /* Operator.GREATER_THAN */ :
            return and(n.exists(), n.greaterThan(Constant._fromProto(r)));

          case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ :
            return and(n.exists(), n.greaterThanOrEqual(Constant._fromProto(r)));

          case "==" /* Operator.EQUAL */ :
            return and(n.exists(), n.equal(Constant._fromProto(r)));

          case "!=" /* Operator.NOT_EQUAL */ :
            return n.notEqual(Constant._fromProto(r));

          case "array-contains" /* Operator.ARRAY_CONTAINS */ :
            return and(n.exists(), n.arrayContains(Constant._fromProto(r)));

          case "in" /* Operator.IN */ :
            {
                const e = r?.arrayValue?.values?.map((e => Constant._fromProto(e)));
                return e ? 1 === e.length ? and(n.exists(), n.equal(e[0])) : and(n.exists(), n.equalAny(e)) : and(n.exists(), n.equalAny([]));
            }

          case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
            {
                const e = r?.arrayValue?.values?.map((e => Constant._fromProto(e)));
                return and(n.exists(), n.arrayContainsAny(e));
            }

          case "not-in" /* Operator.NOT_IN */ :
            {
                const e = r?.arrayValue?.values?.map((e => Constant._fromProto(e)));
                return e ? 1 === e.length ? n.notEqual(e[0]) : n.notEqualAny(e) : n.notEqualAny([]);
            }

          default:
            l(36935);
        }
    } else if (t instanceof CompositeFilter) switch (t.op) {
      case "and" /* CompositeOperator.AND */ :
        {
            const e = t.getFilters().map((e => __PRIVATE_toPipelineBooleanExpr(e)));
            return and(e[0], e[1], ...e.slice(2));
        }

      case "or" /* CompositeOperator.OR */ :
        {
            const e = t.getFilters().map((e => __PRIVATE_toPipelineBooleanExpr(e)));
            return or(e[0], e[1], ...e.slice(2));
        }

      default:
        l(35306);
    }
    throw new Error(`Failed to convert filter to pipeline conditions: ${t}`);
}

function Z(t, n) {
    let r;
    r = __PRIVATE_isCollectionGroupQuery(t) ? n.pipeline().collectionGroup(t.collectionGroup) : __PRIVATE_isDocumentQuery$1(t) ? n.pipeline().documents([ doc(n, t.path.canonicalString()) ]) : n.pipeline().collection(t.path.canonicalString());
    // filters
        for (const e of t.filters) r = r.where(__PRIVATE_toPipelineBooleanExpr(e));
    // orders
        const i = __PRIVATE_queryNormalizedOrderBy(t), s = i.map((t => e(t.field.canonicalString()).exists()));
    r = s.length > 1 ? r.where(and(s[0], s[1], ...s.slice(2))) : r.where(s[0]);
    const _ = i.map((t => "asc" /* Direction.ASCENDING */ === t.dir ? e(t.field.canonicalString()).ascending() : e(t.field.canonicalString()).descending()));
    if (_.length > 0) if ("L" /* LimitType.Last */ === t.limitType) {
        const e = function __PRIVATE_reverseOrderings(e) {
            return e.map((e => new Ordering(e.expr, "ascending" === e.direction ? "descending" : "ascending", void 0)));
        }(_);
        r = r.sort(e[0], ...e.slice(1)), 
        // cursors
        null !== t.startAt && (r = r.where(__PRIVATE_whereConditionsFromCursor(t.startAt, _, "after"))), 
        null !== t.endAt && (r = r.where(__PRIVATE_whereConditionsFromCursor(t.endAt, _, "before"))), 
        r = r.limit(t.limit), r = r.sort(_[0], ..._.slice(1));
    } else r = r.sort(_[0], ..._.slice(1)), null !== t.startAt && (r = r.where(__PRIVATE_whereConditionsFromCursor(t.startAt, _, "after"))), 
    null !== t.endAt && (r = r.where(__PRIVATE_whereConditionsFromCursor(t.endAt, _, "before"))), 
    null !== t.limit && (r = r.limit(t.limit));
    return r.stages;
}

function __PRIVATE_whereConditionsFromCursor(e, t, n) {
    // The filterFunc is either greater than or less than
    const r = "before" === n ? lessThan : greaterThan, i = e.position.map((e => Constant._fromProto(e))), s = i.length;
    let _ = t[s - 1].expr, o = i[s - 1], a = r(_, o);
    e.inclusive && (
    // When the cursor bound is inclusive, then the last bound
    // can be equal to the value, otherwise it's not equal
    a = or(a, _.equal(o)));
    // Iterate backwards over the remaining bounds, adding
    // a condition for each one
        for (let e = s - 2; e >= 0; e--) _ = t[e].expr, o = i[e], 
    // For each field in the orderings, the condition is either
    // a) lt|gt the cursor value,
    // b) or equal the cursor value and lt|gt the cursor values for other fields
    a = or(r(_, o), and(_.equal(o), a));
    return a;
}

function __PRIVATE_canonifyExpr(e) {
    if ((e = __PRIVATE_unwrapExpression(e)) instanceof o) return `fld(${e.fieldName})`;
    if (e instanceof Constant) return `cst(${function __PRIVATE_canonifyConstantValue(e) {
        return null === e ? "null" : "number" == typeof e ? e.toString() : "string" == typeof e ? `"${e}"` : e instanceof X ? `ref(${e.path})` : e instanceof n ? `vec(${JSON.stringify(e)})` : JSON.stringify(e);
    }(e.value)})`;
    if (e instanceof x) return `fn(${e.name},[${e.params.map(__PRIVATE_canonifyExpr).join(",")}])`;
    if ("ListOfExpressions" === e.expressionType) return `list([${e.ur.map(__PRIVATE_canonifyExpr).join(",")}])`;
    throw new Error(`Unrecognized expr ${JSON.stringify(e, null, 2)}`);
}

function __PRIVATE_canonifyStage(e) {
    if (e instanceof w) return `${e._name}(${__PRIVATE_canonifyExprMap(e.fields)})`;
    if (e instanceof V) {
        let t = `${e._name}(${__PRIVATE_canonifyExprMap(e.accumulators)})`;
        return e.groups.size > 0 && (t += `grouping(${__PRIVATE_canonifyExprMap(e.groups)})`), 
        t;
    }
    if (e instanceof M) return `${e._name}(${__PRIVATE_canonifyExprMap(e.groups)})`;
    if (e instanceof H) return `${e._name}(${e.Er})`;
    if (e instanceof J) return `${e._name}(${e.collectionId})`;
    if (e instanceof Q) return `${e._name}()`;
    if (e instanceof Y) return `${e._name}(${e.hr.sort()})`;
    if (e instanceof A) return `${e._name}(${__PRIVATE_canonifyExpr(e.condition)})`;
    if (e instanceof v) return `${e._name}(${e.limit})`;
    if (e instanceof L) return `${e._name}(${function __PRIVATE_canonifySortOrderings(e) {
        return e.map((e => `${__PRIVATE_canonifyExpr(e.expr)}${e.direction}`)).join(",");
    }(e.orderings)})`;
    throw new Error(`Unrecognized stage ${e._name}`);
}

function __PRIVATE_canonifyExprMap(e) {
    return `${Array.from(e.entries()).sort().map((([e, t]) => `${e}=${__PRIVATE_canonifyExpr(t)}`)).join(",")}`;
}

function __PRIVATE_canonifyPipeline(e) {
    return e.stages.map((e => __PRIVATE_canonifyStage(e))).join("|");
}

// TODO(pipeline): do a proper implementation for eq.
function __PRIVATE_pipelineEq(e, t) {
    return __PRIVATE_canonifyPipeline(e) === __PRIVATE_canonifyPipeline(t);
}

function __PRIVATE_isPipeline(e) {
    return e instanceof CorePipeline;
}

function __PRIVATE_stringifyQueryOrPipeline(e) {
    return __PRIVATE_isPipeline(e) ? __PRIVATE_canonifyPipeline(e) : __PRIVATE_stringifyQuery(e);
}

function __PRIVATE_canonifyQueryOrPipeline(e) {
    return __PRIVATE_isPipeline(e) ? __PRIVATE_canonifyPipeline(e) : function __PRIVATE_canonifyQuery(e) {
        return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`;
    }(e);
}

function __PRIVATE_queryOrPipelineEqual(e, t) {
    return e instanceof CorePipeline && t instanceof CorePipeline ? __PRIVATE_pipelineEq(e, t) : !(e instanceof CorePipeline && !(t instanceof CorePipeline) || !(e instanceof CorePipeline) && t instanceof CorePipeline) && __PRIVATE_queryEquals(e, t);
}

function __PRIVATE_canonifyTargetOrPipeline(e) {
    return __PRIVATE_targetIsPipelineTarget(e) ? __PRIVATE_canonifyPipeline(e) : __PRIVATE_canonifyTarget(e);
}

function __PRIVATE_targetOrPipelineEqual(e, t) {
    return e instanceof CorePipeline && t instanceof CorePipeline ? __PRIVATE_pipelineEq(e, t) : !(e instanceof CorePipeline && !(t instanceof CorePipeline) || !(e instanceof CorePipeline) && t instanceof CorePipeline) && __PRIVATE_targetEquals(e, t);
}

// function addSystemFields(
//   fields: Map<string, Expression>
// ): Map<string, Expression> {
//   const newFields = new Map<string, Expression>(fields);
//   newFields.set(DOCUMENT_KEY_NAME, field(DOCUMENT_KEY_NAME));
//   newFields.set(CREATE_TIME_NAME, field(CREATE_TIME_NAME));
//   newFields.set(UPDATE_TIME_NAME, field(UPDATE_TIME_NAME));
//   return newFields;
// }
function __PRIVATE_toCorePipeline(t, n) {
    const r = function __PRIVATE_rewriteStages(t) {
        let n = false;
        const r = [];
        for (const i of t) 
        // For stages that provide ordering semantics
        if (i instanceof L) 
        // Ensure we have a stable ordering
        if (n = true, i.orderings.some((e => e.expr instanceof o && e.expr.fieldName === Ce))) r.push(i); else {
            const t = i.orderings.map((e => e));
            t.push(e(Ce).ascending()), r.push(new L(t, {}));
        } else i instanceof v ? (n || (r.push(new L([ e(Ce).ascending() ], {})), n = true), 
        r.push(i)) : r.push(i);
        return n || r.push(new L([ e(Ce).ascending() ], {})), r;
    }(t.stages);
    if (t.userDataReader) {
        const e = t.userDataReader.createContext(3 /* UserDataSource.Argument */ , "toCorePipeline");
        r.forEach((t => t._readUserData(e)));
    }
    return new CorePipeline(t.userDataReader.serializer, r, n);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A batch of mutations that will be sent as one unit to the backend.
 */ class MutationBatch {
    /**
     * @param batchId - The unique ID of this mutation batch.
     * @param localWriteTime - The original write time of this mutation.
     * @param baseMutations - Mutations that are used to populate the base
     * values when this mutation is applied locally. This can be used to locally
     * overwrite values that are persisted in the remote document cache. Base
     * mutations are never sent to the backend.
     * @param mutations - The user-provided mutations in this mutation batch.
     * User-provided mutations are applied both locally and remotely on the
     * backend.
     */
    constructor(e, t, n, r) {
        this.batchId = e, this.localWriteTime = t, this.baseMutations = n, this.mutations = r;
    }
    /**
     * Applies all the mutations in this MutationBatch to the specified document
     * to compute the state of the remote document
     *
     * @param document - The document to apply mutations to.
     * @param batchResult - The result of applying the MutationBatch to the
     * backend.
     */    applyToRemoteDocument(e, t) {
        const n = t.mutationResults;
        for (let t = 0; t < this.mutations.length; t++) {
            const r = this.mutations[t];
            if (r.key.isEqual(e.key)) {
                __PRIVATE_mutationApplyToRemoteDocument(r, e, n[t]);
            }
        }
    }
    /**
     * Computes the local view of a document given all the mutations in this
     * batch.
     *
     * @param document - The document to apply mutations to.
     * @param mutatedFields - Fields that have been updated before applying this mutation batch.
     * @returns A `FieldMask` representing all the fields that are mutated.
     */    applyToLocalView(e, t) {
        // First, apply the base state. This allows us to apply non-idempotent
        // transform against a consistent set of values.
        for (const n of this.baseMutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));
        // Second, apply all user-provided mutations.
                for (const n of this.mutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime));
        return t;
    }
    /**
     * Computes the local view for all provided documents given the mutations in
     * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to
     * replace all the mutation applications.
     */    applyToLocalDocumentSet(e, t) {
        // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations
        // directly (as done in `applyToLocalView()`), we can reduce the complexity
        // to O(n).
        const n = __PRIVATE_newMutationMap();
        return this.mutations.forEach((r => {
            const i = e.get(r.key), s = i.overlayedDocument;
            // TODO(mutabledocuments): This method should take a MutableDocumentMap
            // and we should remove this cast.
                        let _ = this.applyToLocalView(s, i.mutatedFields);
            // Set mutatedFields to null if the document is only from local mutations.
            // This creates a Set or Delete mutation, instead of trying to create a
            // patch mutation as the overlay.
                        _ = t.has(r.key) ? null : _;
            const o = __PRIVATE_calculateOverlayMutation(s, _);
            null !== o && n.set(r.key, o), s.isValidDocument() || s.convertToNoDocument(SnapshotVersion.min());
        })), n;
    }
    keys() {
        return this.mutations.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet());
    }
    isEqual(e) {
        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)));
    }
}

/** The result of applying a mutation batch to the backend. */ class MutationBatchResult {
    constructor(e, t, n, 
    /**
     * A pre-computed mapping from each mutated document to the resulting
     * version.
     */
    r) {
        this.batch = e, this.commitVersion = t, this.mutationResults = n, this.docVersions = r;
    }
    /**
     * Creates a new MutationBatchResult for the given batch and results. There
     * must be one result for each mutation in the batch. This static factory
     * caches a document=&gt;version mapping (docVersions).
     */    static from(e, t, n) {
        __PRIVATE_hardAssert(e.mutations.length === n.length, 58842, {
            Br: e.mutations.length,
            Ur: n.length
        });
        let r = function __PRIVATE_documentVersionMap() {
            return it;
        }();
        const i = e.mutations;
        for (let e = 0; e < i.length; e++) r = r.insert(i[e].key, n[e].version);
        return new MutationBatchResult(e, t, n, r);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const Kt = "";

/**
 * Encodes a resource path into a IndexedDb-compatible string form.
 */
function __PRIVATE_encodeResourcePath(e) {
    let t = "";
    for (let n = 0; n < e.length; n++) t.length > 0 && (t = __PRIVATE_encodeSeparator(t)), 
    t = __PRIVATE_encodeSegment(e.get(n), t);
    return __PRIVATE_encodeSeparator(t);
}

/** Encodes a single segment of a resource path into the given result */ function __PRIVATE_encodeSegment(e, t) {
    let n = t;
    const r = e.length;
    for (let t = 0; t < r; t++) {
        const r = e.charAt(t);
        switch (r) {
          case "\0":
            n += "";
            break;

          case Kt:
            n += "";
            break;

          default:
            n += r;
        }
    }
    return n;
}

/** Encodes a path separator into the given result */ function __PRIVATE_encodeSeparator(e) {
    return e + Kt + "";
}

/**
 * Decodes the given IndexedDb-compatible string form of a resource path into
 * a ResourcePath instance. Note that this method is not suitable for use with
 * decoding resource names from the server; those are One Platform format
 * strings.
 */ function __PRIVATE_decodeResourcePath(e) {
    // Event the empty path must encode as a path of at least length 2. A path
    // with exactly 2 must be the empty path.
    const t = e.length;
    if (__PRIVATE_hardAssert(t >= 2, 64408, {
        path: e
    }), 2 === t) return __PRIVATE_hardAssert(e.charAt(0) === Kt && "" === e.charAt(1), 56145, {
        path: e
    }), ResourcePath.emptyPath();
    // Escape characters cannot exist past the second-to-last position in the
    // source value.
        const __PRIVATE_lastReasonableEscapeIndex = t - 2, n = [];
    let r = "";
    for (let i = 0; i < t; ) {
        // The last two characters of a valid encoded path must be a separator, so
        // there must be an end to this segment.
        const t = e.indexOf(Kt, i);
        (t < 0 || t > __PRIVATE_lastReasonableEscapeIndex) && l(50515, {
            path: e
        });
        switch (e.charAt(t + 1)) {
          case "":
            const s = e.substring(i, t);
            let _;
            0 === r.length ? 
            // Avoid copying for the common case of a segment that excludes \0
            // and \001
            _ = s : (r += s, _ = r, r = ""), n.push(_);
            break;

          case "":
            r += e.substring(i, t), r += "\0";
            break;

          case "":
            // The escape character can be used in the output to encode itself.
            r += e.substring(i, t + 1);
            break;

          default:
            l(61167, {
                path: e
            });
        }
        i = t + 2;
    }
    return new ResourcePath(n);
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const Wt = "remoteDocuments", Qt = "owner", Gt = "owner", zt = "mutationQueues", jt = "userId", Ht = "mutations", Jt = "batchId", Yt = "userMutationsIndex", Zt = [ "userId", "batchId" ];

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Name of the IndexedDb object store.
 *
 * Note that the name 'owner' is chosen to ensure backwards compatibility with
 * older clients that only supported single locked access to the persistence
 * layer.
 */
/**
 * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
 * index to iterate over all at document mutations for a given path or lower.
 */
function __PRIVATE_newDbDocumentMutationPrefixForPath(e, t) {
    return [ e, __PRIVATE_encodeResourcePath(t) ];
}

/**
 * Creates a full index key of [userId, encodedPath, batchId] for inserting
 * and deleting into the DbDocumentMutations index.
 */ function __PRIVATE_newDbDocumentMutationKey(e, t, n) {
    return [ e, __PRIVATE_encodeResourcePath(t), n ];
}

/**
 * Because we store all the useful information for this store in the key,
 * there is no useful information to store as the value. The raw (unencoded)
 * path cannot be stored because IndexedDb doesn't store prototype
 * information.
 */ const Xt = {}, en = "documentMutations", tn = "remoteDocumentsV14", nn = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], rn = "documentKeyIndex", sn = [ "prefixPath", "collectionGroup", "documentId" ], _n = "collectionGroupIndex", on = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], an = "remoteDocumentGlobal", un = "remoteDocumentGlobalKey", cn = "targets", En = "queryTargetsIndex", hn = [ "canonicalId", "targetId" ], Tn = "targetDocuments", Pn = [ "targetId", "path" ], Rn = "documentTargetsIndex", In = [ "path", "targetId" ], An = "targetGlobalKey", Vn = "targetGlobal", dn = "collectionParents", fn = [ "collectionId", "parent" ], mn = "clientMetadata", pn = "clientId", gn = "bundles", yn = "bundleId", wn = "namedQueries", bn = "name", vn = "indexConfiguration", Sn = "indexId", Dn = "collectionGroupIndex", xn = "collectionGroup", Cn = "indexState", Fn = [ "indexId", "uid" ], On = "sequenceNumberIndex", Mn = [ "uid", "sequenceNumber" ], Nn = "indexEntries", Ln = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], Bn = "documentKeyIndex", Un = [ "indexId", "uid", "orderedDocumentKey" ], kn = "documentOverlays", qn = [ "userId", "collectionPath", "documentId" ], $n = "collectionPathOverlayIndex", Kn = [ "userId", "collectionPath", "largestBatchId" ], Wn = "collectionGroupOverlayIndex", Qn = [ "userId", "collectionGroup", "largestBatchId" ], Gn = "globals", zn = "name", jn = [ ...[ ...[ ...[ ...[ zt, Ht, en, Wt, cn, Qt, Vn, Tn ], mn ], an ], dn ], gn, wn ], Hn = [ ...jn, kn ], Jn = [ zt, Ht, en, tn, cn, Qt, Vn, Tn, mn, an, dn, gn, wn, kn ], Yn = Jn, Zn = [ ...Yn, vn, Cn, Nn ], Xn = Zn, er = [ ...Zn, Gn ], tr = er;

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Delete a mutation batch and the associated document mutations.
 * @returns A PersistencePromise of the document mutations that were removed.
 */
function removeMutationBatch(e, t, n) {
    const r = e.store(Ht), i = e.store(en), s = [], _ = IDBKeyRange.only(n.batchId);
    let o = 0;
    const a = r.jn({
        range: _
    }, ((e, t, n) => (o++, n.delete())));
    s.push(a.next((() => {
        __PRIVATE_hardAssert(1 === o, 47070, {
            batchId: n.batchId
        });
    })));
    const u = [];
    for (const e of n.mutations) {
        const r = __PRIVATE_newDbDocumentMutationKey(t, e.key.path, n.batchId);
        s.push(i.delete(r)), u.push(e.key);
    }
    return PersistencePromise.waitFor(s).next((() => u));
}

/**
 * Returns an approximate size for the given document.
 */ function __PRIVATE_dbDocumentSize(e) {
    if (!e) return 0;
    let t;
    if (e.document) t = e.document; else if (e.unknownDocument) t = e.unknownDocument; else {
        if (!e.noDocument) throw l(14731);
        t = e.noDocument;
    }
    return JSON.stringify(t).length;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_IndexedDbTransaction extends PersistenceTransaction {
    constructor(e, t) {
        super(), this.kr = e, this.currentSequenceNumber = t;
    }
}

function __PRIVATE_getStore(e, t) {
    const n = __PRIVATE_debugCast(e);
    return __PRIVATE_SimpleDb.xn(n.kr, t);
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Representation of an overlay computed by Firestore.
 *
 * Holds information about a mutation and the largest batch id in Firestore when
 * the mutation was created.
 */ class Overlay {
    constructor(e, t) {
        this.largestBatchId = e, this.mutation = t;
    }
    getKey() {
        return this.mutation.key;
    }
    isEqual(e) {
        return null !== e && this.mutation === e.mutation;
    }
    toString() {
        return `Overlay{\n      largestBatchId: ${this.largestBatchId},\n      mutation: ${this.mutation.toString()}\n    }`;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An immutable set of metadata that the local store tracks for each target.
 */ class TargetData {
    constructor(
    /** The target being listened to. */
    e, 
    /**
     * The target ID to which the target corresponds; Assigned by the
     * LocalStore for user listens and by the SyncEngine for limbo watches.
     */
    t, 
    /** The purpose of the target. */
    n, 
    /**
     * The sequence number of the last transaction during which this target data
     * was modified.
     */
    r, 
    /** The latest snapshot version seen for this target. */
    i = SnapshotVersion.min()
    /**
     * The maximum snapshot version at which the associated view
     * contained no limbo documents.
     */ , s = SnapshotVersion.min()
    /**
     * An opaque, server-assigned token that allows watching a target to be
     * resumed after disconnecting without retransmitting all the data that
     * matches the target. The resume token essentially identifies a point in
     * time from which the server should resume sending results.
     */ , _ = ByteString.EMPTY_BYTE_STRING
    /**
     * The number of documents that last matched the query at the resume token or
     * read time. Documents are counted only when making a listen request with
     * resume token or read time, otherwise, keep it null.
     */ , o = null) {
        this.target = e, this.targetId = t, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i, 
        this.lastLimboFreeSnapshotVersion = s, this.resumeToken = _, this.expectedCount = o;
    }
    /** Creates a new target data instance with an updated sequence number. */    withSequenceNumber(e) {
        return new TargetData(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount);
    }
    /**
     * Creates a new target data instance with an updated resume token and
     * snapshot version.
     */    withResumeToken(e, t) {
        return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, t, this.lastLimboFreeSnapshotVersion, e, 
        /* expectedCount= */ null);
    }
    /**
     * Creates a new target data instance with an updated expected count.
     */    withExpectedCount(e) {
        return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e);
    }
    /**
     * Creates a new target data instance with an updated last limbo free
     * snapshot version number.
     */    withLastLimboFreeSnapshotVersion(e) {
        return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Serializer for values stored in the LocalStore. */ class __PRIVATE_LocalSerializer {
    constructor(e) {
        this.qr = e;
    }
}

/** Decodes a remote document from storage locally to a Document. */ function __PRIVATE_fromDbRemoteDocument(e, t) {
    let n;
    if (t.document) n = fromDocument(e.qr, t.document, !!t.hasCommittedMutations); else if (t.noDocument) {
        const e = DocumentKey.fromSegments(t.noDocument.path), r = __PRIVATE_fromDbTimestamp(t.noDocument.readTime);
        n = MutableDocument.newNoDocument(e, r), t.hasCommittedMutations && n.setHasCommittedMutations();
    } else {
        if (!t.unknownDocument) return l(56709);
        {
            const e = DocumentKey.fromSegments(t.unknownDocument.path), r = __PRIVATE_fromDbTimestamp(t.unknownDocument.version);
            n = MutableDocument.newUnknownDocument(e, r);
        }
    }
    return t.readTime && n.setReadTime(function __PRIVATE_fromDbTimestampKey(e) {
        const t = new Timestamp(e[0], e[1]);
        return SnapshotVersion.fromTimestamp(t);
    }(t.readTime)), n;
}

/** Encodes a document for storage locally. */ function __PRIVATE_toDbRemoteDocument(e, t) {
    const n = t.key, r = {
        prefixPath: n.getCollectionPath().popLast().toArray(),
        collectionGroup: n.collectionGroup,
        documentId: n.path.lastSegment(),
        readTime: __PRIVATE_toDbTimestampKey(t.readTime),
        hasCommittedMutations: t.hasCommittedMutations
    };
    if (t.isFoundDocument()) r.document = function __PRIVATE_toDocument(e, t) {
        return {
            name: __PRIVATE_toName(e, t.key),
            fields: t.data.value.mapValue.fields,
            updateTime: toTimestamp(e, t.version.toTimestamp()),
            createTime: toTimestamp(e, t.createTime.toTimestamp())
        };
    }(e.qr, t); else if (t.isNoDocument()) r.noDocument = {
        path: n.path.toArray(),
        readTime: __PRIVATE_toDbTimestamp(t.version)
    }; else {
        if (!t.isUnknownDocument()) return l(57904, {
            document: t
        });
        r.unknownDocument = {
            path: n.path.toArray(),
            version: __PRIVATE_toDbTimestamp(t.version)
        };
    }
    return r;
}

function __PRIVATE_toDbTimestampKey(e) {
    const t = e.toTimestamp();
    return [ t.seconds, t.nanoseconds ];
}

function __PRIVATE_toDbTimestamp(e) {
    const t = e.toTimestamp();
    return {
        seconds: t.seconds,
        nanoseconds: t.nanoseconds
    };
}

function __PRIVATE_fromDbTimestamp(e) {
    const t = new Timestamp(e.seconds, e.nanoseconds);
    return SnapshotVersion.fromTimestamp(t);
}

/** Encodes a batch of mutations into a DbMutationBatch for local storage. */
/** Decodes a DbMutationBatch into a MutationBatch */
function __PRIVATE_fromDbMutationBatch(e, t) {
    const n = (t.baseMutations || []).map((t => __PRIVATE_fromMutation(e.qr, t)));
    // Squash old transform mutations into existing patch or set mutations.
    // The replacement of representing `transforms` with `update_transforms`
    // on the SDK means that old `transform` mutations stored in IndexedDB need
    // to be updated to `update_transforms`.
    // TODO(b/174608374): Remove this code once we perform a schema migration.
        for (let e = 0; e < t.mutations.length - 1; ++e) {
        const n = t.mutations[e];
        if (e + 1 < t.mutations.length && void 0 !== t.mutations[e + 1].transform) {
            const r = t.mutations[e + 1];
            n.updateTransforms = r.transform.fieldTransforms, t.mutations.splice(e + 1, 1), 
            ++e;
        }
    }
    const r = t.mutations.map((t => __PRIVATE_fromMutation(e.qr, t))), i = Timestamp.fromMillis(t.localWriteTimeMs);
    return new MutationBatch(t.batchId, i, n, r);
}

/** Decodes a DbTarget into TargetData */ function __PRIVATE_fromDbTarget(e, t) {
    const n = __PRIVATE_fromDbTimestamp(t.readTime), r = void 0 !== t.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(t.lastLimboFreeSnapshotVersion) : SnapshotVersion.min();
    let i;
    return i = function __PRIVATE_isPipelineQueryTarget(e) {
        return void 0 !== e.structuredPipeline;
    }
    /**
 * A helper function for figuring out what kind of query has been stored.
 */ (t.query) ? function __PRIVATE_fromPipelineTarget(e, t) {
        const n = e.structuredPipeline;
        __PRIVATE_hardAssert((n?.pipeline?.stages ?? []).length > 0, 1845);
        const r = n?.pipeline?.stages.map(__PRIVATE_stageFromProto);
        return new CorePipeline(t, r);
    }(t.query, e.qr) : function __PRIVATE_isDocumentQuery(e) {
        return void 0 !== e.documents;
    }
    /** Encodes a DbBundle to a BundleMetadata object. */ (t.query) ? function __PRIVATE_fromDocumentsTarget(e) {
        const t = e.documents.length;
        return __PRIVATE_hardAssert(1 === t, 1966, {
            count: t
        }), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0])));
    }(t.query) : function __PRIVATE_fromQueryTarget(e) {
        return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e));
    }(t.query), new TargetData(i, t.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, n, r, ByteString.fromBase64String(t.resumeToken));
}

/** Encodes TargetData into a DbTarget for storage locally. */ function __PRIVATE_toDbTarget(e, t) {
    const n = __PRIVATE_toDbTimestamp(t.snapshotVersion), r = __PRIVATE_toDbTimestamp(t.lastLimboFreeSnapshotVersion);
    let i;
    i = __PRIVATE_targetIsPipelineTarget(t.target) ? __PRIVATE_toPipelineTarget(e.qr, t.target) : __PRIVATE_targetIsDocumentTarget(t.target) ? __PRIVATE_toDocumentsTarget(e.qr, t.target) : __PRIVATE_toQueryTarget(e.qr, t.target).be;
    // We can't store the resumeToken as a ByteString in IndexedDb, so we
    // convert it to a base64 string for storage.
        const s = t.resumeToken.toBase64();
    // lastListenSequenceNumber is always 0 until we do real GC.
        return {
        targetId: t.targetId,
        canonicalId: __PRIVATE_canonifyTargetOrPipeline(t.target),
        readTime: n,
        resumeToken: s,
        lastListenSequenceNumber: t.sequenceNumber,
        lastLimboFreeSnapshotVersion: r,
        query: i
    };
}

/**
 * Encodes a `BundledQuery` from bundle proto to a Query object.
 *
 * This reconstructs the original query used to build the bundle being loaded,
 * including features exists only in SDKs (for example: limit-to-last).
 */
function __PRIVATE_fromBundledQuery(e) {
    const t = __PRIVATE_convertQueryTargetToQuery({
        parent: e.parent,
        structuredQuery: e.structuredQuery
    });
    return "LAST" === e.limitType ? __PRIVATE_queryWithLimit(t, t.limit, "L" /* LimitType.Last */) : t;
}

/** Encodes a NamedQuery proto object to a NamedQuery model object. */
/** Encodes a DbDocumentOverlay object to an Overlay model object. */
function __PRIVATE_fromDbDocumentOverlay(e, t) {
    return new Overlay(t.largestBatchId, __PRIVATE_fromMutation(e.qr, t.overlayMutation));
}

/** Decodes an Overlay model object into a DbDocumentOverlay object. */
/**
 * Returns the DbDocumentOverlayKey corresponding to the given user and
 * document key.
 */
function __PRIVATE_toDbDocumentOverlayKey(e, t) {
    const n = t.path.lastSegment();
    return [ e, __PRIVATE_encodeResourcePath(t.path.popLast()), n ];
}

function __PRIVATE_toDbIndexState(e, t, n, r) {
    return {
        indexId: e,
        uid: t,
        sequenceNumber: n,
        readTime: __PRIVATE_toDbTimestamp(r.readTime),
        documentKey: __PRIVATE_encodeResourcePath(r.documentKey.path),
        largestBatchId: r.largestBatchId
    };
}

function __PRIVATE_stageFromProto(e) {
    switch (e.name) {
      case "collection":
        return new H(e.args[0].referenceValue, {});

      case "collection_group":
        return new J(e.args[1].stringValue, {});

      case "database":
        return new Q({});

      case "documents":
        return new Y(e.args.map((e => e.referenceValue)), {});

      case "where":
        return new A(__PRIVATE_exprFromProto(e.args[0]), {});

      case "limit":
        {
            const t = e.args[0].integerValue ?? e.args[0].doubleValue;
            return new v("number" == typeof t ? t : Number(t), {});
        }

      case "sort":
        return new L(e.args.map((e => function __PRIVATE_orderingFromProto(e) {
            const t = e.mapValue?.fields;
            return new Ordering(__PRIVATE_exprFromProto(t.expression), t.direction?.stringValue, "orderingFromProto");
        }
        /**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
        /** A mutation queue for a specific user, backed by IndexedDB. */ (e))), {});

      default:
        throw new Error(`Stage type: ${e.name} not supported.`);
    }
}

function __PRIVATE_exprFromProto(e) {
    return e.fieldReferenceValue ? new o(ta("_exprFromProto", e.fieldReferenceValue), "_exprFromProto") : e.functionValue ? function __PRIVATE_functionFromProto(e) {
        // TODO(pipeline): When aggregation is supported, we need to return AggregateFunction for the functions
        // with aggregate names (sum, count, etc).
        return new x(e.functionValue.name, e.functionValue.args?.map(__PRIVATE_exprFromProto) || []);
    }(e) : Constant._fromProto(e);
}

class __PRIVATE_IndexedDbMutationQueue {
    constructor(
    /**
     * The normalized userId (e.g. null UID => "" userId) used to store /
     * retrieve mutations.
     */
    e, t, n, r) {
        this.userId = e, this.serializer = t, this.indexManager = n, this.referenceDelegate = r, 
        /**
         * Caches the document keys for pending mutation batches. If the mutation
         * has been removed from IndexedDb, the cached value may continue to
         * be used to retrieve the batch's document keys. To remove a cached value
         * locally, `removeCachedMutationKeys()` should be invoked either directly
         * or through `removeMutationBatches()`.
         *
         * With multi-tab, when the primary client acknowledges or rejects a mutation,
         * this cache is used by secondary clients to invalidate the local
         * view of the documents that were previously affected by the mutation.
         */
        // PORTING NOTE: Multi-tab only.
        this.$r = {};
    }
    /**
     * Creates a new mutation queue for the given user.
     * @param user - The user for which to create a mutation queue.
     * @param serializer - The serializer to use when persisting to IndexedDb.
     */    static Kr(e, t, n, r) {
        // TODO(mcg): Figure out what constraints there are on userIDs
        // In particular, are there any reserved characters? are empty ids allowed?
        // For the moment store these together in the same mutations table assuming
        // that empty userIDs aren't allowed.
        __PRIVATE_hardAssert("" !== e.uid, 64387);
        const i = e.isAuthenticated() ? e.uid : "";
        return new __PRIVATE_IndexedDbMutationQueue(i, t, n, r);
    }
    checkEmpty(e) {
        let t = true;
        const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
        return __PRIVATE_mutationsStore(e).jn({
            index: Yt,
            range: n
        }, ((e, n, r) => {
            t = false, r.done();
        })).next((() => t));
    }
    addMutationBatch(e, t, n, r) {
        const i = __PRIVATE_documentMutationsStore(e), s = __PRIVATE_mutationsStore(e);
        // The IndexedDb implementation in Chrome (and Firefox) does not handle
        // compound indices that include auto-generated keys correctly. To ensure
        // that the index entry is added correctly in all browsers, we perform two
        // writes: The first write is used to retrieve the next auto-generated Batch
        // ID, and the second write populates the index and stores the actual
        // mutation batch.
        // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972
        // We write an empty object to obtain key
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return s.add({}).next((_ => {
            __PRIVATE_hardAssert("number" == typeof _, 49019);
            const o = new MutationBatch(_, t, n, r), a = function __PRIVATE_toDbMutationBatch(e, t, n) {
                const r = n.baseMutations.map((t => toMutation(e.qr, t))), i = n.mutations.map((t => toMutation(e.qr, t)));
                return {
                    userId: t,
                    batchId: n.batchId,
                    localWriteTimeMs: n.localWriteTime.toMillis(),
                    baseMutations: r,
                    mutations: i
                };
            }(this.serializer, this.userId, o), u = [];
            let c = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString())));
            for (const e of r) {
                const t = __PRIVATE_newDbDocumentMutationKey(this.userId, e.key.path, _);
                c = c.add(e.key.path.popLast()), u.push(s.put(a)), u.push(i.put(t, Xt));
            }
            return c.forEach((t => {
                u.push(this.indexManager.addToCollectionParentIndex(e, t));
            })), e.addOnCommittedListener((() => {
                this.$r[_] = o.keys();
            })), PersistencePromise.waitFor(u).next((() => o));
        }));
    }
    lookupMutationBatch(e, t) {
        return __PRIVATE_mutationsStore(e).get(t).next((e => e ? (__PRIVATE_hardAssert(e.userId === this.userId, 48, "Unexpected user for mutation batch", {
            userId: e.userId,
            batchId: t
        }), __PRIVATE_fromDbMutationBatch(this.serializer, e)) : null));
    }
    /**
     * Returns the document keys for the mutation batch with the given batchId.
     * For primary clients, this method returns `null` after
     * `removeMutationBatches()` has been called. Secondary clients return a
     * cached result until `removeCachedMutationKeys()` is invoked.
     */
    // PORTING NOTE: Multi-tab only.
    Wr(e, t) {
        return this.$r[t] ? PersistencePromise.resolve(this.$r[t]) : this.lookupMutationBatch(e, t).next((e => {
            if (e) {
                const n = e.keys();
                return this.$r[t] = n, n;
            }
            return null;
        }));
    }
    getNextMutationBatchAfterBatchId(e, t) {
        const n = t + 1, r = IDBKeyRange.lowerBound([ this.userId, n ]);
        let i = null;
        return __PRIVATE_mutationsStore(e).jn({
            index: Yt,
            range: r
        }, ((e, t, r) => {
            t.userId === this.userId && (__PRIVATE_hardAssert(t.batchId >= n, 47524, {
                Qr: n
            }), i = __PRIVATE_fromDbMutationBatch(this.serializer, t)), r.done();
        })).next((() => i));
    }
    getHighestUnacknowledgedBatchId(e) {
        const t = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
        let n = Ke;
        return __PRIVATE_mutationsStore(e).jn({
            index: Yt,
            range: t,
            reverse: true
        }, ((e, t, r) => {
            n = t.batchId, r.done();
        })).next((() => n));
    }
    getAllMutationBatches(e) {
        const t = IDBKeyRange.bound([ this.userId, Ke ], [ this.userId, Number.POSITIVE_INFINITY ]);
        return __PRIVATE_mutationsStore(e).Kn(Yt, t).next((e => e.map((e => __PRIVATE_fromDbMutationBatch(this.serializer, e)))));
    }
    getAllMutationBatchesAffectingDocumentKey(e, t) {
        // Scan the document-mutation index starting with a prefix starting with
        // the given documentKey.
        const n = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), r = IDBKeyRange.lowerBound(n), i = [];
        return __PRIVATE_documentMutationsStore(e).jn({
            range: r
        }, ((n, r, s) => {
            const [_, o, a] = n, u = __PRIVATE_decodeResourcePath(o);
            // Only consider rows matching exactly the specific key of
            // interest. Note that because we order by path first, and we
            // order terminators before path separators, we'll encounter all
            // the index rows for documentKey contiguously. In particular, all
            // the rows for documentKey will occur before any rows for
            // documents nested in a subcollection beneath documentKey so we
            // can stop as soon as we hit any such row.
                        if (_ === this.userId && t.path.isEqual(u)) 
            // Look up the mutation batch in the store.
            return __PRIVATE_mutationsStore(e).get(a).next((e => {
                if (!e) throw l(61480, {
                    Gr: n,
                    batchId: a
                });
                __PRIVATE_hardAssert(e.userId === this.userId, 10503, "Unexpected user for mutation batch", {
                    userId: e.userId,
                    batchId: a
                }), i.push(__PRIVATE_fromDbMutationBatch(this.serializer, e));
            }));
            s.done();
        })).next((() => i));
    }
    getAllMutationBatchesAffectingDocumentKeys(e, t) {
        let n = new SortedSet(__PRIVATE_primitiveComparator);
        const r = [];
        return t.forEach((t => {
            const i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), s = IDBKeyRange.lowerBound(i), _ = __PRIVATE_documentMutationsStore(e).jn({
                range: s
            }, ((e, r, i) => {
                const [s, _, o] = e, a = __PRIVATE_decodeResourcePath(_);
                // Only consider rows matching exactly the specific key of
                // interest. Note that because we order by path first, and we
                // order terminators before path separators, we'll encounter all
                // the index rows for documentKey contiguously. In particular, all
                // the rows for documentKey will occur before any rows for
                // documents nested in a subcollection beneath documentKey so we
                // can stop as soon as we hit any such row.
                                s === this.userId && t.path.isEqual(a) ? n = n.add(o) : i.done();
            }));
            r.push(_);
        })), PersistencePromise.waitFor(r).next((() => this.zr(e, n)));
    }
    getAllMutationBatchesAffectingQuery(e, t) {
        const n = t.path, r = n.length + 1, i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n), s = IDBKeyRange.lowerBound(i);
        // Collect up unique batchIDs encountered during a scan of the index. Use a
        // SortedSet to accumulate batch IDs so they can be traversed in order in a
        // scan of the main table.
        let _ = new SortedSet(__PRIVATE_primitiveComparator);
        return __PRIVATE_documentMutationsStore(e).jn({
            range: s
        }, ((e, t, i) => {
            const [s, o, a] = e, u = __PRIVATE_decodeResourcePath(o);
            s === this.userId && n.isPrefixOf(u) ? 
            // Rows with document keys more than one segment longer than the
            // query path can't be matches. For example, a query on 'rooms'
            // can't match the document /rooms/abc/messages/xyx.
            // TODO(mcg): we'll need a different scanner when we implement
            // ancestor queries.
            u.length === r && (_ = _.add(a)) : i.done();
        })).next((() => this.zr(e, _)));
    }
    zr(e, t) {
        const n = [], r = [];
        // TODO(rockwood): Implement this using iterate.
        return t.forEach((t => {
            r.push(__PRIVATE_mutationsStore(e).get(t).next((e => {
                if (null === e) throw l(35274, {
                    batchId: t
                });
                __PRIVATE_hardAssert(e.userId === this.userId, 9748, "Unexpected user for mutation batch", {
                    userId: e.userId,
                    batchId: t
                }), n.push(__PRIVATE_fromDbMutationBatch(this.serializer, e));
            })));
        })), PersistencePromise.waitFor(r).next((() => n));
    }
    removeMutationBatch(e, t) {
        return removeMutationBatch(e.kr, this.userId, t).next((n => (e.addOnCommittedListener((() => {
            this.jr(t.batchId);
        })), PersistencePromise.forEach(n, (t => this.referenceDelegate.markPotentiallyOrphaned(e, t))))));
    }
    /**
     * Clears the cached keys for a mutation batch. This method should be
     * called by secondary clients after they process mutation updates.
     *
     * Note that this method does not have to be called from primary clients as
     * the corresponding cache entries are cleared when an acknowledged or
     * rejected batch is removed from the mutation queue.
     */
    // PORTING NOTE: Multi-tab only
    jr(e) {
        delete this.$r[e];
    }
    performConsistencyCheck(e) {
        return this.checkEmpty(e).next((t => {
            if (!t) return PersistencePromise.resolve();
            // Verify that there are no entries in the documentMutations index if
            // the queue is empty.
                        const n = IDBKeyRange.lowerBound(
            /**
 * Creates a [userId] key for use in the DbDocumentMutations index to iterate
 * over all of a user's document mutations.
 */
            function __PRIVATE_newDbDocumentMutationPrefixForUser(e) {
                return [ e ];
            }(this.userId)), r = [];
            return __PRIVATE_documentMutationsStore(e).jn({
                range: n
            }, ((e, t, n) => {
                if (e[0] === this.userId) {
                    const t = __PRIVATE_decodeResourcePath(e[1]);
                    r.push(t);
                } else n.done();
            })).next((() => {
                __PRIVATE_hardAssert(0 === r.length, 56720, {
                    Hr: r.map((e => e.canonicalString()))
                });
            }));
        }));
    }
    containsKey(e, t) {
        return __PRIVATE_mutationQueueContainsKey(e, this.userId, t);
    }
    // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
    /** Returns the mutation queue's metadata from IndexedDb. */
    Jr(e) {
        return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e => e || {
            userId: this.userId,
            lastAcknowledgedBatchId: Ke,
            lastStreamToken: ""
        }));
    }
}

/**
 * @returns true if the mutation queue for the given user contains a pending
 *         mutation for the given key.
 */ function __PRIVATE_mutationQueueContainsKey(e, t, n) {
    const r = __PRIVATE_newDbDocumentMutationPrefixForPath(t, n.path), i = r[1], s = IDBKeyRange.lowerBound(r);
    let _ = false;
    return __PRIVATE_documentMutationsStore(e).jn({
        range: s,
        zn: true
    }, ((e, n, r) => {
        const [s, o, /*batchID*/ a] = e;
        s === t && o === i && (_ = true), r.done();
    })).next((() => _));
}

/** Returns true if any mutation queue contains the given document. */
/**
 * Helper to get a typed SimpleDbStore for the mutations object store.
 */
function __PRIVATE_mutationsStore(e) {
    return __PRIVATE_getStore(e, Ht);
}

/**
 * Helper to get a typed SimpleDbStore for the mutationQueues object store.
 */ function __PRIVATE_documentMutationsStore(e) {
    return __PRIVATE_getStore(e, en);
}

/**
 * Helper to get a typed SimpleDbStore for the mutationQueues object store.
 */ function __PRIVATE_mutationQueuesStore(e) {
    return __PRIVATE_getStore(e, zt);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_IndexedDbBundleCache {
    getBundleMetadata(e, t) {
        return __PRIVATE_bundlesStore(e).get(t).next((e => {
            if (e) return function __PRIVATE_fromDbBundle(e) {
                return {
                    id: e.bundleId,
                    createTime: __PRIVATE_fromDbTimestamp(e.createTime),
                    version: e.version
                };
            }
            /** Encodes a BundleMetadata to a DbBundle. */ (e);
        }));
    }
    saveBundleMetadata(e, t) {
        return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e) {
            return {
                bundleId: e.id,
                createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)),
                version: e.version
            };
        }
        /** Encodes a DbNamedQuery to a NamedQuery. */ (t));
    }
    getNamedQuery(e, t) {
        return __PRIVATE_namedQueriesStore(e).get(t).next((e => {
            if (e) return function __PRIVATE_fromDbNamedQuery(e) {
                return {
                    name: e.name,
                    query: __PRIVATE_fromBundledQuery(e.bundledQuery),
                    readTime: __PRIVATE_fromDbTimestamp(e.readTime)
                };
            }
            /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ (e);
        }));
    }
    saveNamedQuery(e, t) {
        return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e) {
            return {
                name: e.name,
                readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)),
                bundledQuery: e.bundledQuery
            };
        }(t));
    }
}

/**
 * Helper to get a typed SimpleDbStore for the bundles object store.
 */ function __PRIVATE_bundlesStore(e) {
    return __PRIVATE_getStore(e, gn);
}

/**
 * Helper to get a typed SimpleDbStore for the namedQueries object store.
 */ function __PRIVATE_namedQueriesStore(e) {
    return __PRIVATE_getStore(e, wn);
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Implementation of DocumentOverlayCache using IndexedDb.
 */ class __PRIVATE_IndexedDbDocumentOverlayCache {
    /**
     * @param serializer - The document serializer.
     * @param userId - The userId for which we are accessing overlays.
     */
    constructor(e, t) {
        this.serializer = e, this.userId = t;
    }
    static Kr(e, t) {
        const n = t.uid || "";
        return new __PRIVATE_IndexedDbDocumentOverlayCache(e, n);
    }
    getOverlay(e, t) {
        return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t)).next((e => e ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e) : null));
    }
    getOverlays(e, t) {
        const n = __PRIVATE_newOverlayMap();
        return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => {
            null !== e && n.set(t, e);
        })))).next((() => n));
    }
    getAllOverlays(e, t) {
        const n = __PRIVATE_newOverlayMap();
        // TODO(pipeline): should we create an index for this? But how often people really expect
        // querying entire database to be fast?
                return __PRIVATE_documentOverlayStore(e).jn(((e, r) => {
            const i = __PRIVATE_fromDbDocumentOverlay(this.serializer, r);
            i.largestBatchId > t && n.set(i.getKey(), i);
        })).next((() => n));
    }
    saveOverlays(e, t, n) {
        const r = [];
        return n.forEach(((n, i) => {
            const s = new Overlay(t, i);
            r.push(this.Yr(e, s));
        })), PersistencePromise.waitFor(r);
    }
    removeOverlaysForBatchId(e, t, n) {
        const r = new Set;
        // Get the set of unique collection paths.
                t.forEach((e => r.add(__PRIVATE_encodeResourcePath(e.getCollectionPath()))));
        const i = [];
        return r.forEach((t => {
            const r = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, n + 1 ], 
            /*lowerOpen=*/ false, 
            /*upperOpen=*/ true);
            i.push(__PRIVATE_documentOverlayStore(e).Gn($n, r));
        })), PersistencePromise.waitFor(i);
    }
    getOverlaysForCollection(e, t, n) {
        const r = __PRIVATE_newOverlayMap(), i = __PRIVATE_encodeResourcePath(t), s = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], 
        /*lowerOpen=*/ true);
        return __PRIVATE_documentOverlayStore(e).Kn($n, s).next((e => {
            for (const t of e) {
                const e = __PRIVATE_fromDbDocumentOverlay(this.serializer, t);
                r.set(e.getKey(), e);
            }
            return r;
        }));
    }
    getOverlaysForCollectionGroup(e, t, n, r) {
        const i = __PRIVATE_newOverlayMap();
        let s;
        // We want batch IDs larger than `sinceBatchId`, and so the lower bound
        // is not inclusive.
                const _ = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, Number.POSITIVE_INFINITY ], 
        /*lowerOpen=*/ true);
        return __PRIVATE_documentOverlayStore(e).jn({
            index: Wn,
            range: _
        }, ((e, t, n) => {
            // We do not want to return partial batch overlays, even if the size
            // of the result set exceeds the given `count` argument. Therefore, we
            // continue to aggregate results even after the result size exceeds
            // `count` if there are more overlays from the `currentBatchId`.
            const _ = __PRIVATE_fromDbDocumentOverlay(this.serializer, t);
            i.size() < r || _.largestBatchId === s ? (i.set(_.getKey(), _), s = _.largestBatchId) : n.done();
        })).next((() => i));
    }
    Yr(e, t) {
        return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e, t, n) {
            const [r, i, s] = __PRIVATE_toDbDocumentOverlayKey(t, n.mutation.key);
            return {
                userId: t,
                collectionPath: i,
                documentId: s,
                collectionGroup: n.mutation.key.getCollectionGroup(),
                largestBatchId: n.largestBatchId,
                overlayMutation: toMutation(e.qr, n.mutation)
            };
        }(this.serializer, this.userId, t));
    }
}

/**
 * Helper to get a typed SimpleDbStore for the document overlay object store.
 */ function __PRIVATE_documentOverlayStore(e) {
    return __PRIVATE_getStore(e, kn);
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_IndexedDbGlobalsCache {
    Zr(e) {
        return __PRIVATE_getStore(e, Gn);
    }
    getSessionToken(e) {
        return this.Zr(e).get("sessionToken").next((e => {
            const t = e?.value;
            return t ? ByteString.fromUint8Array(t) : ByteString.EMPTY_BYTE_STRING;
        }));
    }
    setSessionToken(e, t) {
        return this.Zr(e).put({
            name: "sessionToken",
            value: t.toUint8Array()
        });
    }
}

/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// Note: This code is copied from the backend. Code that is not used by
// Firestore was removed.
/** Firestore index value writer.  */
class __PRIVATE_FirestoreIndexValueWriter {
    constructor() {}
    // The write methods below short-circuit writing terminators for values
    // containing a (terminating) truncated value.
    // As an example, consider the resulting encoding for:
    // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM)
    // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC)
    // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC)
    /** Writes an index value.  */
    Xr(e, t) {
        this.ei(e, t), 
        // Write separator to split index values
        // (see go/firestore-storage-format#encodings).
        t.ti();
    }
    ei(e, t) {
        if ("nullValue" in e) this.ni(t, 5); else if ("booleanValue" in e) this.ni(t, 10), 
        t.ri(e.booleanValue ? 1 : 0); else if ("integerValue" in e) this.ni(t, 15), t.ri(__PRIVATE_normalizeNumber(e.integerValue)); else if ("doubleValue" in e) {
            const n = __PRIVATE_normalizeNumber(e.doubleValue);
            isNaN(n) ? this.ni(t, 13) : (this.ni(t, 15), __PRIVATE_isNegativeZero(n) ? 
            // -0.0, 0 and 0.0 are all considered the same
            t.ri(0) : t.ri(n));
        } else if ("timestampValue" in e) {
            let n = e.timestampValue;
            this.ni(t, 20), "string" == typeof n && (n = __PRIVATE_normalizeTimestamp(n)), t.ii(`${n.seconds || ""}`), 
            t.ri(n.nanos || 0);
        } else if ("stringValue" in e) this.si(e.stringValue, t), this._i(t); else if ("bytesValue" in e) this.ni(t, 30), 
        t.oi(__PRIVATE_normalizeByteString(e.bytesValue)), this._i(t); else if ("referenceValue" in e) this.ai(e.referenceValue, t); else if ("geoPointValue" in e) {
            const n = e.geoPointValue;
            this.ni(t, 45), t.ri(n.latitude || 0), t.ri(n.longitude || 0);
        } else "mapValue" in e ? __PRIVATE_isMaxValue(e) ? this.ni(t, Number.MAX_SAFE_INTEGER) : __PRIVATE_isVectorValue(e) ? this.ui(e.mapValue, t) : (this.ci(e.mapValue, t), 
        this._i(t)) : "arrayValue" in e ? (this.li(e.arrayValue, t), this._i(t)) : l(19022, {
            Ei: e
        });
    }
    si(e, t) {
        this.ni(t, 25), this.hi(e, t);
    }
    hi(e, t) {
        t.ii(e);
    }
    ci(e, t) {
        const n = e.fields || {};
        this.ni(t, 55);
        for (const e of Object.keys(n)) this.si(e, t), this.ei(n[e], t);
    }
    ui(e, t) {
        const n = e.fields || {};
        this.ni(t, 53);
        // Vectors sort first by length
        const r = je, i = n[r].arrayValue?.values?.length || 0;
        this.ni(t, 15), t.ri(__PRIVATE_normalizeNumber(i)), 
        // Vectors then sort by position value
        this.si(r, t), this.ei(n[r], t);
    }
    li(e, t) {
        const n = e.values || [];
        this.ni(t, 50);
        for (const e of n) this.ei(e, t);
    }
    ai(e, t) {
        this.ni(t, 37);
        DocumentKey.fromName(e).path.forEach((e => {
            this.ni(t, 60), this.hi(e, t);
        }));
    }
    ni(e, t) {
        e.ri(t);
    }
    _i(e) {
        // While the SDK does not implement truncation, the truncation marker is
        // used to terminate all variable length values (which are strings, bytes,
        // references, arrays and maps).
        e.ri(2);
    }
}

__PRIVATE_FirestoreIndexValueWriter.Ti = new __PRIVATE_FirestoreIndexValueWriter;

/**
 * @license
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law | agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** These constants are taken from the backend. */
const nr = 255;

/**
 * Counts the number of zeros in a byte.
 *
 * Visible for testing.
 */
function __PRIVATE_numberOfLeadingZerosInByte(e) {
    if (0 === e) return 8;
    let t = 0;
    return e >> 4 || (
    // Test if the first four bits are zero.
    t += 4, e <<= 4), e >> 6 || (
    // Test if the first two (or next two) bits are zero.
    t += 2, e <<= 2), e >> 7 || (
    // Test if the remaining bit is zero.
    t += 1), t;
}

/** Counts the number of leading zeros in the given byte array. */
/**
 * Returns the number of bytes required to store "value". Leading zero bytes
 * are skipped.
 */
function __PRIVATE_unsignedNumLength(e) {
    // This is just the number of bytes for the unsigned representation of the number.
    const t = 64 - function __PRIVATE_numberOfLeadingZeros(e) {
        let t = 0;
        for (let n = 0; n < 8; ++n) {
            const r = __PRIVATE_numberOfLeadingZerosInByte(255 & e[n]);
            if (t += r, 8 !== r) break;
        }
        return t;
    }(e);
    return Math.ceil(t / 8);
}

/**
 * OrderedCodeWriter is a minimal-allocation implementation of the writing
 * behavior defined by the backend.
 *
 * The code is ported from its Java counterpart.
 */ class __PRIVATE_OrderedCodeWriter {
    constructor() {
        this.buffer = new Uint8Array(1024), this.position = 0;
    }
    Pi(e) {
        const t = e[Symbol.iterator]();
        let n = t.next();
        for (;!n.done; ) this.Ri(n.value), n = t.next();
        this.Ii();
    }
    Ai(e) {
        const t = e[Symbol.iterator]();
        let n = t.next();
        for (;!n.done; ) this.Vi(n.value), n = t.next();
        this.di();
    }
    /** Writes utf8 bytes into this byte sequence, ascending. */    fi(e) {
        for (const t of e) {
            const e = t.charCodeAt(0);
            if (e < 128) this.Ri(e); else if (e < 2048) this.Ri(960 | e >>> 6), this.Ri(128 | 63 & e); else if (t < "\ud800" || "\udbff" < t) this.Ri(480 | e >>> 12), 
            this.Ri(128 | 63 & e >>> 6), this.Ri(128 | 63 & e); else {
                const e = t.codePointAt(0);
                this.Ri(240 | e >>> 18), this.Ri(128 | 63 & e >>> 12), this.Ri(128 | 63 & e >>> 6), 
                this.Ri(128 | 63 & e);
            }
        }
        this.Ii();
    }
    /** Writes utf8 bytes into this byte sequence, descending */    mi(e) {
        for (const t of e) {
            const e = t.charCodeAt(0);
            if (e < 128) this.Vi(e); else if (e < 2048) this.Vi(960 | e >>> 6), this.Vi(128 | 63 & e); else if (t < "\ud800" || "\udbff" < t) this.Vi(480 | e >>> 12), 
            this.Vi(128 | 63 & e >>> 6), this.Vi(128 | 63 & e); else {
                const e = t.codePointAt(0);
                this.Vi(240 | e >>> 18), this.Vi(128 | 63 & e >>> 12), this.Vi(128 | 63 & e >>> 6), 
                this.Vi(128 | 63 & e);
            }
        }
        this.di();
    }
    pi(e) {
        // Values are encoded with a single byte length prefix, followed by the
        // actual value in big-endian format with leading 0 bytes dropped.
        const t = this.gi(e), n = __PRIVATE_unsignedNumLength(t);
        this.yi(1 + n), this.buffer[this.position++] = 255 & n;
        // Write the length
        for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = 255 & t[e];
    }
    wi(e) {
        // Values are encoded with a single byte length prefix, followed by the
        // inverted value in big-endian format with leading 0 bytes dropped.
        const t = this.gi(e), n = __PRIVATE_unsignedNumLength(t);
        this.yi(1 + n), this.buffer[this.position++] = ~(255 & n);
        // Write the length
        for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = ~(255 & t[e]);
    }
    /**
     * Writes the "infinity" byte sequence that sorts after all other byte
     * sequences written in ascending order.
     */    bi() {
        this.Si(nr), this.Si(255);
    }
    /**
     * Writes the "infinity" byte sequence that sorts before all other byte
     * sequences written in descending order.
     */    Di() {
        this.xi(nr), this.xi(255);
    }
    /**
     * Resets the buffer such that it is the same as when it was newly
     * constructed.
     */    reset() {
        this.position = 0;
    }
    seed(e) {
        this.yi(e.length), this.buffer.set(e, this.position), this.position += e.length;
    }
    /** Makes a copy of the encoded bytes in this buffer.  */    Ci() {
        return this.buffer.slice(0, this.position);
    }
    /**
     * Encodes `val` into an encoding so that the order matches the IEEE 754
     * floating-point comparison results with the following exceptions:
     *   -0.0 < 0.0
     *   all non-NaN < NaN
     *   NaN = NaN
     */    gi(e) {
        const t = 
        /** Converts a JavaScript number to a byte array (using big endian encoding). */
        function __PRIVATE_doubleToLongBits(e) {
            const t = new DataView(new ArrayBuffer(8));
            return t.setFloat64(0, e, /* littleEndian= */ false), new Uint8Array(t.buffer);
        }(e), n = !!(128 & t[0]);
        // Check if the first bit is set. We use a bit mask since value[0] is
        // encoded as a number from 0 to 255.
                // Revert the two complement to get natural ordering
        t[0] ^= n ? 255 : 128;
        for (let e = 1; e < t.length; ++e) t[e] ^= n ? 255 : 0;
        return t;
    }
    /** Writes a single byte ascending to the buffer. */    Ri(e) {
        const t = 255 & e;
        0 === t ? (this.Si(0), this.Si(255)) : t === nr ? (this.Si(nr), this.Si(0)) : this.Si(t);
    }
    /** Writes a single byte descending to the buffer.  */    Vi(e) {
        const t = 255 & e;
        0 === t ? (this.xi(0), this.xi(255)) : t === nr ? (this.xi(nr), this.xi(0)) : this.xi(e);
    }
    Ii() {
        this.Si(0), this.Si(1);
    }
    di() {
        this.xi(0), this.xi(1);
    }
    Si(e) {
        this.yi(1), this.buffer[this.position++] = e;
    }
    xi(e) {
        this.yi(1), this.buffer[this.position++] = ~e;
    }
    yi(e) {
        const t = e + this.position;
        if (t <= this.buffer.length) return;
        // Try doubling.
                let n = 2 * this.buffer.length;
        // Still not big enough? Just allocate the right size.
                n < t && (n = t);
        // Create the new buffer.
                const r = new Uint8Array(n);
        r.set(this.buffer), // copy old data
        this.buffer = r;
    }
}

class __PRIVATE_AscendingIndexByteEncoder {
    constructor(e) {
        this.Fi = e;
    }
    oi(e) {
        this.Fi.Pi(e);
    }
    ii(e) {
        this.Fi.fi(e);
    }
    ri(e) {
        this.Fi.pi(e);
    }
    ti() {
        this.Fi.bi();
    }
}

class __PRIVATE_DescendingIndexByteEncoder {
    constructor(e) {
        this.Fi = e;
    }
    oi(e) {
        this.Fi.Ai(e);
    }
    ii(e) {
        this.Fi.mi(e);
    }
    ri(e) {
        this.Fi.wi(e);
    }
    ti() {
        this.Fi.Di();
    }
}

/**
 * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the
 * actual encoding.
 */ class __PRIVATE_IndexByteEncoder {
    constructor() {
        this.Fi = new __PRIVATE_OrderedCodeWriter, this.ascending = new __PRIVATE_AscendingIndexByteEncoder(this.Fi), 
        this.descending = new __PRIVATE_DescendingIndexByteEncoder(this.Fi);
    }
    seed(e) {
        this.Fi.seed(e);
    }
    Oi(e) {
        return 0 /* IndexKind.ASCENDING */ === e ? this.ascending : this.descending;
    }
    Ci() {
        return this.Fi.Ci();
    }
    reset() {
        this.Fi.reset();
    }
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Represents an index entry saved by the SDK in persisted storage. */ class __PRIVATE_IndexEntry {
    constructor(e, t, n, r) {
        this.Mi = e, this.Ni = t, this.Li = n, this.Bi = r;
    }
    /**
     * Returns an IndexEntry entry that sorts immediately after the current
     * directional value.
     */    Ui() {
        const e = this.Bi.length, t = 0 === e || 255 === this.Bi[e - 1] ? e + 1 : e, n = new Uint8Array(t);
        return n.set(this.Bi, 0), t !== e ? n.set([ 0 ], this.Bi.length) : ++n[n.length - 1], 
        new __PRIVATE_IndexEntry(this.Mi, this.Ni, this.Li, n);
    }
    // Create a representation of the Index Entry as a DbIndexEntry
    ki(e, t, n) {
        return {
            indexId: this.Mi,
            uid: e,
            arrayValue: __PRIVATE_encodeKeySafeBytes(this.Li),
            directionalValue: __PRIVATE_encodeKeySafeBytes(this.Bi),
            orderedDocumentKey: __PRIVATE_encodeKeySafeBytes(t),
            documentKey: n.path.toArray()
        };
    }
    // Create a representation of the Index Entry as a DbIndexEntryKey
    qi(e, t, n) {
        const r = this.ki(e, t, n);
        return [ r.indexId, r.uid, r.arrayValue, r.directionalValue, r.orderedDocumentKey, r.documentKey ];
    }
}

function __PRIVATE_indexEntryComparator(e, t) {
    let n = e.Mi - t.Mi;
    return 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.Li, t.Li), 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.Bi, t.Bi), 
    0 !== n ? n : DocumentKey.comparator(e.Ni, t.Ni)));
}

function __PRIVATE_compareByteArrays(e, t) {
    for (let n = 0; n < e.length && n < t.length; ++n) {
        const r = e[n] - t[n];
        if (0 !== r) return r;
    }
    return e.length - t.length;
}

/**
 * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721
 * Create a key safe representation of Uint8Array values.
 * If the browser is detected as Safari or WebKit, then
 * the input array will be converted to "sortable byte string".
 * Otherwise, the input array will be returned in its original type.
 */ function __PRIVATE_encodeKeySafeBytes(e) {
    return util.isSafariOrWebkit() ? 
    /**
 * Encodes a Uint8Array into a "sortable byte string".
 * A "sortable byte string" sorts in the same order as the Uint8Array.
 * This works because JS string comparison sorts strings based on code points.
 */
    function __PRIVATE_encodeUint8ArrayToSortableString(e) {
        let t = "";
        for (let n = 0; n < e.length; n++) t += String.fromCharCode(e[n]);
        return t;
    }
    /**
 * Decodes a "sortable byte string" back into a Uint8Array.
 * A "sortable byte string" is assumed to be created where each character's
 * Unicode code point directly corresponds to a single byte value (0-255).
 */ (e) : e;
}

/**
 * Reverts the key safe representation of Uint8Array (created by
 * encodeKeySafeBytes) to a normal Uint8Array.
 */ function __PRIVATE_decodeKeySafeBytes(e) {
    return "string" != typeof e ? e : function __PRIVATE_decodeSortableStringToUint8Array(e) {
        const t = new Uint8Array(e.length);
        for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n);
        return t;
    }
    /**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
    /**
 * A light query planner for Firestore.
 *
 * This class matches a `FieldIndex` against a Firestore Query `Target`. It
 * determines whether a given index can be used to serve the specified target.
 *
 * The following table showcases some possible index configurations:
 *
 * Query                                               | Index
 * -----------------------------------------------------------------------------
 * where('a', '==', 'a').where('b', '==', 'b')         | a ASC, b DESC
 * where('a', '==', 'a').where('b', '==', 'b')         | a ASC
 * where('a', '==', 'a').where('b', '==', 'b')         | b DESC
 * where('a', '>=', 'a').orderBy('a')                  | a ASC
 * where('a', '>=', 'a').orderBy('a', 'desc')          | a DESC
 * where('a', '>=', 'a').orderBy('a').orderBy('b')     | a ASC, b ASC
 * where('a', '>=', 'a').orderBy('a').orderBy('b')     | a ASC
 * where('a', 'array-contains', 'a').orderBy('b')      | a CONTAINS, b ASCENDING
 * where('a', 'array-contains', 'a').orderBy('b')      | a CONTAINS
 */ (e);
}

class __PRIVATE_TargetIndexMatcher {
    constructor(e) {
        // The inequality filters of the target (if it exists).
        // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom
        // comparator.
        this.$i = new SortedSet(((e, t) => Oe.comparator(e.field, t.field))), this.collectionId = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment(), 
        this.Ki = e.orderBy, this.Wi = [];
        for (const t of e.filters) {
            const e = t;
            e.isInequality() ? this.$i = this.$i.add(e) : this.Wi.push(e);
        }
    }
    get Qi() {
        return this.$i.size > 1;
    }
    /**
     * Returns whether the index can be used to serve the TargetIndexMatcher's
     * target.
     *
     * An index is considered capable of serving the target when:
     * - The target uses all index segments for its filters and orderBy clauses.
     *   The target can have additional filter and orderBy clauses, but not
     *   fewer.
     * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also
     *   have a corresponding `CONTAINS` segment.
     * - All directional index segments can be mapped to the target as a series of
     *   equality filters, a single inequality filter and a series of orderBy
     *   clauses.
     * - The segments that represent the equality filters may appear out of order.
     * - The optional segment for the inequality filter must appear after all
     *   equality segments.
     * - The segments that represent that orderBy clause of the target must appear
     *   in order after all equality and inequality segments. Single orderBy
     *   clauses cannot be skipped, but a continuous orderBy suffix may be
     *   omitted.
     */    Gi(e) {
        if (__PRIVATE_hardAssert(e.collectionGroup === this.collectionId, 49279), this.Qi) 
        // Only single inequality is supported for now.
        // TODO(Add support for multiple inequality query): b/298441043
        return false;
        // If there is an array element, find a matching filter.
                const t = __PRIVATE_fieldIndexGetArraySegment(e);
        if (void 0 !== t && !this.zi(t)) return false;
        const n = __PRIVATE_fieldIndexGetDirectionalSegments(e);
        let r = new Set, i = 0, s = 0;
        // Process all equalities first. Equalities can appear out of order.
        for (;i < n.length && this.zi(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString());
        // If we already have processed all segments, all segments are used to serve
        // the equality filters and we do not need to map any segments to the
        // target's inequality and orderBy clauses.
                if (i === n.length) return true;
        if (this.$i.size > 0) {
            // Only a single inequality is currently supported. Get the only entry in the set.
            const e = this.$i.getIterator().getNext();
            // If there is an inequality filter and the field was not in one of the
            // equality filters above, the next segment must match both the filter
            // and the first orderBy clause.
                        if (!r.has(e.field.canonicalString())) {
                const t = n[i];
                if (!this.ji(e, t) || !this.Hi(this.Ki[s++], t)) return false;
            }
            ++i;
        }
        // All remaining segments need to represent the prefix of the target's
        // orderBy.
                for (;i < n.length; ++i) {
            const e = n[i];
            if (s >= this.Ki.length || !this.Hi(this.Ki[s++], e)) return false;
        }
        return true;
    }
    /**
     * Returns a full matched field index for this target. Currently multiple
     * inequality query is not supported so function returns null.
     */    Ji() {
        if (this.Qi) return null;
        // We want to make sure only one segment created for one field. For example,
        // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created
        // once.
                let e = new SortedSet(Oe.comparator);
        const t = [];
        for (const n of this.Wi) {
            if (n.field.isKeyField()) continue;
            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 {
                if (e.has(n.field)) continue;
                e = e.add(n.field), t.push(new IndexSegment(n.field, 0 /* IndexKind.ASCENDING */));
            }
        }
        // Note: We do not explicitly check `this.inequalityFilter` but rather rely
        // on the target defining an appropriate "order by" to ensure that the
        // required index segment is added. The query engine would reject a query
        // with an inequality filter that lacks the required order-by clause.
                for (const n of this.Ki) 
        // Stop adding more segments if we see a order-by on key. Typically this
        // is the default implicit order-by which is covered in the index_entry
        // table as a separate column. If it is not the default order-by, the
        // generated index will be missing some segments optimized for order-bys,
        // which is probably fine.
        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 */)));
        return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, t, IndexState.empty());
    }
    zi(e) {
        for (const t of this.Wi) if (this.ji(t, e)) return true;
        return false;
    }
    ji(e, t) {
        if (void 0 === e || !e.field.isEqual(t.fieldPath)) return false;
        const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === e.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e.op;
        return 2 /* IndexKind.CONTAINS */ === t.kind === n;
    }
    Hi(e, t) {
        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);
    }
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Provides utility functions that help with boolean logic transformations needed for handling
 * complex filters used in queries.
 */
/**
 * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in
 * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given
 * input into a disjunction of equality filters and returns the expanded filter.
 */ function __PRIVATE_computeInExpansion(e) {
    if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 20012), 
    e instanceof FieldFilter) {
        if (e instanceof __PRIVATE_InFilter) {
            const t = e.value.arrayValue?.values?.map((t => FieldFilter.create(e.field, "==" /* Operator.EQUAL */ , t))) || [];
            return CompositeFilter.create(t, "or" /* CompositeOperator.OR */);
        }
        // We have reached other kinds of field filters.
        return e;
    }
    // We have a composite filter.
        const t = e.filters.map((e => __PRIVATE_computeInExpansion(e)));
    return CompositeFilter.create(t, e.op);
}

/**
 * Given a composite filter, returns the list of terms in its disjunctive normal form.
 *
 * <p>Each element in the return value is one term of the resulting DNF. For instance: For the
 * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list
 * with two elements: a composite filter that performs (A && C), and a composite filter that
 * performs (B && C).
 *
 * @param filter - the composite filter to calculate DNF transform for.
 * @returns the terms in the DNF transform.
 */ function __PRIVATE_getDnfTerms(e) {
    if (0 === e.getFilters().length) return [];
    const t = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e));
    return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t), 7391), __PRIVATE_isSingleFieldFilter(t) || __PRIVATE_isFlatConjunction(t) ? [ t ] : t.getFilters();
}

/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function __PRIVATE_isSingleFieldFilter(e) {
    return e instanceof FieldFilter;
}

/**
 * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10
 * && b == 20)
 */ function __PRIVATE_isFlatConjunction(e) {
    return e instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e);
}

/**
 * Returns whether or not the given filter is in disjunctive normal form (DNF).
 *
 * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical
 * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.
 *
 * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form
 */ function __PRIVATE_isDisjunctiveNormalForm(e) {
    return __PRIVATE_isSingleFieldFilter(e) || __PRIVATE_isFlatConjunction(e) || 
    /**
 * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and
 * field filters. e.g. (a == 10) || (b==20 && c==30)
 */
    function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e) {
        if (e instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e)) {
            for (const t of e.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t) && !__PRIVATE_isFlatConjunction(t)) return false;
            return true;
        }
        return false;
    }(e);
}

function __PRIVATE_computeDistributedNormalForm(e) {
    if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 34018), 
    e instanceof FieldFilter) return e;
    if (1 === e.filters.length) return __PRIVATE_computeDistributedNormalForm(e.filters[0]);
    // Compute DNF for each of the subfilters first
        const t = e.filters.map((e => __PRIVATE_computeDistributedNormalForm(e)));
    let n = CompositeFilter.create(t, e.op);
    return n = __PRIVATE_applyAssociation(n), __PRIVATE_isDisjunctiveNormalForm(n) ? n : (__PRIVATE_hardAssert(n instanceof CompositeFilter, 64498), 
    __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n), 40251), __PRIVATE_hardAssert(n.filters.length > 1, 57927), 
    n.filters.reduce(((e, t) => __PRIVATE_applyDistribution(e, t))));
}

function __PRIVATE_applyDistribution(e, t) {
    let n;
    return __PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 38388), 
    __PRIVATE_hardAssert(t instanceof FieldFilter || t instanceof CompositeFilter, 25473), 
    // FieldFilter FieldFilter
    n = e instanceof FieldFilter ? t instanceof FieldFilter ? function __PRIVATE_applyDistributionFieldFilters(e, t) {
        // Conjunction distribution for two field filters is the conjunction of them.
        return CompositeFilter.create([ e, t ], "and" /* CompositeOperator.AND */);
    }(e, t) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) : t instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t, e) : function __PRIVATE_applyDistributionCompositeFilters(e, t) {
        // There are four cases:
        // (A & B) & (C & D) --> (A & B & C & D)
        // (A & B) & (C | D) --> (A & B & C) | (A & B & D)
        // (A | B) & (C & D) --> (C & D & A) | (C & D & B)
        // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)
        // Case 1 is a merge.
        if (__PRIVATE_hardAssert(e.filters.length > 0 && t.filters.length > 0, 48005), __PRIVATE_compositeFilterIsConjunction(e) && __PRIVATE_compositeFilterIsConjunction(t)) return __PRIVATE_compositeFilterWithAddedFilters(e, t.getFilters());
        // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases
        // we should take each element of the disjunction and distribute it over the other side, and
        // return the disjunction of the distribution results.
                const n = __PRIVATE_compositeFilterIsDisjunction(e) ? e : t, r = __PRIVATE_compositeFilterIsDisjunction(e) ? t : e, i = n.filters.map((e => __PRIVATE_applyDistribution(e, r)));
        return CompositeFilter.create(i, "or" /* CompositeOperator.OR */);
    }(e, t), __PRIVATE_applyAssociation(n);
}

function __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) {
    // There are two cases:
    // A & (B & C) --> (A & B & C)
    // A & (B | C) --> (A & B) | (A & C)
    if (__PRIVATE_compositeFilterIsConjunction(t)) 
    // Case 1
    return __PRIVATE_compositeFilterWithAddedFilters(t, e.getFilters());
    {
        // Case 2
        const n = t.filters.map((t => __PRIVATE_applyDistribution(e, t)));
        return CompositeFilter.create(n, "or" /* CompositeOperator.OR */);
    }
}

/**
 * Applies the associativity property to the given filter and returns the resulting filter.
 *
 * <ul>
 *   <li>A | (B | C) == (A | B) | C == (A | B | C)
 *   <li>A & (B & C) == (A & B) & C == (A & B & C)
 * </ul>
 *
 * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic
 */ function __PRIVATE_applyAssociation(e) {
    if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 11850), 
    e instanceof FieldFilter) return e;
    const t = e.getFilters();
    // If the composite filter only contains 1 filter, apply associativity to it.
        if (1 === t.length) return __PRIVATE_applyAssociation(t[0]);
    // Associativity applied to a flat composite filter results is itself.
        if (__PRIVATE_compositeFilterIsFlat(e)) return e;
    // First apply associativity to all subfilters. This will in turn recursively apply
    // associativity to all nested composite filters and field filters.
        const n = t.map((e => __PRIVATE_applyAssociation(e))), r = [];
    // For composite subfilters that perform the same kind of logical operation as `compositeFilter`
    // take out their filters and add them to `compositeFilter`. For example:
    // compositeFilter = (A | (B | C | D))
    // compositeSubfilter = (B | C | D)
    // Result: (A | B | C | D)
    // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been
    // added to the top-level "compositeFilter".
        return n.forEach((t => {
        t instanceof FieldFilter ? r.push(t) : t instanceof CompositeFilter && (t.op === e.op ? 
        // compositeFilter: (A | (B | C))
        // compositeSubfilter: (B | C)
        // Result: (A | B | C)
        r.push(...t.filters) : 
        // compositeFilter: (A | (B & C))
        // compositeSubfilter: (B & C)
        // Result: (A | (B & C))
        r.push(t));
    })), 1 === r.length ? r[0] : CompositeFilter.create(r, e.op);
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An in-memory implementation of IndexManager.
 */ class __PRIVATE_MemoryIndexManager {
    constructor() {
        this.Yi = new __PRIVATE_MemoryCollectionParentIndex;
    }
    addToCollectionParentIndex(e, t) {
        return this.Yi.add(t), PersistencePromise.resolve();
    }
    getCollectionParents(e, t) {
        return PersistencePromise.resolve(this.Yi.getEntries(t));
    }
    addFieldIndex(e, t) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve();
    }
    deleteFieldIndex(e, t) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve();
    }
    deleteAllFieldIndexes(e) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve();
    }
    createTargetIndexes(e, t) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve();
    }
    getDocumentsMatchingTarget(e, t) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve(null);
    }
    getIndexType(e, t) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve(0 /* IndexType.NONE */);
    }
    getFieldIndexes(e, t) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve([]);
    }
    getNextCollectionGroupToUpdate(e) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve(null);
    }
    getMinOffset(e, t) {
        return PersistencePromise.resolve(IndexOffset.min());
    }
    getMinOffsetFromCollectionGroup(e, t) {
        return PersistencePromise.resolve(IndexOffset.min());
    }
    updateCollectionGroup(e, t, n) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve();
    }
    updateIndexEntries(e, t) {
        // Field indices are not supported with memory persistence.
        return PersistencePromise.resolve();
    }
}

/**
 * Internal implementation of the collection-parent index exposed by MemoryIndexManager.
 * Also used for in-memory caching by IndexedDbIndexManager and initial index population
 * in indexeddb_schema.ts
 */ class __PRIVATE_MemoryCollectionParentIndex {
    constructor() {
        this.index = {};
    }
    // Returns false if the entry already existed.
    add(e) {
        const t = e.lastSegment(), n = e.popLast(), r = this.index[t] || new SortedSet(ResourcePath.comparator), i = !r.has(n);
        return this.index[t] = r.add(n), i;
    }
    has(e) {
        const t = e.lastSegment(), n = e.popLast(), r = this.index[t];
        return r && r.has(n);
    }
    getEntries(e) {
        return (this.index[e] || new SortedSet(ResourcePath.comparator)).toArray();
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const rr = "IndexedDbIndexManager", ir = new Uint8Array(0);

/**
 * A persisted implementation of IndexManager.
 *
 * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index
 * data as it supports multi-tab access.
 */
class __PRIVATE_IndexedDbIndexManager {
    constructor(e, t) {
        this.databaseId = t, 
        /**
         * An in-memory copy of the index entries we've already written since the SDK
         * launched. Used to avoid re-writing the same entry repeatedly.
         *
         * This is *NOT* a complete cache of what's in persistence and so can never be
         * used to satisfy reads.
         */
        this.Zi = new __PRIVATE_MemoryCollectionParentIndex, 
        /**
         * Maps from a target to its equivalent list of sub-targets. Each sub-target
         * contains only one term from the target's disjunctive normal form (DNF).
         */
        this.Xi = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), ((e, t) => __PRIVATE_targetEquals(e, t))), 
        this.uid = e.uid || "";
    }
    /**
     * Adds a new entry to the collection parent index.
     *
     * Repeated calls for the same collectionPath should be avoided within a
     * transaction as IndexedDbIndexManager only caches writes once a transaction
     * has been committed.
     */    addToCollectionParentIndex(e, t) {
        if (!this.Zi.has(t)) {
            const n = t.lastSegment(), r = t.popLast();
            e.addOnCommittedListener((() => {
                // Add the collection to the in memory cache only if the transaction was
                // successfully committed.
                this.Zi.add(t);
            }));
            const i = {
                collectionId: n,
                parent: __PRIVATE_encodeResourcePath(r)
            };
            return __PRIVATE_collectionParentsStore(e).put(i);
        }
        return PersistencePromise.resolve();
    }
    getCollectionParents(e, t) {
        const n = [], r = IDBKeyRange.bound([ t, "" ], [ __PRIVATE_immediateSuccessor(t), "" ], 
        /*lowerOpen=*/ false, 
        /*upperOpen=*/ true);
        return __PRIVATE_collectionParentsStore(e).Kn(r).next((e => {
            for (const r of e) {
                // This collectionId guard shouldn't be necessary (and isn't as long
                // as we're running in a real browser), but there's a bug in
                // indexeddbshim that breaks our range in our tests running in node:
                // https://github.com/axemclion/IndexedDBShim/issues/334
                if (r.collectionId !== t) break;
                n.push(__PRIVATE_decodeResourcePath(r.parent));
            }
            return n;
        }));
    }
    addFieldIndex(e, t) {
        // TODO(indexing): Verify that the auto-incrementing index ID works in
        // Safari & Firefox.
        const n = __PRIVATE_indexConfigurationStore(e), r = function __PRIVATE_toDbIndexConfiguration(e) {
            return {
                indexId: e.indexId,
                collectionGroup: e.collectionGroup,
                fields: e.fields.map((e => [ e.fieldPath.canonicalString(), e.kind ]))
            };
        }(t);
        delete r.indexId;
        // `indexId` is auto-populated by IndexedDb
        const i = n.add(r);
        if (t.indexState) {
            const n = __PRIVATE_indexStateStore(e);
            return i.next((e => {
                n.put(__PRIVATE_toDbIndexState(e, this.uid, t.indexState.sequenceNumber, t.indexState.offset));
            }));
        }
        return i.next();
    }
    deleteFieldIndex(e, t) {
        const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e), i = __PRIVATE_indexEntriesStore(e);
        return n.delete(t.indexId).next((() => r.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], 
        /*lowerOpen=*/ false, 
        /*upperOpen=*/ true)))).next((() => i.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], 
        /*lowerOpen=*/ false, 
        /*upperOpen=*/ true))));
    }
    deleteAllFieldIndexes(e) {
        const t = __PRIVATE_indexConfigurationStore(e), n = __PRIVATE_indexEntriesStore(e), r = __PRIVATE_indexStateStore(e);
        return t.Gn().next((() => n.Gn())).next((() => r.Gn()));
    }
    createTargetIndexes(e, t) {
        return PersistencePromise.forEach(this.es(t), (t => this.getIndexType(e, t).next((n => {
            if (0 /* IndexType.NONE */ === n || 1 /* IndexType.PARTIAL */ === n) {
                const n = new __PRIVATE_TargetIndexMatcher(t).Ji();
                if (null != n) return this.addFieldIndex(e, n);
            }
        }))));
    }
    getDocumentsMatchingTarget(e, t) {
        const n = __PRIVATE_indexEntriesStore(e);
        let r = true;
        const i = new Map;
        return PersistencePromise.forEach(this.es(t), (t => this.ts(e, t).next((e => {
            r && (r = !!e), i.set(t, e);
        })))).next((() => {
            if (r) {
                let e = __PRIVATE_documentKeySet();
                const r = [];
                return PersistencePromise.forEach(i, ((i, s) => {
                    __PRIVATE_logDebug(rr, `Using index ${function __PRIVATE_fieldIndexToString(e) {
                        return `id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e => `${e.fieldPath}:${e.kind}`)).join(",")}`;
                    }(i)} to execute ${__PRIVATE_canonifyTarget(t)}`);
                    const _ = function __PRIVATE_targetGetArrayValues(e, t) {
                        const n = __PRIVATE_fieldIndexGetArraySegment(t);
                        if (void 0 === n) return null;
                        for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, n.fieldPath)) switch (t.op) {
                          case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ :
                            return t.value.arrayValue.values || [];

                          case "array-contains" /* Operator.ARRAY_CONTAINS */ :
                            return [ t.value ];
                            // Remaining filters are not array filters.
                                                }
                        return null;
                    }
                    /**
 * Returns the list of values that are used in != or NOT_IN filters. Returns
 * `null` if there are no such filters.
 */ (s, i), o = function __PRIVATE_targetGetNotInValues(e, t) {
                        const n = new Map;
                        for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(t)) for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, r.fieldPath)) switch (t.op) {
                          case "==" /* Operator.EQUAL */ :
                          case "in" /* Operator.IN */ :
                            // Encode equality prefix, which is encoded in the index value before
                            // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to
                            // `value != 'ab'`).
                            n.set(r.fieldPath.canonicalString(), t.value);
                            break;

                          case "not-in" /* Operator.NOT_IN */ :
                          case "!=" /* Operator.NOT_EQUAL */ :
                            // NotIn/NotEqual is always a suffix. There cannot be any remaining
                            // segments and hence we can return early here.
                            return n.set(r.fieldPath.canonicalString(), t.value), Array.from(n.values());
                            // Remaining filters cannot be used as notIn bounds.
                                                }
                        return null;
                    }
                    /**
 * Returns a lower bound of field values that can be used as a starting point to
 * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound
 * exists.
 */ (s, i), a = function __PRIVATE_targetGetLowerBound(e, t) {
                        const n = [];
                        let r = true;
                        // For each segment, retrieve a lower bound if there is a suitable filter or
                        // startAt.
                                                for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) {
                            const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.startAt) : __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.startAt);
                            n.push(t.value), r && (r = t.inclusive);
                        }
                        return new Bound(n, r);
                    }
                    /**
 * Returns an upper bound of field values that can be used as an ending point
 * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no
 * upper bound exists.
 */ (s, i), u = function __PRIVATE_targetGetUpperBound(e, t) {
                        const n = [];
                        let r = true;
                        // For each segment, retrieve an upper bound if there is a suitable filter or
                        // endAt.
                                                for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) {
                            const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.endAt) : __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.endAt);
                            n.push(t.value), r && (r = t.inclusive);
                        }
                        return new Bound(n, r);
                    }(s, i), c = this.ns(i, s, a), l = this.ns(i, s, u), E = this.rs(i, s, o), h = this.ss(i.indexId, _, c, a.inclusive, l, u.inclusive, E);
                    return PersistencePromise.forEach(h, (i => n.Qn(i, t.limit).next((t => {
                        t.forEach((t => {
                            const n = DocumentKey.fromSegments(t.documentKey);
                            e.has(n) || (e = e.add(n), r.push(n));
                        }));
                    }))));
                })).next((() => r));
            }
            return PersistencePromise.resolve(null);
        }));
    }
    es(e) {
        let t = this.Xi.get(e);
        if (t) return t;
        if (0 === e.filters.length) t = [ e ]; else {
            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)));
        }
        return this.Xi.set(e, t), t;
    }
    /**
     * Constructs a key range query on `DbIndexEntryStore` that unions all
     * bounds.
     */    ss(e, t, n, r, i, s, _) {
        // The number of total index scans we union together. This is similar to a
        // distributed normal form, but adapted for array values. We create a single
        // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter
        // combined with the values from the query bounds.
        const o = (null != t ? t.length : 1) * Math.max(n.length, i.length), a = o / (null != t ? t.length : 1), u = [];
        for (let c = 0; c < o; ++c) {
            const o = t ? this._s(t[c / a]) : ir, l = this.us(e, o, n[c % a], r), E = this.cs(e, o, i[c % a], s), h = _.map((t => this.us(e, o, t, 
            /* inclusive= */ true)));
            u.push(...this.createRange(l, E, h));
        }
        return u;
    }
    /** Generates the lower bound for `arrayValue` and `directionalValue`. */    us(e, t, n, r) {
        const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);
        return r ? i : i.Ui();
    }
    /** Generates the upper bound for `arrayValue` and `directionalValue`. */    cs(e, t, n, r) {
        const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n);
        return r ? i.Ui() : i;
    }
    ts(e, t) {
        const n = new __PRIVATE_TargetIndexMatcher(t), r = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment();
        return this.getFieldIndexes(e, r).next((e => {
            // Return the index with the most number of segments.
            let t = null;
            for (const r of e) {
                n.Gi(r) && (!t || r.fields.length > t.fields.length) && (t = r);
            }
            return t;
        }));
    }
    getIndexType(e, t) {
        let n = 2 /* IndexType.FULL */;
        const r = this.es(t);
        return PersistencePromise.forEach(r, (t => this.ts(e, t).next((e => {
            e ? 0 /* IndexType.NONE */ !== n && e.fields.length < function __PRIVATE_targetGetSegmentCount(e) {
                let t = new SortedSet(Oe.comparator), n = false;
                for (const r of e.filters) for (const e of r.getFlattenedFilters()) 
                // __name__ is not an explicit segment of any index, so we don't need to
                // count it.
                e.field.isKeyField() || (
                // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.
                // For instance, it is possible to have an index for "a ARRAY a ASC". Even
                // though these are on the same field, they should be counted as two
                // separate segments in an index.
                "array-contains" /* Operator.ARRAY_CONTAINS */ === e.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e.op ? n = true : t = t.add(e.field));
                for (const n of e.orderBy) 
                // __name__ is not an explicit segment of any index, so we don't need to
                // count it.
                n.field.isKeyField() || (t = t.add(n.field));
                return t.size + (n ? 1 : 0);
            }(t) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;
        })))).next((() => 
        // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider
        // OR queries that have a `limit` to have a partial index. For such queries we perform sorting
        // and apply the limit in memory as a post-processing step.
        function __PRIVATE_targetHasLimit(e) {
            return null !== e.limit;
        }(t) && r.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));
    }
    /**
     * Returns the byte encoded form of the directional values in the field index.
     * Returns `null` if the document does not have all fields specified in the
     * index.
     */    ls(e, t) {
        const n = new __PRIVATE_IndexByteEncoder;
        for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {
            const e = t.data.field(r.fieldPath);
            if (null == e) return null;
            const i = n.Oi(r.kind);
            __PRIVATE_FirestoreIndexValueWriter.Ti.Xr(e, i);
        }
        return n.Ci();
    }
    /** Encodes a single value to the ascending index format. */    _s(e) {
        const t = new __PRIVATE_IndexByteEncoder;
        return __PRIVATE_FirestoreIndexValueWriter.Ti.Xr(e, t.Oi(0 /* IndexKind.ASCENDING */)), 
        t.Ci();
    }
    /**
     * Returns an encoded form of the document key that sorts based on the key
     * ordering of the field index.
     */    Es(e, t) {
        const n = new __PRIVATE_IndexByteEncoder;
        return __PRIVATE_FirestoreIndexValueWriter.Ti.Xr(__PRIVATE_refValue(this.databaseId, t), n.Oi(function __PRIVATE_fieldIndexGetKeyOrder(e) {
            const t = __PRIVATE_fieldIndexGetDirectionalSegments(e);
            return 0 === t.length ? 0 /* IndexKind.ASCENDING */ : t[t.length - 1].kind;
        }(e))), n.Ci();
    }
    /**
     * Encodes the given field values according to the specification in `target`.
     * For IN queries, a list of possible values is returned.
     */    rs(e, t, n) {
        if (null === n) return [];
        let r = [];
        r.push(new __PRIVATE_IndexByteEncoder);
        let i = 0;
        for (const s of __PRIVATE_fieldIndexGetDirectionalSegments(e)) {
            const e = n[i++];
            for (const n of r) if (this.hs(t, s.fieldPath) && isArray(e)) r = this.Ts(r, s, e); else {
                const t = n.Oi(s.kind);
                __PRIVATE_FirestoreIndexValueWriter.Ti.Xr(e, t);
            }
        }
        return this.Ps(r);
    }
    /**
     * Encodes the given bounds according to the specification in `target`. For IN
     * queries, a list of possible values is returned.
     */    ns(e, t, n) {
        return this.rs(e, t, n.position);
    }
    /** Returns the byte representation for the provided encoders. */    Ps(e) {
        const t = [];
        for (let n = 0; n < e.length; ++n) t[n] = e[n].Ci();
        return t;
    }
    /**
     * Creates a separate encoder for each element of an array.
     *
     * The method appends each value to all existing encoders (e.g. filter("a",
     * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A
     * list of new encoders is returned.
     */    Ts(e, t, n) {
        const r = [ ...e ], i = [];
        for (const e of n.arrayValue.values || []) for (const n of r) {
            const r = new __PRIVATE_IndexByteEncoder;
            r.seed(n.Ci()), __PRIVATE_FirestoreIndexValueWriter.Ti.Xr(e, r.Oi(t.kind)), i.push(r);
        }
        return i;
    }
    hs(e, t) {
        return !!e.filters.find((e => e instanceof FieldFilter && e.field.isEqual(t) && ("in" /* Operator.IN */ === e.op || "not-in" /* Operator.NOT_IN */ === e.op)));
    }
    getFieldIndexes(e, t) {
        const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e);
        return (t ? n.Kn(Dn, IDBKeyRange.bound(t, t)) : n.Kn()).next((e => {
            const t = [];
            return PersistencePromise.forEach(e, (e => r.get([ e.indexId, this.uid ]).next((n => {
                t.push(function __PRIVATE_fromDbIndexConfiguration(e, t) {
                    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(Oe.fromServerFormat(e), t)));
                    return new FieldIndex(e.indexId, e.collectionGroup, r, n);
                }(e, n));
            })))).next((() => t));
        }));
    }
    getNextCollectionGroupToUpdate(e) {
        return this.getFieldIndexes(e).next((e => 0 === e.length ? null : (e.sort(((e, t) => {
            const n = e.indexState.sequenceNumber - t.indexState.sequenceNumber;
            return 0 !== n ? n : __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup);
        })), e[0].collectionGroup)));
    }
    updateCollectionGroup(e, t, n) {
        const r = __PRIVATE_indexConfigurationStore(e), i = __PRIVATE_indexStateStore(e);
        return this.Rs(e).next((e => r.Kn(Dn, IDBKeyRange.bound(t, t)).next((t => PersistencePromise.forEach(t, (t => i.put(__PRIVATE_toDbIndexState(t.indexId, this.uid, e, n))))))));
    }
    updateIndexEntries(e, t) {
        // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as
        // it could be used across different IndexedDB transactions. As any cached
        // data might be invalidated by other multi-tab clients, we can only trust
        // data within a single IndexedDB transaction. We therefore add a cache
        // here.
        const n = new Map;
        return PersistencePromise.forEach(t, ((t, r) => {
            const i = n.get(t.collectionGroup);
            return (i ? PersistencePromise.resolve(i) : this.getFieldIndexes(e, t.collectionGroup)).next((i => (n.set(t.collectionGroup, i), 
            PersistencePromise.forEach(i, (n => this.Is(e, t, n).next((t => {
                const i = this.As(r, n);
                return t.isEqual(i) ? PersistencePromise.resolve() : this.Vs(e, r, n, t, i);
            })))))));
        }));
    }
    ds(e, t, n, r) {
        return __PRIVATE_indexEntriesStore(e).put(r.ki(this.uid, this.Es(n, t.key), t.key));
    }
    fs(e, t, n, r) {
        return __PRIVATE_indexEntriesStore(e).delete(r.qi(this.uid, this.Es(n, t.key), t.key));
    }
    Is(e, t, n) {
        const r = __PRIVATE_indexEntriesStore(e);
        let i = new SortedSet(__PRIVATE_indexEntryComparator);
        return r.jn({
            index: Bn,
            range: IDBKeyRange.only([ n.indexId, this.uid, __PRIVATE_encodeKeySafeBytes(this.Es(n, t)) ])
        }, ((e, r) => {
            i = i.add(new __PRIVATE_IndexEntry(n.indexId, t, __PRIVATE_decodeKeySafeBytes(r.arrayValue), __PRIVATE_decodeKeySafeBytes(r.directionalValue)));
        })).next((() => i));
    }
    /** Creates the index entries for the given document. */    As(e, t) {
        let n = new SortedSet(__PRIVATE_indexEntryComparator);
        const r = this.ls(t, e);
        if (null == r) return n;
        const i = __PRIVATE_fieldIndexGetArraySegment(t);
        if (null != i) {
            const s = e.data.field(i.fieldPath);
            if (isArray(s)) for (const i of s.arrayValue.values || []) n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, this._s(i), r));
        } else n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, ir, r));
        return n;
    }
    /**
     * Updates the index entries for the provided document by deleting entries
     * that are no longer referenced in `newEntries` and adding all newly added
     * entries.
     */    Vs(e, t, n, r, i) {
        __PRIVATE_logDebug(rr, "Updating index entries for document '%s'", t.key);
        const s = [];
        return function __PRIVATE_diffSortedSets(e, t, n, r, i) {
            const s = e.getIterator(), _ = t.getIterator();
            let o = __PRIVATE_advanceIterator(s), a = __PRIVATE_advanceIterator(_);
            // Walk through the two sets at the same time, using the ordering defined by
            // `comparator`.
            for (;o || a; ) {
                let e = false, t = false;
                if (o && a) {
                    const r = n(o, a);
                    r < 0 ? 
                    // The element was removed if the next element in our ordered
                    // walkthrough is only in `before`.
                    t = true : r > 0 && (
                    // The element was added if the next element in our ordered walkthrough
                    // is only in `after`.
                    e = true);
                } else null != o ? t = true : e = true;
                e ? (r(a), a = __PRIVATE_advanceIterator(_)) : t ? (i(o), o = __PRIVATE_advanceIterator(s)) : (o = __PRIVATE_advanceIterator(s), 
                a = __PRIVATE_advanceIterator(_));
            }
        }(r, i, __PRIVATE_indexEntryComparator, (
        /* onAdd= */ r => {
            s.push(this.ds(e, t, n, r));
        }), (
        /* onRemove= */ r => {
            s.push(this.fs(e, t, n, r));
        })), PersistencePromise.waitFor(s);
    }
    Rs(e) {
        let t = 1;
        return __PRIVATE_indexStateStore(e).jn({
            index: On,
            reverse: true,
            range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])
        }, ((e, n, r) => {
            r.done(), t = n.sequenceNumber + 1;
        })).next((() => t));
    }
    /**
     * Returns a new set of IDB ranges that splits the existing range and excludes
     * any values that match the `notInValue` from these ranges. As an example,
     * '[foo > 2 && foo != 3]` becomes  `[foo > 2 && < 3, foo > 3]`.
     */    createRange(e, t, n) {
        // The notIn values need to be sorted and unique so that we can return a
        // sorted set of non-overlapping ranges.
        n = n.sort(((e, t) => __PRIVATE_indexEntryComparator(e, t))).filter(((e, t, n) => !t || 0 !== __PRIVATE_indexEntryComparator(e, n[t - 1])));
        const r = [];
        r.push(e);
        for (const i of n) {
            const n = __PRIVATE_indexEntryComparator(i, e), s = __PRIVATE_indexEntryComparator(i, t);
            if (0 === n) 
            // `notInValue` is the lower bound. We therefore need to raise the bound
            // to the next value.
            r[0] = e.Ui(); else if (n > 0 && s < 0) 
            // `notInValue` is in the middle of the range
            r.push(i), r.push(i.Ui()); else if (s > 0) 
            // `notInValue` (and all following values) are out of the range
            break;
        }
        r.push(t);
        const i = [];
        for (let e = 0; e < r.length; e += 2) {
            // If we encounter two bounds that will create an unmatchable key range,
            // then we return an empty set of key ranges.
            if (this.ps(r[e], r[e + 1])) return [];
            const t = r[e].qi(this.uid, ir, DocumentKey.empty()), n = r[e + 1].qi(this.uid, ir, DocumentKey.empty());
            i.push(IDBKeyRange.bound(t, n));
        }
        return i;
    }
    ps(e, t) {
        // If lower bound is greater than the upper bound, then the key
        // range can never be matched.
        return __PRIVATE_indexEntryComparator(e, t) > 0;
    }
    getMinOffsetFromCollectionGroup(e, t) {
        return this.getFieldIndexes(e, t).next(__PRIVATE_getMinOffsetFromFieldIndexes);
    }
    getMinOffset(e, t) {
        return PersistencePromise.mapArray(this.es(t), (t => this.ts(e, t).next((e => e || l(44426))))).next(__PRIVATE_getMinOffsetFromFieldIndexes);
    }
}

/**
 * Helper to get a typed SimpleDbStore for the collectionParents
 * document store.
 */ function __PRIVATE_collectionParentsStore(e) {
    return __PRIVATE_getStore(e, dn);
}

/**
 * Helper to get a typed SimpleDbStore for the index entry object store.
 */ function __PRIVATE_indexEntriesStore(e) {
    return __PRIVATE_getStore(e, Nn);
}

/**
 * Helper to get a typed SimpleDbStore for the index configuration object store.
 */ function __PRIVATE_indexConfigurationStore(e) {
    return __PRIVATE_getStore(e, vn);
}

/**
 * Helper to get a typed SimpleDbStore for the index state object store.
 */ function __PRIVATE_indexStateStore(e) {
    return __PRIVATE_getStore(e, Cn);
}

function __PRIVATE_getMinOffsetFromFieldIndexes(e) {
    __PRIVATE_hardAssert(0 !== e.length, 28825);
    let t = e[0].indexState.offset, n = t.largestBatchId;
    for (let r = 1; r < e.length; r++) {
        const i = e[r].indexState.offset;
        __PRIVATE_indexOffsetComparator(i, t) < 0 && (t = i), n < i.largestBatchId && (n = i.largestBatchId);
    }
    return new IndexOffset(t.readTime, t.documentKey, n);
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Offset to ensure non-overlapping target ids. */
/**
 * Generates monotonically increasing target IDs for sending targets to the
 * watch stream.
 *
 * The client constructs two generators, one for the target cache, and one for
 * for the sync engine (to generate limbo documents targets). These
 * generators produce non-overlapping IDs (by using even and odd IDs
 * respectively).
 *
 * By separating the target ID space, the query cache can generate target IDs
 * that persist across client restarts, while sync engine can independently
 * generate in-memory target IDs that are transient and can be reused after a
 * restart.
 */
class __PRIVATE_TargetIdGenerator {
    constructor(e) {
        this.gs = e;
    }
    next() {
        return this.gs += 2, this.gs;
    }
    static ys() {
        // The target cache generator must return '2' in its first call to `next()`
        // as there is no differentiation in the protocol layer between an unset
        // number and the number '0'. If we were to sent a target with target ID
        // '0', the backend would consider it unset and replace it with its own ID.
        return new __PRIVATE_TargetIdGenerator(0);
    }
    static ws() {
        // Sync engine assigns target IDs for limbo document detection.
        return new __PRIVATE_TargetIdGenerator(-1);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_IndexedDbTargetCache {
    constructor(e, t) {
        this.referenceDelegate = e, this.serializer = t;
    }
    // PORTING NOTE: We don't cache global metadata for the target cache, since
    // some of it (in particular `highestTargetId`) can be modified by secondary
    // tabs. We could perhaps be more granular (and e.g. still cache
    // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go
    // to IndexedDb whenever we need to read metadata. We can revisit if it turns
    // out to have a meaningful performance impact.
    allocateTargetId(e) {
        return this.bs(e).next((t => {
            const n = new __PRIVATE_TargetIdGenerator(t.highestTargetId);
            return t.highestTargetId = n.next(), this.vs(e, t).next((() => t.highestTargetId));
        }));
    }
    getLastRemoteSnapshotVersion(e) {
        return this.bs(e).next((e => SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds, e.lastRemoteSnapshotVersion.nanoseconds))));
    }
    getHighestSequenceNumber(e) {
        return this.bs(e).next((e => e.highestListenSequenceNumber));
    }
    setTargetsMetadata(e, t, n) {
        return this.bs(e).next((r => (r.highestListenSequenceNumber = t, n && (r.lastRemoteSnapshotVersion = n.toTimestamp()), 
        t > r.highestListenSequenceNumber && (r.highestListenSequenceNumber = t), this.vs(e, r))));
    }
    addTargetData(e, t) {
        return this.Ss(e, t).next((() => this.bs(e).next((n => (n.targetCount += 1, this.Ds(t, n), 
        this.vs(e, n))))));
    }
    updateTargetData(e, t) {
        return this.Ss(e, t);
    }
    removeTargetData(e, t) {
        return this.removeMatchingKeysForTargetId(e, t.targetId).next((() => __PRIVATE_targetsStore(e).delete(t.targetId))).next((() => this.bs(e))).next((t => (__PRIVATE_hardAssert(t.targetCount > 0, 8065), 
        t.targetCount -= 1, this.vs(e, t))));
    }
    /**
     * Drops any targets with sequence number less than or equal to the upper bound, excepting those
     * present in `activeTargetIds`. Document associations for the removed targets are also removed.
     * Returns the number of targets removed.
     */    removeTargets(e, t, n) {
        let r = 0;
        const i = [];
        return __PRIVATE_targetsStore(e).jn(((s, _) => {
            const o = __PRIVATE_fromDbTarget(this.serializer, _);
            o.sequenceNumber <= t && null === n.get(o.targetId) && (r++, i.push(this.removeTargetData(e, o)));
        })).next((() => PersistencePromise.waitFor(i))).next((() => r));
    }
    /**
     * Call provided function with each `TargetData` that we have cached.
     */    forEachTarget(e, t) {
        return __PRIVATE_targetsStore(e).jn(((e, n) => {
            const r = __PRIVATE_fromDbTarget(this.serializer, n);
            t(r);
        }));
    }
    bs(e) {
        return __PRIVATE_globalTargetStore(e).get(An).next((e => (__PRIVATE_hardAssert(null !== e, 2888), 
        e)));
    }
    vs(e, t) {
        return __PRIVATE_globalTargetStore(e).put(An, t);
    }
    Ss(e, t) {
        return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer, t));
    }
    /**
     * In-place updates the provided metadata to account for values in the given
     * TargetData. Saving is done separately. Returns true if there were any
     * changes to the metadata.
     */    Ds(e, t) {
        let n = false;
        return e.targetId > t.highestTargetId && (t.highestTargetId = e.targetId, n = true), 
        e.sequenceNumber > t.highestListenSequenceNumber && (t.highestListenSequenceNumber = e.sequenceNumber, 
        n = true), n;
    }
    getTargetCount(e) {
        return this.bs(e).next((e => e.targetCount));
    }
    getTargetData(e, t) {
        // Iterating by the canonicalId may yield more than one result because
        // canonicalId values are not required to be unique per target. This query
        // depends on the queryTargets index to be efficient.
        const n = __PRIVATE_canonifyTargetOrPipeline(t), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);
        let i = null;
        return __PRIVATE_targetsStore(e).jn({
            range: r,
            index: En
        }, ((e, n, r) => {
            const s = __PRIVATE_fromDbTarget(this.serializer, n);
            // After finding a potential match, check that the target is
            // actually equal to the requested target.
                        __PRIVATE_targetOrPipelineEqual(t, s.target) && (i = s, r.done());
        })).next((() => i));
    }
    addMatchingKeys(e, t, n) {
        // PORTING NOTE: The reverse index (documentsTargets) is maintained by
        // IndexedDb.
        const r = [], i = __PRIVATE_documentTargetStore(e);
        return t.forEach((t => {
            const s = __PRIVATE_encodeResourcePath(t.path);
            r.push(i.put({
                targetId: n,
                path: s
            })), r.push(this.referenceDelegate.addReference(e, n, t));
        })), PersistencePromise.waitFor(r);
    }
    removeMatchingKeys(e, t, n) {
        // PORTING NOTE: The reverse index (documentsTargets) is maintained by
        // IndexedDb.
        const r = __PRIVATE_documentTargetStore(e);
        return PersistencePromise.forEach(t, (t => {
            const i = __PRIVATE_encodeResourcePath(t.path);
            return PersistencePromise.waitFor([ r.delete([ n, i ]), this.referenceDelegate.removeReference(e, n, t) ]);
        }));
    }
    removeMatchingKeysForTargetId(e, t) {
        const n = __PRIVATE_documentTargetStore(e), r = IDBKeyRange.bound([ t ], [ t + 1 ], 
        /*lowerOpen=*/ false, 
        /*upperOpen=*/ true);
        return n.delete(r);
    }
    getMatchingKeysForTargetId(e, t) {
        const n = IDBKeyRange.bound([ t ], [ t + 1 ], 
        /*lowerOpen=*/ false, 
        /*upperOpen=*/ true), r = __PRIVATE_documentTargetStore(e);
        let i = __PRIVATE_documentKeySet();
        return r.jn({
            range: n,
            zn: true
        }, ((e, t, n) => {
            const r = __PRIVATE_decodeResourcePath(e[1]), s = new DocumentKey(r);
            i = i.add(s);
        })).next((() => i));
    }
    containsKey(e, t) {
        const n = __PRIVATE_encodeResourcePath(t.path), r = IDBKeyRange.bound([ n ], [ __PRIVATE_immediateSuccessor(n) ], 
        /*lowerOpen=*/ false, 
        /*upperOpen=*/ true);
        let i = 0;
        return __PRIVATE_documentTargetStore(e).jn({
            index: Rn,
            zn: true,
            range: r
        }, (([e, t], n, r) => {
            // Having a sentinel row for a document does not count as containing that document;
            // For the target cache, containing the document means the document is part of some
            // target.
            0 !== e && (i++, r.done());
        })).next((() => i > 0));
    }
    /**
     * Looks up a TargetData entry by target ID.
     *
     * @param targetId - The target ID of the TargetData entry to look up.
     * @returns The cached TargetData entry, or null if the cache has no entry for
     * the target.
     */
    // PORTING NOTE: Multi-tab only.
    ge(e, t) {
        return __PRIVATE_targetsStore(e).get(t).next((e => e ? __PRIVATE_fromDbTarget(this.serializer, e) : null));
    }
}

/**
 * Helper to get a typed SimpleDbStore for the queries object store.
 */ function __PRIVATE_targetsStore(e) {
    return __PRIVATE_getStore(e, cn);
}

/**
 * Helper to get a typed SimpleDbStore for the target globals object store.
 */ function __PRIVATE_globalTargetStore(e) {
    return __PRIVATE_getStore(e, Vn);
}

/**
 * Helper to get a typed SimpleDbStore for the document target object store.
 */ function __PRIVATE_documentTargetStore(e) {
    return __PRIVATE_getStore(e, Tn);
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Provides LRU functionality for IndexedDB persistence. */ class __PRIVATE_IndexedDbLruDelegateImpl {
    constructor(e, t) {
        this.db = e, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);
    }
    rr(e) {
        const t = this.xs(e);
        return this.db.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t))));
    }
    xs(e) {
        let t = 0;
        return this.ir(e, (e => {
            t++;
        })).next((() => t));
    }
    forEachTarget(e, t) {
        return this.db.getTargetCache().forEachTarget(e, t);
    }
    ir(e, t) {
        return this.Cs(e, ((e, n) => t(n)));
    }
    addReference(e, t, n) {
        return __PRIVATE_writeSentinelKey(e, n);
    }
    removeReference(e, t, n) {
        return __PRIVATE_writeSentinelKey(e, n);
    }
    removeTargets(e, t, n) {
        return this.db.getTargetCache().removeTargets(e, t, n);
    }
    markPotentiallyOrphaned(e, t) {
        return __PRIVATE_writeSentinelKey(e, t);
    }
    /**
     * Returns true if anything would prevent this document from being garbage
     * collected, given that the document in question is not present in any
     * targets and has a sequence number less than or equal to the upper bound for
     * the collection run.
     */    Fs(e, t) {
        return function __PRIVATE_mutationQueuesContainKey(e, t) {
            let n = false;
            return __PRIVATE_mutationQueuesStore(e).Hn((r => __PRIVATE_mutationQueueContainsKey(e, r, t).next((e => (e && (n = true), 
            PersistencePromise.resolve(!e)))))).next((() => n));
        }(e, t);
    }
    removeOrphanedDocuments(e, t) {
        const n = this.db.getRemoteDocumentCache().newChangeBuffer(), r = [];
        let i = 0;
        return this.Cs(e, ((s, _) => {
            if (_ <= t) {
                const t = this.Fs(e, s).next((t => {
                    if (!t) 
                    // Our size accounting requires us to read all documents before
                    // removing them.
                    return i++, n.getEntry(e, s).next((() => (n.removeEntry(s, SnapshotVersion.min()), 
                    __PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e) {
                        return [ 0, __PRIVATE_encodeResourcePath(e.path) ];
                    }
                    /**
 * @returns A value suitable for writing a sentinel row in the target-document
 * store.
 */ (s)))));
                }));
                r.push(t);
            }
        })).next((() => PersistencePromise.waitFor(r))).next((() => n.apply(e))).next((() => i));
    }
    removeTarget(e, t) {
        const n = t.withSequenceNumber(e.currentSequenceNumber);
        return this.db.getTargetCache().updateTargetData(e, n);
    }
    updateLimboDocument(e, t) {
        return __PRIVATE_writeSentinelKey(e, t);
    }
    /**
     * Call provided function for each document in the cache that is 'orphaned'. Orphaned
     * means not a part of any target, so the only entry in the target-document index for
     * that document will be the sentinel row (targetId 0), which will also have the sequence
     * number for the last time the document was accessed.
     */    Cs(e, t) {
        const n = __PRIVATE_documentTargetStore(e);
        let r, i = __PRIVATE_ListenSequence.yn;
        return n.jn({
            index: Rn
        }, (([e, n], {path: s, sequenceNumber: _}) => {
            0 === e ? (
            // if nextToReport is valid, report it, this is a new key so the
            // last one must not be a member of any targets.
            i !== __PRIVATE_ListenSequence.yn && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i), 
            // set nextToReport to be this sequence number. It's the next one we
            // might report, if we don't find any targets for this document.
            // Note that the sequence number must be defined when the targetId
            // is 0.
            i = _, r = s) : 
            // set nextToReport to be invalid, we know we don't need to report
            // this one since we found a target for it.
            i = __PRIVATE_ListenSequence.yn;
        })).next((() => {
            // Since we report sequence numbers after getting to the next key, we
            // need to check if the last key we iterated over was an orphaned
            // document and report it.
            i !== __PRIVATE_ListenSequence.yn && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i);
        }));
    }
    getCacheSize(e) {
        return this.db.getRemoteDocumentCache().getSize(e);
    }
}

function __PRIVATE_writeSentinelKey(e, t) {
    return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e, t) {
        return {
            targetId: 0,
            path: __PRIVATE_encodeResourcePath(e.path),
            sequenceNumber: t
        };
    }(t, e.currentSequenceNumber));
}

// Copyright 2024 Google LLC* @license
// Copyright 2024 Google LLC

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at

//      http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
function __PRIVATE_runPipeline(e, t) {
    let n = t;
    for (const t of e.stages) n = evaluate({
        serializer: e.serializer,
        serverTimestampBehavior: e.listenOptions?.serverTimestampBehavior
    }, t, n);
    return n;
}

function __PRIVATE_pipelineMatches(e, t) {
    // TODO(pipeline): this is not true for aggregations, and we need to examine if there are other
    // stages that will not work this way.
    return __PRIVATE_runPipeline(e, [ t ]).length > 0;
}

function __PRIVATE_queryOrPipelineMatches(e, t) {
    return __PRIVATE_isPipeline(e) ? __PRIVATE_pipelineMatches(e, t) : __PRIVATE_queryMatches(e, t);
}

function evaluate(e, t, n) {
    if (t instanceof H) return function __PRIVATE_evaluateCollection(e, t, n) {
        return n.filter((e => e.isFoundDocument() && `/${e.key.getCollectionPath().canonicalString()}` === t.Er));
    }(0, t, n);
    if (t instanceof A) return function __PRIVATE_evaluateWhere(e, t, n) {
        return n.filter((n => {
            const r = __PRIVATE_valueOrUndefined(__PRIVATE_toEvaluable(t.condition).evaluate(e, n));
            return void 0 !== r && __PRIVATE_valueEquals$1(r, Je);
        }));
    }(e, t, n);
    if (t instanceof J) return function __PRIVATE_evaluateCollectionGroup(e, t, n) {
        // return those records in input whose collection id is stage.collectionId
        return n.filter((e => e.isFoundDocument() && e.key.getCollectionPath().lastSegment() === t.collectionId));
    }(0, t, n);
    if (t instanceof Q) return function __PRIVATE_evaluateDatabase(e, t, n) {
        return n.filter((e => e.isFoundDocument()));
    }(0, 0, n);
    if (t instanceof Y) return function __PRIVATE_evaluateDocuments(e, t, n) {
        return n.filter((e => e.isFoundDocument() && t.Tr.has(e.key.path.toStringWithLeadingSlash())));
    }(0, t, n);
    if (t instanceof v) return function __PRIVATE_evaluateLimit(e, t, n) {
        return n.slice(0, t.limit);
    }
    // function evaluateOffset(
    //   context: EvaluationContext,
    //   stage: Offset,
    //   input: PipelineInputOutput[]
    // ): PipelineInputOutput[] {
    //   return input.slice((stage as any).offset);
    // }
    (0, t, n);
    if (t instanceof L) return function __PRIVATE_evaluateSort(e, t, n) {
        const r = t.orderings.map((e => ({
            Os: __PRIVATE_toEvaluable(e.expr),
            direction: e.direction
        })));
        return [ ...n ].sort(((t, n) => {
            // Evaluate expressions in stage.orderings against left and right, and use them to compare
            // the documents
            for (const {Os: i, direction: s} of r) {
                const r = __PRIVATE_valueOrUndefined(i.evaluate(e, t)), _ = __PRIVATE_valueOrUndefined(i.evaluate(e, n)), o = __PRIVATE_valueCompare(r ?? He, _ ?? He);
                if (0 !== o) 
                // Return the comparison result if documents are not equal
                return "ascending" === s ? o : -o;
            }
            return 0;
        }));
    }(e, t, n);
    throw new Error(`Unknown stage: ${t._name}`);
}

function __PRIVATE_newPipelineComparator(e) {
    const t = function __PRIVATE_lastEffectiveSort(e) {
        // return the last sort stage, throws exception if it doesn't exist
        // TODO(pipeline): this implementation is wrong, there are stages that can invalidate
        // the orderings later. The proper way to manipulate the pipeline so that last Sort
        // always has effects.
        for (let t = e.stages.length - 1; t >= 0; t--) {
            const n = e.stages[t];
            if (n instanceof L) return n.orderings;
        }
        throw new Error("Pipeline must contain at least one Sort stage");
    }(e);
    return (n, r) => {
        for (const i of t) {
            // TODO(pipeline): consider the possibility of memoizing the evaluation
            const t = __PRIVATE_valueOrUndefined(__PRIVATE_toEvaluable(i.expr).evaluate({
                serializer: e.serializer
            }, n)), s = __PRIVATE_valueOrUndefined(__PRIVATE_toEvaluable(i.expr).evaluate({
                serializer: e.serializer
            }, r)), _ = __PRIVATE_valueCompare(t || He, s || He);
            if (0 !== _) return "ascending" === i.direction ? _ : -_;
        }
        return 0;
    };
}

function __PRIVATE_getLastEffectiveLimit(e) {
    // TODO(pipeline): Consider other stages that might imply a limit,
    // e.g., FindNearestStage, once they are implemented.
    for (let t = e.stages.length - 1; t >= 0; t--) {
        const n = e.stages[t];
        if (n instanceof v) return {
            limit: n.limit
        };
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An in-memory buffer of entries to be written to a RemoteDocumentCache.
 * It can be used to batch up a set of changes to be written to the cache, but
 * additionally supports reading entries back with the `getEntry()` method,
 * falling back to the underlying RemoteDocumentCache if no entry is
 * buffered.
 *
 * Entries added to the cache *must* be read first. This is to facilitate
 * calculating the size delta of the pending changes.
 *
 * PORTING NOTE: This class was implemented then removed from other platforms.
 * If byte-counting ends up being needed on the other platforms, consider
 * porting this class as part of that implementation work.
 */ class RemoteDocumentChangeBuffer {
    constructor() {
        // A mapping of document key to the new cache entry that should be written.
        this.changes = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))), this.changesApplied = false;
    }
    /**
     * Buffers a `RemoteDocumentCache.addEntry()` call.
     *
     * You can only modify documents that have already been retrieved via
     * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
     */    addEntry(e) {
        this.assertNotApplied(), this.changes.set(e.key, e);
    }
    /**
     * Buffers a `RemoteDocumentCache.removeEntry()` call.
     *
     * You can only remove documents that have already been retrieved via
     * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
     */    removeEntry(e, t) {
        this.assertNotApplied(), this.changes.set(e, MutableDocument.newInvalidDocument(e).setReadTime(t));
    }
    /**
     * Looks up an entry in the cache. The buffered changes will first be checked,
     * and if no buffered change applies, this will forward to
     * `RemoteDocumentCache.getEntry()`.
     *
     * @param transaction - The transaction in which to perform any persistence
     *     operations.
     * @param documentKey - The key of the entry to look up.
     * @returns The cached document or an invalid document if we have nothing
     * cached.
     */    getEntry(e, t) {
        this.assertNotApplied();
        const n = this.changes.get(t);
        return void 0 !== n ? PersistencePromise.resolve(n) : this.getFromCache(e, t);
    }
    /**
     * Looks up several entries in the cache, forwarding to
     * `RemoteDocumentCache.getEntry()`.
     *
     * @param transaction - The transaction in which to perform any persistence
     *     operations.
     * @param documentKeys - The keys of the entries to look up.
     * @returns A map of cached documents, indexed by key. If an entry cannot be
     *     found, the corresponding key will be mapped to an invalid document.
     */    getEntries(e, t) {
        return this.getAllFromCache(e, t);
    }
    /**
     * Applies buffered changes to the underlying RemoteDocumentCache, using
     * the provided transaction.
     */    apply(e) {
        return this.assertNotApplied(), this.changesApplied = true, this.applyChanges(e);
    }
    /** Helper to assert this.changes is not null  */    assertNotApplied() {}
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The RemoteDocumentCache for IndexedDb. To construct, invoke
 * `newIndexedDbRemoteDocumentCache()`.
 */ class __PRIVATE_IndexedDbRemoteDocumentCacheImpl {
    constructor(e) {
        this.serializer = e;
    }
    setIndexManager(e) {
        this.indexManager = e;
    }
    /**
     * Adds the supplied entries to the cache.
     *
     * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer
     * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
     */    addEntry(e, t, n) {
        return __PRIVATE_remoteDocumentsStore(e).put(n);
    }
    /**
     * Removes a document from the cache.
     *
     * All calls of `removeEntry`  are required to go through the RemoteDocumentChangeBuffer
     * returned by `newChangeBuffer()` to ensure proper accounting of metadata.
     */    removeEntry(e, t, n) {
        return __PRIVATE_remoteDocumentsStore(e).delete(
        /**
 * Returns a key that can be used for document lookups via the primary key of
 * the DbRemoteDocument object store.
 */
        function __PRIVATE_dbReadTimeKey(e, t) {
            const n = e.path.toArray();
            return [ 
            /* prefix path */ n.slice(0, n.length - 2), 
            /* collection id */ n[n.length - 2], __PRIVATE_toDbTimestampKey(t), 
            /* document id */ n[n.length - 1] ];
        }
        /**
 * Returns a key that can be used for document lookups on the
 * `DbRemoteDocumentDocumentCollectionGroupIndex` index.
 */ (t, n));
    }
    /**
     * Updates the current cache size.
     *
     * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
     * cache's metadata.
     */    updateMetadata(e, t) {
        return this.getMetadata(e).next((n => (n.byteSize += t, this.Ms(e, n))));
    }
    getEntry(e, t) {
        let n = MutableDocument.newInvalidDocument(t);
        return __PRIVATE_remoteDocumentsStore(e).jn({
            index: rn,
            range: IDBKeyRange.only(__PRIVATE_dbKey(t))
        }, ((e, r) => {
            n = this.Ns(t, r);
        })).next((() => n));
    }
    /**
     * Looks up an entry in the cache.
     *
     * @param documentKey - The key of the entry to look up.
     * @returns The cached document entry and its size.
     */    Ls(e, t) {
        let n = {
            size: 0,
            document: MutableDocument.newInvalidDocument(t)
        };
        return __PRIVATE_remoteDocumentsStore(e).jn({
            index: rn,
            range: IDBKeyRange.only(__PRIVATE_dbKey(t))
        }, ((e, r) => {
            n = {
                document: this.Ns(t, r),
                size: __PRIVATE_dbDocumentSize(r)
            };
        })).next((() => n));
    }
    getEntries(e, t) {
        let n = __PRIVATE_mutableDocumentMap();
        return this.Bs(e, t, ((e, t) => {
            const r = this.Ns(e, t);
            n = n.insert(e, r);
        })).next((() => n));
    }
    getAllEntries(e) {
        let t = __PRIVATE_mutableDocumentMap();
        return __PRIVATE_remoteDocumentsStore(e).jn(((e, n) => {
            const r = this.Ns(DocumentKey.fromSegments(n.prefixPath.concat(n.collectionGroup, n.documentId)), n);
            t = t.insert(r.key, r);
        })).next((() => t));
    }
    /**
     * Looks up several entries in the cache.
     *
     * @param documentKeys - The set of keys entries to look up.
     * @returns A map of documents indexed by key and a map of sizes indexed by
     *     key (zero if the document does not exist).
     */    Us(e, t) {
        let n = __PRIVATE_mutableDocumentMap(), r = new SortedMap(DocumentKey.comparator);
        return this.Bs(e, t, ((e, t) => {
            const i = this.Ns(e, t);
            n = n.insert(e, i), r = r.insert(e, __PRIVATE_dbDocumentSize(t));
        })).next((() => ({
            documents: n,
            ks: r
        })));
    }
    Bs(e, t, n) {
        if (t.isEmpty()) return PersistencePromise.resolve();
        let r = new SortedSet(__PRIVATE_dbKeyComparator);
        t.forEach((e => r = r.add(e)));
        const i = IDBKeyRange.bound(__PRIVATE_dbKey(r.first()), __PRIVATE_dbKey(r.last())), s = r.getIterator();
        let _ = s.getNext();
        return __PRIVATE_remoteDocumentsStore(e).jn({
            index: rn,
            range: i
        }, ((e, t, r) => {
            const i = DocumentKey.fromSegments([ ...t.prefixPath, t.collectionGroup, t.documentId ]);
            // Go through keys not found in cache.
                        for (;_ && __PRIVATE_dbKeyComparator(_, i) < 0; ) n(_, null), _ = s.getNext();
            _ && _.isEqual(i) && (
            // Key found in cache.
            n(_, t), _ = s.hasNext() ? s.getNext() : null), 
            // Skip to the next key (if there is one).
            _ ? r.$n(__PRIVATE_dbKey(_)) : r.done();
        })).next((() => {
            // The rest of the keys are not in the cache. One case where `iterate`
            // above won't go through them is when the cache is empty.
            for (;_; ) n(_, null), _ = s.hasNext() ? s.getNext() : null;
        }));
    }
    getDocumentsMatchingQuery(e, t, n, r, i) {
        const s = __PRIVATE_isPipeline(t) ? ResourcePath.fromString(getPipelineCollection(t)) : t.path, _ = [ s.popLast().toArray(), s.lastSegment(), __PRIVATE_toDbTimestampKey(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], o = [ s.popLast().toArray(), s.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ];
        return __PRIVATE_remoteDocumentsStore(e).Kn(IDBKeyRange.bound(_, o, true)).next((e => {
            i?.incrementDocumentReadCount(e.length);
            let n = __PRIVATE_mutableDocumentMap();
            for (const i of e) {
                const e = this.Ns(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i);
                e.isFoundDocument() && (__PRIVATE_queryOrPipelineMatches(t, e) || r.has(e.key)) && (
                // Either the document matches the given query, or it is mutated.
                n = n.insert(e.key, e));
            }
            return n;
        }));
    }
    getAllFromCollectionGroup(e, t, n, r) {
        let i = __PRIVATE_mutableDocumentMap();
        const s = __PRIVATE_dbCollectionGroupKey(t, n), _ = __PRIVATE_dbCollectionGroupKey(t, IndexOffset.max());
        return __PRIVATE_remoteDocumentsStore(e).jn({
            index: _n,
            range: IDBKeyRange.bound(s, _, true)
        }, ((e, t, n) => {
            const s = this.Ns(DocumentKey.fromSegments(t.prefixPath.concat(t.collectionGroup, t.documentId)), t);
            i = i.insert(s.key, s), i.size === r && n.done();
        })).next((() => i));
    }
    newChangeBuffer(e) {
        return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e && e.trackRemovals);
    }
    getSize(e) {
        return this.getMetadata(e).next((e => e.byteSize));
    }
    getMetadata(e) {
        return __PRIVATE_documentGlobalStore(e).get(un).next((e => (__PRIVATE_hardAssert(!!e, 20021), 
        e)));
    }
    Ms(e, t) {
        return __PRIVATE_documentGlobalStore(e).put(un, t);
    }
    /**
     * Decodes `dbRemoteDoc` and returns the document (or an invalid document if
     * the document corresponds to the format used for sentinel deletes).
     */    Ns(e, t) {
        if (t) {
            const e = __PRIVATE_fromDbRemoteDocument(this.serializer, t);
            // Whether the document is a sentinel removal and should only be used in the
            // `getNewDocumentChanges()`
                        if (!(e.isNoDocument() && e.version.isEqual(SnapshotVersion.min()))) return e;
        }
        return MutableDocument.newInvalidDocument(e);
    }
}

/** Creates a new IndexedDbRemoteDocumentCache. */ function __PRIVATE_newIndexedDbRemoteDocumentCache(e) {
    return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e);
}

/**
 * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.
 *
 * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size
 * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb
 * when we apply the changes.
 */ class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {
    /**
     * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.
     * @param trackRemovals - Whether to create sentinel deletes that can be tracked by
     * `getNewDocumentChanges()`.
     */
    constructor(e, t) {
        super(), this.qs = e, this.trackRemovals = t, 
        // A map of document sizes and read times prior to applying the changes in
        // this buffer.
        this.$s = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t)));
    }
    applyChanges(e) {
        const t = [];
        let n = 0, r = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString())));
        return this.changes.forEach(((i, s) => {
            const _ = this.$s.get(i);
            if (t.push(this.qs.removeEntry(e, i, _.readTime)), s.isValidDocument()) {
                const o = __PRIVATE_toDbRemoteDocument(this.qs.serializer, s);
                r = r.add(i.path.popLast());
                const a = __PRIVATE_dbDocumentSize(o);
                n += a - _.size, t.push(this.qs.addEntry(e, i, o));
            } else if (n -= _.size, this.trackRemovals) {
                // In order to track removals, we store a "sentinel delete" in the
                // RemoteDocumentCache. This entry is represented by a NoDocument
                // with a version of 0 and ignored by `maybeDecodeDocument()` but
                // preserved in `getNewDocumentChanges()`.
                const n = __PRIVATE_toDbRemoteDocument(this.qs.serializer, s.convertToNoDocument(SnapshotVersion.min()));
                t.push(this.qs.addEntry(e, i, n));
            }
        })), r.forEach((n => {
            t.push(this.qs.indexManager.addToCollectionParentIndex(e, n));
        })), t.push(this.qs.updateMetadata(e, n)), PersistencePromise.waitFor(t);
    }
    getFromCache(e, t) {
        // Record the size of everything we load from the cache so we can compute a delta later.
        return this.qs.Ls(e, t).next((e => (this.$s.set(t, {
            size: e.size,
            readTime: e.document.readTime
        }), e.document)));
    }
    getAllFromCache(e, t) {
        // Record the size of everything we load from the cache so we can compute
        // a delta later.
        return this.qs.Us(e, t).next((({documents: e, ks: t}) => (
        // Note: `getAllFromCache` returns two maps instead of a single map from
        // keys to `DocumentSizeEntry`s. This is to allow returning the
        // `MutableDocumentMap` directly, without a conversion.
        t.forEach(((t, n) => {
            this.$s.set(t, {
                size: n,
                readTime: e.get(t).readTime
            });
        })), e)));
    }
}

function __PRIVATE_documentGlobalStore(e) {
    return __PRIVATE_getStore(e, an);
}

/**
 * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
 */ function __PRIVATE_remoteDocumentsStore(e) {
    return __PRIVATE_getStore(e, tn);
}

/**
 * Returns a key that can be used for document lookups on the
 * `DbRemoteDocumentDocumentKeyIndex` index.
 */ function __PRIVATE_dbKey(e) {
    const t = e.path.toArray();
    return [ 
    /* prefix path */ t.slice(0, t.length - 2), 
    /* collection id */ t[t.length - 2], 
    /* document id */ t[t.length - 1] ];
}

function __PRIVATE_dbCollectionGroupKey(e, t) {
    const n = t.documentKey.path.toArray();
    return [ 
    /* collection id */ e, __PRIVATE_toDbTimestampKey(t.readTime), 
    /* prefix path */ n.slice(0, n.length - 2), 
    /* document id */ n.length > 0 ? n[n.length - 1] : "" ];
}

/**
 * Comparator that compares document keys according to the primary key sorting
 * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id
 * and then document ID).
 *
 * Visible for testing.
 */ function __PRIVATE_dbKeyComparator(e, t) {
    const n = e.path.toArray(), r = t.path.toArray();
    // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74
    let i = 0;
    for (let e = 0; e < n.length - 2 && e < r.length - 2; ++e) if (i = __PRIVATE_primitiveComparator(n[e], r[e]), 
    i) return i;
    return i = __PRIVATE_primitiveComparator(n.length, r.length), i || (i = __PRIVATE_primitiveComparator(n[n.length - 2], r[r.length - 2]), 
    i || __PRIVATE_primitiveComparator(n[n.length - 1], r[r.length - 1]));
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Schema Version for the Web client:
 * 1.  Initial version including Mutation Queue, Query Cache, and Remote
 *     Document Cache
 * 2.  Used to ensure a targetGlobal object exists and add targetCount to it. No
 *     longer required because migration 3 unconditionally clears it.
 * 3.  Dropped and re-created Query Cache to deal with cache corruption related
 *     to limbo resolution. Addresses
 *     https://github.com/firebase/firebase-ios-sdk/issues/1548
 * 4.  Multi-Tab Support.
 * 5.  Removal of held write acks.
 * 6.  Create document global for tracking document cache size.
 * 7.  Ensure every cached document has a sentinel row with a sequence number.
 * 8.  Add collection-parent index for Collection Group queries.
 * 9.  Change RemoteDocumentChanges store to be keyed by readTime rather than
 *     an auto-incrementing ID. This is required for Index-Free queries.
 * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.
 * 11. Add bundles and named_queries for bundle support.
 * 12. Add document overlays.
 * 13. Rewrite the keys of the remote document cache to allow for efficient
 *     document lookup via `getAll()`.
 * 14. Add overlays.
 * 15. Add indexing support.
 * 16. Parse timestamp strings before creating index entries.
 * 17. TODO(tomandersen)
 * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore.
 */
/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents a local view (overlay) of a document, and the fields that are
 * locally mutated.
 */
class OverlayedDocument {
    constructor(e, 
    /**
     * The fields that are locally mutated by patch mutations.
     *
     * If the overlayed	document is from set or delete mutations, this is `null`.
     * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.
     */
    t) {
        this.overlayedDocument = e, this.mutatedFields = t;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A readonly view of the local state of all documents we're tracking (i.e. we
 * have a cached version in remoteDocumentCache or local mutations for the
 * document). The view is computed by applying the mutations in the
 * MutationQueue to the RemoteDocumentCache.
 */ class LocalDocumentsView {
    constructor(e, t, n, r) {
        this.remoteDocumentCache = e, this.mutationQueue = t, this.documentOverlayCache = n, 
        this.indexManager = r;
    }
    /**
     * Get the local view of the document identified by `key`.
     *
     * @returns Local view of the document or null if we don't have any cached
     * state for it.
     */    getDocument(e, t) {
        let n = null;
        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()), 
        e)));
    }
    /**
     * Gets the local view of the documents identified by `keys`.
     *
     * If we don't have cached state for a document in `keys`, a NoDocument will
     * be stored for that key in the resulting set.
     */    getDocuments(e, t) {
        return this.remoteDocumentCache.getEntries(e, t).next((t => this.getLocalViewOfDocuments(e, t, __PRIVATE_documentKeySet()).next((() => t))));
    }
    /**
     * Similar to `getDocuments`, but creates the local view from the given
     * `baseDocs` without retrieving documents from the local store.
     *
     * @param transaction - The transaction this operation is scoped to.
     * @param docs - The documents to apply local mutations to get the local views.
     * @param existenceStateChanged - The set of document keys whose existence state
     *   is changed. This is useful to determine if some documents overlay needs
     *   to be recalculated.
     */    getLocalViewOfDocuments(e, t, n = __PRIVATE_documentKeySet()) {
        const r = __PRIVATE_newOverlayMap();
        return this.populateOverlays(e, r, t).next((() => this.computeViews(e, t, r, n).next((e => {
            let t = documentMap();
            return e.forEach(((e, n) => {
                t = t.insert(e, n.overlayedDocument);
            })), t;
        }))));
    }
    /**
     * Gets the overlayed documents for the given document map, which will include
     * the local view of those documents and a `FieldMask` indicating which fields
     * are mutated locally, `null` if overlay is a Set or Delete mutation.
     */    getOverlayedDocuments(e, t) {
        const n = __PRIVATE_newOverlayMap();
        return this.populateOverlays(e, n, t).next((() => this.computeViews(e, t, n, __PRIVATE_documentKeySet())));
    }
    /**
     * Fetches the overlays for {@code docs} and adds them to provided overlay map
     * if the map does not already contain an entry for the given document key.
     */    populateOverlays(e, t, n) {
        const r = [];
        return n.forEach((e => {
            t.has(e) || r.push(e);
        })), this.documentOverlayCache.getOverlays(e, r).next((e => {
            e.forEach(((e, n) => {
                t.set(e, n);
            }));
        }));
    }
    /**
     * Computes the local view for the given documents.
     *
     * @param docs - The documents to compute views for. It also has the base
     *   version of the documents.
     * @param overlays - The overlays that need to be applied to the given base
     *   version of the documents.
     * @param existenceStateChanged - A set of documents whose existence states
     *   might have changed. This is used to determine if we need to re-calculate
     *   overlays from mutation queues.
     * @returns A map represents the local documents view.
     */    computeViews(e, t, n, r) {
        let i = __PRIVATE_mutableDocumentMap();
        const s = __PRIVATE_newDocumentKeyMap(), _ = function __PRIVATE_newOverlayedDocumentMap() {
            return __PRIVATE_newDocumentKeyMap();
        }();
        return t.forEach(((e, t) => {
            const _ = n.get(t.key);
            // Recalculate an overlay if the document's existence state changed due to
            // a remote event *and* the overlay is a PatchMutation. This is because
            // document existence state can change if some patch mutation's
            // preconditions are met.
            // NOTE: we recalculate when `overlay` is undefined as well, because there
            // might be a patch mutation whose precondition does not match before the
            // change (hence overlay is undefined), but would now match.
                        r.has(t.key) && (void 0 === _ || _.mutation instanceof __PRIVATE_PatchMutation) ? i = i.insert(t.key, t) : void 0 !== _ ? (s.set(t.key, _.mutation.getFieldMask()), 
            __PRIVATE_mutationApplyToLocalView(_.mutation, t, _.mutation.getFieldMask(), Timestamp.now())) : 
            // no overlay exists
            // Using EMPTY to indicate there is no overlay for the document.
            s.set(t.key, FieldMask.empty());
        })), this.recalculateAndSaveOverlays(e, i).next((e => (e.forEach(((e, t) => s.set(e, t))), 
        t.forEach(((e, t) => _.set(e, new OverlayedDocument(t, s.get(e) ?? null)))), _)));
    }
    recalculateAndSaveOverlays(e, t) {
        const n = __PRIVATE_newDocumentKeyMap();
        // A reverse lookup map from batch id to the documents within that batch.
                let r = new SortedMap(((e, t) => e - t)), i = __PRIVATE_documentKeySet();
        return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e, t).next((e => {
            for (const i of e) i.keys().forEach((e => {
                const s = t.get(e);
                if (null === s) return;
                let _ = n.get(e) || FieldMask.empty();
                _ = i.applyToLocalView(s, _), n.set(e, _);
                const o = (r.get(i.batchId) || __PRIVATE_documentKeySet()).add(e);
                r = r.insert(i.batchId, o);
            }));
        })).next((() => {
            const s = [], _ = r.getReverseIterator();
            // Iterate in descending order of batch IDs, and skip documents that are
            // already saved.
                        for (;_.hasNext(); ) {
                const r = _.getNext(), o = r.key, a = r.value, u = __PRIVATE_newMutationMap();
                a.forEach((e => {
                    if (!i.has(e)) {
                        const r = __PRIVATE_calculateOverlayMutation(t.get(e), n.get(e));
                        null !== r && u.set(e, r), i = i.add(e);
                    }
                })), s.push(this.documentOverlayCache.saveOverlays(e, o, u));
            }
            return PersistencePromise.waitFor(s);
        })).next((() => n));
    }
    /**
     * Recalculates overlays by reading the documents from remote document cache
     * first, and saves them after they are calculated.
     */    recalculateAndSaveOverlaysForDocumentKeys(e, t) {
        return this.remoteDocumentCache.getEntries(e, t).next((t => this.recalculateAndSaveOverlays(e, t)));
    }
    /**
     * Performs a query against the local view of all documents.
     *
     * @param transaction - The persistence transaction.
     * @param query - The query to match documents against.
     * @param offset - Read time and key to start scanning by (exclusive).
     * @param context - A optional tracker to keep a record of important details
     *   during database local query execution.
     */    getDocumentsMatchingQuery(e, t, n, r) {
        return __PRIVATE_isPipeline(t) ? this.getDocumentsMatchingPipeline(e, t, n, r) : __PRIVATE_isDocumentQuery$1(t) ? this.getDocumentsMatchingDocumentQuery(e, t.path) : __PRIVATE_isCollectionGroupQuery(t) ? this.getDocumentsMatchingCollectionGroupQuery(e, t, n, r) : this.getDocumentsMatchingCollectionQuery(e, t, n, r);
    }
    /**
     * Given a collection group, returns the next documents that follow the provided offset, along
     * with an updated batch ID.
     *
     * <p>The documents returned by this method are ordered by remote version from the provided
     * offset. If there are no more remote documents after the provided offset, documents with
     * mutations in order of batch id from the offset are returned. Since all documents in a batch are
     * returned together, the total number of documents returned can exceed {@code count}.
     *
     * @param transaction
     * @param collectionGroup - The collection group for the documents.
     * @param offset - The offset to index into.
     * @param count - The number of documents to return
     * @returns A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.
     */    getNextDocuments(e, t, n, r) {
        return this.remoteDocumentCache.getAllFromCollectionGroup(e, t, n, r).next((i => {
            const s = r - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e, t, n.largestBatchId, r - i.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap());
            // The callsite will use the largest batch ID together with the latest read time to create
            // a new index offset. Since we only process batch IDs if all remote documents have been read,
            // no overlay will increase the overall read time. This is why we only need to special case
            // the batch id.
                        let _ = Xe, o = i;
            return s.next((t => PersistencePromise.forEach(t, ((t, n) => (_ < n.largestBatchId && (_ = n.largestBatchId), 
            i.get(t) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e, t).next((e => {
                o = o.insert(t, e);
            }))))).next((() => this.populateOverlays(e, t, i))).next((() => this.computeViews(e, o, t, __PRIVATE_documentKeySet()))).next((e => ({
                batchId: _,
                changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e)
            })))));
        }));
    }
    getDocumentsMatchingDocumentQuery(e, t) {
        // Just do a simple document lookup.
        return this.getDocument(e, new DocumentKey(t)).next((e => {
            let t = documentMap();
            return e.isFoundDocument() && (t = t.insert(e.key, e)), t;
        }));
    }
    getDocumentsMatchingCollectionGroupQuery(e, t, n, r) {
        const i = t.collectionGroup;
        let s = documentMap();
        return this.indexManager.getCollectionParents(e, i).next((_ => PersistencePromise.forEach(_, (_ => {
            const o = function __PRIVATE_asCollectionQueryAtPath(e, t) {
                return new __PRIVATE_QueryImpl(t, 
                /*collectionGroup=*/ null, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt);
            }(t, _.child(i));
            return this.getDocumentsMatchingCollectionQuery(e, o, n, r).next((e => {
                e.forEach(((e, t) => {
                    s = s.insert(e, t);
                }));
            }));
        })).next((() => s))));
    }
    getDocumentsMatchingCollectionQuery(e, t, n, r) {
        // Query the remote documents and overlay mutations.
        let i;
        return this.documentOverlayCache.getOverlaysForCollection(e, t.path, n.largestBatchId).next((s => (i = s, 
        this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, i, r)))).next((e => this.retrieveMatchingLocalDocuments(i, e, (e => __PRIVATE_queryMatches(t, e)))));
    }
    getDocumentsMatchingPipeline(e, t, n, r) {
        if ("collection_group" === getPipelineSourceType(t)) {
            const i = getPipelineCollectionGroup(t);
            let s = documentMap();
            return this.indexManager.getCollectionParents(e, i).next((_ => PersistencePromise.forEach(_, (_ => {
                const o = function __PRIVATE_asCollectionPipelineAtPath(e, t) {
                    const n = e.stages.map((e => e instanceof J ? new H(t.canonicalString(), {}) : e));
                    return new CorePipeline(e.serializer, n);
                }(t, _.child(i));
                return this.getDocumentsMatchingPipeline(e, o, n, r).next((e => {
                    e.forEach(((e, t) => {
                        s = s.insert(e, t);
                    }));
                }));
            })).next((() => s))));
        }
        {
            // Query the remote documents and overlay mutations.
            let i;
            return this.getOverlaysForPipeline(e, t, n.largestBatchId).next((_ => {
                switch (i = _, getPipelineSourceType(t)) {
                  case "collection":
                    return this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, i, r);

                  case "documents":
                    let _ = __PRIVATE_documentKeySet();
                    for (const e of getPipelineDocuments(t)) _ = _.add(DocumentKey.fromPath(e));
                    return this.remoteDocumentCache.getEntries(e, _);

                  case "database":
                    return this.remoteDocumentCache.getAllEntries(e);

                  default:
                    throw new s("invalid-argument", `Invalid pipeline source to execute offline: ${__PRIVATE_canonifyPipeline(t)}`);
                }
            })).next((e => this.retrieveMatchingLocalDocuments(i, e, (e => __PRIVATE_pipelineMatches(t, e)))));
        }
    }
    retrieveMatchingLocalDocuments(e, t, n) {
        // As documents might match the query because of their overlay we need to
        // include documents for all overlays in the initial document set.
        e.forEach(((e, n) => {
            const r = n.getKey();
            null === t.get(r) && (t = t.insert(r, MutableDocument.newInvalidDocument(r)));
        }));
        // Apply the overlays and match against the query.
        let r = documentMap();
        return t.forEach(((t, i) => {
            const s = e.get(t);
            void 0 !== s && __PRIVATE_mutationApplyToLocalView(s.mutation, i, FieldMask.empty(), Timestamp.now()), 
            // Finally, insert the documents that still match the query
            n(i) && (r = r.insert(t, i));
        })), r;
    }
    getOverlaysForPipeline(e, t, n) {
        switch (getPipelineSourceType(t)) {
          case "collection":
            return this.documentOverlayCache.getOverlaysForCollection(e, ResourcePath.fromString(getPipelineCollection(t)), n);

          case "collection_group":
            throw new s("invalid-argument", `Unexpected collection group pipeline: ${__PRIVATE_canonifyPipeline(t)}`);

          case "documents":
            return this.documentOverlayCache.getOverlays(e, getPipelineDocuments(t).map((e => DocumentKey.fromPath(e))));

          case "database":
            return this.documentOverlayCache.getAllOverlays(e, n);

          default:
            throw new s("invalid-argument", `Failed to get overlays for pipeline: ${__PRIVATE_canonifyPipeline(t)}`);
        }
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_MemoryBundleCache {
    constructor(e) {
        this.serializer = e, this.Ks = new Map, this.Ws = new Map;
    }
    getBundleMetadata(e, t) {
        return PersistencePromise.resolve(this.Ks.get(t));
    }
    saveBundleMetadata(e, t) {
        return this.Ks.set(t.id, 
        /** Decodes a BundleMetadata proto into a BundleMetadata object. */
        function __PRIVATE_fromBundleMetadata(e) {
            return {
                id: e.id,
                version: e.version,
                createTime: __PRIVATE_fromVersion(e.createTime)
            };
        }(t)), PersistencePromise.resolve();
    }
    getNamedQuery(e, t) {
        return PersistencePromise.resolve(this.Ws.get(t));
    }
    saveNamedQuery(e, t) {
        return this.Ws.set(t.name, function __PRIVATE_fromProtoNamedQuery(e) {
            return {
                name: e.name,
                query: __PRIVATE_fromBundledQuery(e.bundledQuery),
                readTime: __PRIVATE_fromVersion(e.readTime)
            };
        }(t)), PersistencePromise.resolve();
    }
}

/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * An in-memory implementation of DocumentOverlayCache.
 */ class __PRIVATE_MemoryDocumentOverlayCache {
    constructor() {
        // A map sorted by DocumentKey, whose value is a pair of the largest batch id
        // for the overlay and the overlay itself.
        this.overlays = new SortedMap(DocumentKey.comparator), this.Qs = new Map;
    }
    getOverlay(e, t) {
        return PersistencePromise.resolve(this.overlays.get(t));
    }
    getOverlays(e, t) {
        const n = __PRIVATE_newOverlayMap();
        return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => {
            null !== e && n.set(t, e);
        })))).next((() => n));
    }
    getAllOverlays(e, t) {
        const n = __PRIVATE_newOverlayMap();
        return this.overlays.forEach(((e, r) => {
            r.largestBatchId > t && n.set(e, r);
        })), PersistencePromise.resolve(n);
    }
    saveOverlays(e, t, n) {
        return n.forEach(((n, r) => {
            this.Yr(e, t, r);
        })), PersistencePromise.resolve();
    }
    removeOverlaysForBatchId(e, t, n) {
        const r = this.Qs.get(n);
        return void 0 !== r && (r.forEach((e => this.overlays = this.overlays.remove(e))), 
        this.Qs.delete(n)), PersistencePromise.resolve();
    }
    getOverlaysForCollection(e, t, n) {
        const r = __PRIVATE_newOverlayMap(), i = t.length + 1, s = new DocumentKey(t.child("")), _ = this.overlays.getIteratorFrom(s);
        for (;_.hasNext(); ) {
            const e = _.getNext().value, s = e.getKey();
            if (!t.isPrefixOf(s.path)) break;
            // Documents from sub-collections
                        s.path.length === i && (e.largestBatchId > n && r.set(e.getKey(), e));
        }
        return PersistencePromise.resolve(r);
    }
    getOverlaysForCollectionGroup(e, t, n, r) {
        let i = new SortedMap(((e, t) => e - t));
        const s = this.overlays.getIterator();
        for (;s.hasNext(); ) {
            const e = s.getNext().value;
            if (e.getKey().getCollectionGroup() === t && e.largestBatchId > n) {
                let t = i.get(e.largestBatchId);
                null === t && (t = __PRIVATE_newOverlayMap(), i = i.insert(e.largestBatchId, t)), 
                t.set(e.getKey(), e);
            }
        }
        const _ = __PRIVATE_newOverlayMap(), o = i.getIterator();
        for (;o.hasNext(); ) {
            if (o.getNext().value.forEach(((e, t) => _.set(e, t))), _.size() >= r) break;
        }
        return PersistencePromise.resolve(_);
    }
    Yr(e, t, n) {
        // Remove the association of the overlay to its batch id.
        const r = this.overlays.get(n.key);
        if (null !== r) {
            const e = this.Qs.get(r.largestBatchId).delete(n.key);
            this.Qs.set(r.largestBatchId, e);
        }
        this.overlays = this.overlays.insert(n.key, new Overlay(t, n));
        // Create the association of this overlay to the given largestBatchId.
        let i = this.Qs.get(t);
        void 0 === i && (i = __PRIVATE_documentKeySet(), this.Qs.set(t, i)), this.Qs.set(t, i.add(n.key));
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_MemoryGlobalsCache {
    constructor() {
        this.sessionToken = ByteString.EMPTY_BYTE_STRING;
    }
    getSessionToken(e) {
        return PersistencePromise.resolve(this.sessionToken);
    }
    setSessionToken(e, t) {
        return this.sessionToken = t, PersistencePromise.resolve();
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A collection of references to a document from some kind of numbered entity
 * (either a target ID or batch ID). As references are added to or removed from
 * the set corresponding events are emitted to a registered garbage collector.
 *
 * Each reference is represented by a DocumentReference object. Each of them
 * contains enough information to uniquely identify the reference. They are all
 * stored primarily in a set sorted by key. A document is considered garbage if
 * there's no references in that set (this can be efficiently checked thanks to
 * sorting by key).
 *
 * ReferenceSet also keeps a secondary set that contains references sorted by
 * IDs. This one is used to efficiently implement removal of all references by
 * some target ID.
 */ class __PRIVATE_ReferenceSet {
    constructor() {
        // A set of outstanding references to a document sorted by key.
        this.Gs = new SortedSet(__PRIVATE_DocReference.zs), 
        // A set of outstanding references to a document sorted by target id.
        this.js = new SortedSet(__PRIVATE_DocReference.Hs);
    }
    /** Returns true if the reference set contains no references. */    isEmpty() {
        return this.Gs.isEmpty();
    }
    /** Adds a reference to the given document key for the given ID. */    addReference(e, t) {
        const n = new __PRIVATE_DocReference(e, t);
        this.Gs = this.Gs.add(n), this.js = this.js.add(n);
    }
    /** Add references to the given document keys for the given ID. */    Js(e, t) {
        e.forEach((e => this.addReference(e, t)));
    }
    /**
     * Removes a reference to the given document key for the given
     * ID.
     */    removeReference(e, t) {
        this.Ys(new __PRIVATE_DocReference(e, t));
    }
    Zs(e, t) {
        e.forEach((e => this.removeReference(e, t)));
    }
    /**
     * Clears all references with a given ID. Calls removeRef() for each key
     * removed.
     */    Xs(e) {
        const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1), i = [];
        return this.js.forEachInRange([ n, r ], (e => {
            this.Ys(e), i.push(e.key);
        })), i;
    }
    e_() {
        this.Gs.forEach((e => this.Ys(e)));
    }
    Ys(e) {
        this.Gs = this.Gs.delete(e), this.js = this.js.delete(e);
    }
    t_(e) {
        const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1);
        let i = __PRIVATE_documentKeySet();
        return this.js.forEachInRange([ n, r ], (e => {
            i = i.add(e.key);
        })), i;
    }
    containsKey(e) {
        const t = new __PRIVATE_DocReference(e, 0), n = this.Gs.firstAfterOrEqual(t);
        return null !== n && e.isEqual(n.key);
    }
}

class __PRIVATE_DocReference {
    constructor(e, t) {
        this.key = e, this.n_ = t;
    }
    /** Compare by key then by ID */    static zs(e, t) {
        return DocumentKey.comparator(e.key, t.key) || __PRIVATE_primitiveComparator(e.n_, t.n_);
    }
    /** Compare by ID then by key */    static Hs(e, t) {
        return __PRIVATE_primitiveComparator(e.n_, t.n_) || DocumentKey.comparator(e.key, t.key);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_MemoryMutationQueue {
    constructor(e, t) {
        this.indexManager = e, this.referenceDelegate = t, 
        /**
         * The set of all mutations that have been sent but not yet been applied to
         * the backend.
         */
        this.mutationQueue = [], 
        /** Next value to use when assigning sequential IDs to each mutation batch. */
        this.Qr = 1, 
        /** An ordered mapping between documents and the mutations batch IDs. */
        this.r_ = new SortedSet(__PRIVATE_DocReference.zs);
    }
    checkEmpty(e) {
        return PersistencePromise.resolve(0 === this.mutationQueue.length);
    }
    addMutationBatch(e, t, n, r) {
        const i = this.Qr;
        this.Qr++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];
        const s = new MutationBatch(i, t, n, r);
        this.mutationQueue.push(s);
        // Track references by document key and index collection parents.
        for (const t of r) this.r_ = this.r_.add(new __PRIVATE_DocReference(t.key, i)), 
        this.indexManager.addToCollectionParentIndex(e, t.key.path.popLast());
        return PersistencePromise.resolve(s);
    }
    lookupMutationBatch(e, t) {
        return PersistencePromise.resolve(this.i_(t));
    }
    getNextMutationBatchAfterBatchId(e, t) {
        const n = t + 1, r = this.s_(n), i = r < 0 ? 0 : r;
        // The requested batchId may still be out of range so normalize it to the
        // start of the queue.
                return PersistencePromise.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);
    }
    getHighestUnacknowledgedBatchId() {
        return PersistencePromise.resolve(0 === this.mutationQueue.length ? Ke : this.Qr - 1);
    }
    getAllMutationBatches(e) {
        return PersistencePromise.resolve(this.mutationQueue.slice());
    }
    getAllMutationBatchesAffectingDocumentKey(e, t) {
        const n = new __PRIVATE_DocReference(t, 0), r = new __PRIVATE_DocReference(t, Number.POSITIVE_INFINITY), i = [];
        return this.r_.forEachInRange([ n, r ], (e => {
            const t = this.i_(e.n_);
            i.push(t);
        })), PersistencePromise.resolve(i);
    }
    getAllMutationBatchesAffectingDocumentKeys(e, t) {
        let n = new SortedSet(__PRIVATE_primitiveComparator);
        return t.forEach((e => {
            const t = new __PRIVATE_DocReference(e, 0), r = new __PRIVATE_DocReference(e, Number.POSITIVE_INFINITY);
            this.r_.forEachInRange([ t, r ], (e => {
                n = n.add(e.n_);
            }));
        })), PersistencePromise.resolve(this.__(n));
    }
    getAllMutationBatchesAffectingQuery(e, t) {
        // Use the query path as a prefix for testing if a document matches the
        // query.
        const n = t.path, r = n.length + 1;
        // Construct a document reference for actually scanning the index. Unlike
        // the prefix the document key in this reference must have an even number of
        // segments. The empty segment can be used a suffix of the query path
        // because it precedes all other segments in an ordered traversal.
        let i = n;
        DocumentKey.isDocumentKey(i) || (i = i.child(""));
        const s = new __PRIVATE_DocReference(new DocumentKey(i), 0);
        // Find unique batchIDs referenced by all documents potentially matching the
        // query.
                let _ = new SortedSet(__PRIVATE_primitiveComparator);
        return this.r_.forEachWhile((e => {
            const t = e.key.path;
            return !!n.isPrefixOf(t) && (
            // Rows with document keys more than one segment longer than the query
            // path can't be matches. For example, a query on 'rooms' can't match
            // the document /rooms/abc/messages/xyx.
            // TODO(mcg): we'll need a different scanner when we implement
            // ancestor queries.
            t.length === r && (_ = _.add(e.n_)), true);
        }), s), PersistencePromise.resolve(this.__(_));
    }
    __(e) {
        // Construct an array of matching batches, sorted by batchID to ensure that
        // multiple mutations affecting the same document key are applied in order.
        const t = [];
        return e.forEach((e => {
            const n = this.i_(e);
            null !== n && t.push(n);
        })), t;
    }
    removeMutationBatch(e, t) {
        __PRIVATE_hardAssert(0 === this.o_(t.batchId, "removed"), 55003), this.mutationQueue.shift();
        let n = this.r_;
        return PersistencePromise.forEach(t.mutations, (r => {
            const i = new __PRIVATE_DocReference(r.key, t.batchId);
            return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(e, r.key);
        })).next((() => {
            this.r_ = n;
        }));
    }
    jr(e) {
        // No-op since the memory mutation queue does not maintain a separate cache.
    }
    containsKey(e, t) {
        const n = new __PRIVATE_DocReference(t, 0), r = this.r_.firstAfterOrEqual(n);
        return PersistencePromise.resolve(t.isEqual(r && r.key));
    }
    performConsistencyCheck(e) {
        return this.mutationQueue.length, PersistencePromise.resolve();
    }
    /**
     * Finds the index of the given batchId in the mutation queue and asserts that
     * the resulting index is within the bounds of the queue.
     *
     * @param batchId - The batchId to search for
     * @param action - A description of what the caller is doing, phrased in passive
     * form (e.g. "acknowledged" in a routine that acknowledges batches).
     */    o_(e, t) {
        return this.s_(e);
    }
    /**
     * Finds the index of the given batchId in the mutation queue. This operation
     * is O(1).
     *
     * @returns The computed index of the batch with the given batchId, based on
     * the state of the queue. Note this index can be negative if the requested
     * batchId has already been removed from the queue or past the end of the
     * queue if the batchId is larger than the last added batch.
     */    s_(e) {
        if (0 === this.mutationQueue.length) 
        // As an index this is past the end of the queue
        return 0;
        // Examine the front of the queue to figure out the difference between the
        // batchId and indexes in the array. Note that since the queue is ordered
        // by batchId, if the first batch has a larger batchId then the requested
        // batchId doesn't exist in the queue.
                return e - this.mutationQueue[0].batchId;
    }
    /**
     * A version of lookupMutationBatch that doesn't return a promise, this makes
     * other functions that uses this code easier to read and more efficient.
     */    i_(e) {
        const t = this.s_(e);
        if (t < 0 || t >= this.mutationQueue.length) return null;
        return this.mutationQueue[t];
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The smallest value representable by a 64-bit signed integer (long).
 */
/**
 * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke
 * `newMemoryRemoteDocumentCache()`.
 */
class __PRIVATE_MemoryRemoteDocumentCacheImpl {
    /**
     * @param sizer - Used to assess the size of a document. For eager GC, this is
     * expected to just return 0 to avoid unnecessarily doing the work of
     * calculating the size.
     */
    constructor(e) {
        this.a_ = e, 
        /** Underlying cache of documents and their read times. */
        this.docs = function __PRIVATE_documentEntryMap() {
            return new SortedMap(DocumentKey.comparator);
        }(), 
        /** Size of all cached documents. */
        this.size = 0;
    }
    setIndexManager(e) {
        this.indexManager = e;
    }
    /**
     * Adds the supplied entry to the cache and updates the cache size as appropriate.
     *
     * All calls of `addEntry`  are required to go through the RemoteDocumentChangeBuffer
     * returned by `newChangeBuffer()`.
     */    addEntry(e, t) {
        const n = t.key, r = this.docs.get(n), i = r ? r.size : 0, s = this.a_(t);
        return this.docs = this.docs.insert(n, {
            document: t.mutableCopy(),
            size: s
        }), this.size += s - i, this.indexManager.addToCollectionParentIndex(e, n.path.popLast());
    }
    /**
     * Removes the specified entry from the cache and updates the cache size as appropriate.
     *
     * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer
     * returned by `newChangeBuffer()`.
     */    removeEntry(e) {
        const t = this.docs.get(e);
        t && (this.docs = this.docs.remove(e), this.size -= t.size);
    }
    getEntry(e, t) {
        const n = this.docs.get(t);
        return PersistencePromise.resolve(n ? n.document.mutableCopy() : MutableDocument.newInvalidDocument(t));
    }
    getEntries(e, t) {
        let n = __PRIVATE_mutableDocumentMap();
        return t.forEach((e => {
            const t = this.docs.get(e);
            n = n.insert(e, t ? t.document.mutableCopy() : MutableDocument.newInvalidDocument(e));
        })), PersistencePromise.resolve(n);
    }
    getAllEntries(e) {
        let t = __PRIVATE_mutableDocumentMap();
        return this.docs.forEach(((e, n) => {
            t = t.insert(e, n.document);
        })), PersistencePromise.resolve(t);
    }
    getDocumentsMatchingQuery(e, t, n, r) {
        // Documents are ordered by key, so we can use a prefix scan to narrow down
        // the documents we need to match the query against.
        let i, s;
        __PRIVATE_isPipeline(t) ? (
        // Documents are ordered by key, so we can use a prefix scan to narrow down
        // the documents we need to match the query against.
        i = ResourcePath.fromString(getPipelineCollection(t)), s = e => __PRIVATE_pipelineMatches(t, e)) : (
        // Documents are ordered by key, so we can use a prefix scan to narrow down
        // the documents we need to match the query against.
        i = t.path, s = e => __PRIVATE_queryMatches(t, e));
        let _ = __PRIVATE_mutableDocumentMap();
        // Document keys are ordered first by numeric value ("__id<Long>__"),
        // then lexicographically by string value. Start the iterator at the minimum
        // possible Document key value.
                const o = new DocumentKey(i.child("__id-9223372036854775808__")), a = this.docs.getIteratorFrom(o);
        for (;a.hasNext(); ) {
            const {key: e, value: {document: t}} = a.getNext();
            if (!i.isPrefixOf(e.path)) break;
            e.path.length > i.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(t), n) <= 0 || (r.has(t.key) || s(t)) && (_ = _.insert(t.key, t.mutableCopy())));
        }
        return PersistencePromise.resolve(_);
    }
    getAllFromCollectionGroup(e, t, n, r) {
        // This method should only be called from the IndexBackfiller if persistence
        // is enabled.
        l(9500);
    }
    u_(e, t) {
        return PersistencePromise.forEach(this.docs, (e => t(e)));
    }
    newChangeBuffer(e) {
        // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
        // a separate changelog and does not need special handling for removals.
        return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this);
    }
    getSize(e) {
        return PersistencePromise.resolve(this.size);
    }
}

/**
 * Creates a new memory-only RemoteDocumentCache.
 *
 * @param sizer - Used to assess the size of a document. For eager GC, this is
 * expected to just return 0 to avoid unnecessarily doing the work of
 * calculating the size.
 */
/**
 * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
 */
class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {
    constructor(e) {
        super(), this.qs = e;
    }
    applyChanges(e) {
        const t = [];
        return this.changes.forEach(((n, r) => {
            r.isValidDocument() ? t.push(this.qs.addEntry(e, r)) : this.qs.removeEntry(n);
        })), PersistencePromise.waitFor(t);
    }
    getFromCache(e, t) {
        return this.qs.getEntry(e, t);
    }
    getAllFromCache(e, t) {
        return this.qs.getEntries(e, t);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class __PRIVATE_MemoryTargetCache {
    constructor(e) {
        this.persistence = e, 
        /**
         * Maps a target to the data about that target
         */
        this.c_ = new ObjectMap((e => __PRIVATE_canonifyTargetOrPipeline(e)), __PRIVATE_targetOrPipelineEqual), 
        /** The last received snapshot version. */
        this.lastRemoteSnapshotVersion = SnapshotVersion.min(), 
        /** The highest numbered target ID encountered. */
        this.highestTargetId = 0, 
        /** The highest sequence number encountered. */
        this.l_ = 0, 
        /**
         * A ordered bidirectional mapping between documents and the remote target
         * IDs.
         */
        this.E_ = new __PRIVATE_ReferenceSet, this.targetCount = 0, this.h_ = __PRIVATE_TargetIdGenerator.ys();
    }
    forEachTarget(e, t) {
        return this.c_.forEach(((e, n) => t(n))), PersistencePromise.resolve();
    }
    getLastRemoteSnapshotVersion(e) {
        return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);
    }
    getHighestSequenceNumber(e) {
        return PersistencePromise.resolve(this.l_);
    }
    allocateTargetId(e) {
        return this.highestTargetId = this.h_.next(), PersistencePromise.resolve(this.highestTargetId);
    }
    setTargetsMetadata(e, t, n) {
        return n && (this.lastRemoteSnapshotVersion = n), t > this.l_ && (this.l_ = t), 
        PersistencePromise.resolve();
    }
    Ss(e) {
        this.c_.set(e.target, e);
        const t = e.targetId;
        t > this.highestTargetId && (this.h_ = new __PRIVATE_TargetIdGenerator(t), this.highestTargetId = t), 
        e.sequenceNumber > this.l_ && (this.l_ = e.sequenceNumber);
    }
    addTargetData(e, t) {
        return this.Ss(t), this.targetCount += 1, PersistencePromise.resolve();
    }
    updateTargetData(e, t) {
        return this.Ss(t), PersistencePromise.resolve();
    }
    removeTargetData(e, t) {
        return this.c_.delete(t.target), this.E_.Xs(t.targetId), this.targetCount -= 1, 
        PersistencePromise.resolve();
    }
    removeTargets(e, t, n) {
        let r = 0;
        const i = [];
        return this.c_.forEach(((s, _) => {
            _.sequenceNumber <= t && null === n.get(_.targetId) && (this.c_.delete(s), i.push(this.removeMatchingKeysForTargetId(e, _.targetId)), 
            r++);
        })), PersistencePromise.waitFor(i).next((() => r));
    }
    getTargetCount(e) {
        return PersistencePromise.resolve(this.targetCount);
    }
    getTargetData(e, t) {
        const n = this.c_.get(t) || null;
        return PersistencePromise.resolve(n);
    }
    addMatchingKeys(e, t, n) {
        return this.E_.Js(t, n), PersistencePromise.resolve();
    }
    removeMatchingKeys(e, t, n) {
        this.E_.Zs(t, n);
        const r = this.persistence.referenceDelegate, i = [];
        return r && t.forEach((t => {
            i.push(r.markPotentiallyOrphaned(e, t));
        })), PersistencePromise.waitFor(i);
    }
    removeMatchingKeysForTargetId(e, t) {
        return this.E_.Xs(t), PersistencePromise.resolve();
    }
    getMatchingKeysForTargetId(e, t) {
        const n = this.E_.t_(t);
        return PersistencePromise.resolve(n);
    }
    containsKey(e, t) {
        return PersistencePromise.resolve(this.E_.containsKey(t));
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A memory-backed instance of Persistence. Data is stored only in RAM and
 * not persisted across sessions.
 */
class __PRIVATE_MemoryPersistence {
    /**
     * The constructor accepts a factory for creating a reference delegate. This
     * allows both the delegate and this instance to have strong references to
     * each other without having nullable fields that would then need to be
     * checked or asserted on every access.
     */
    constructor(e, t) {
        this.T_ = {}, this.overlays = {}, this.P_ = new __PRIVATE_ListenSequence(0), this.R_ = false, 
        this.R_ = true, this.I_ = new __PRIVATE_MemoryGlobalsCache, this.referenceDelegate = e(this), 
        this.A_ = new __PRIVATE_MemoryTargetCache(this);
        this.indexManager = new __PRIVATE_MemoryIndexManager, this.remoteDocumentCache = function __PRIVATE_newMemoryRemoteDocumentCache(e) {
            return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e);
        }((e => this.referenceDelegate.V_(e))), this.serializer = new __PRIVATE_LocalSerializer(t), 
        this.d_ = new __PRIVATE_MemoryBundleCache(this.serializer);
    }
    start() {
        return Promise.resolve();
    }
    shutdown() {
        // No durable state to ensure is closed on shutdown.
        return this.R_ = false, Promise.resolve();
    }
    get started() {
        return this.R_;
    }
    setDatabaseDeletedListener() {
        // No op.
    }
    setNetworkEnabled() {
        // No op.
    }
    getIndexManager(e) {
        // We do not currently support indices for memory persistence, so we can
        // return the same shared instance of the memory index manager.
        return this.indexManager;
    }
    getDocumentOverlayCache(e) {
        let t = this.overlays[e.toKey()];
        return t || (t = new __PRIVATE_MemoryDocumentOverlayCache, this.overlays[e.toKey()] = t), 
        t;
    }
    getMutationQueue(e, t) {
        let n = this.T_[e.toKey()];
        return n || (n = new __PRIVATE_MemoryMutationQueue(t, this.referenceDelegate), this.T_[e.toKey()] = n), 
        n;
    }
    getGlobalsCache() {
        return this.I_;
    }
    getTargetCache() {
        return this.A_;
    }
    getRemoteDocumentCache() {
        return this.remoteDocumentCache;
    }
    getBundleCache() {
        return this.d_;
    }
    runTransaction(e, t, n) {
        __PRIVATE_logDebug("MemoryPersistence", "Starting transaction:", e);
        const r = new __PRIVATE_MemoryTransaction(this.P_.next());
        return this.referenceDelegate.f_(), n(r).next((e => this.referenceDelegate.m_(r).next((() => e)))).toPromise().then((e => (r.raiseOnCommittedEvent(), 
        e)));
    }
    p_(e, t) {
        return PersistencePromise.or(Object.values(this.T_).map((n => () => n.containsKey(e, t))));
    }
}

/**
 * Memory persistence is not actually transactional, but future implementations
 * may have transaction-scoped state.
 */ class __PRIVATE_MemoryTransaction extends PersistenceTransaction {
    constructor(e) {
        super(), this.currentSequenceNumber = e;
    }
}

class __PRIVATE_MemoryEagerDelegate {
    constructor(e) {
        this.persistence = e, 
        /** Tracks all documents that are active in Query views. */
        this.g_ = new __PRIVATE_ReferenceSet, 
        /** The list of documents that are potentially GCed after each transaction. */
        this.y_ = null;
    }
    static w_(e) {
        return new __PRIVATE_MemoryEagerDelegate(e);
    }
    get b_() {
        if (this.y_) return this.y_;
        throw l(60996);
    }
    addReference(e, t, n) {
        return this.g_.addReference(n, t), this.b_.delete(n.toString()), PersistencePromise.resolve();
    }
    removeReference(e, t, n) {
        return this.g_.removeReference(n, t), this.b_.add(n.toString()), PersistencePromise.resolve();
    }
    markPotentiallyOrphaned(e, t) {
        return this.b_.add(t.toString()), PersistencePromise.resolve();
    }
    removeTarget(e, t) {
        this.g_.Xs(t.targetId).forEach((e => this.b_.add(e.toString())));
        const n = this.persistence.getTargetCache();
        return n.getMatchingKeysForTargetId(e, t.targetId).next((e => {
            e.forEach((e => this.b_.add(e.toString())));
        })).next((() => n.removeTargetData(e, t)));
    }
    f_() {
        this.y_ = new Set;
    }
    m_(e) {
        // Remove newly orphaned documents.
        const t = this.persistence.getRemoteDocumentCache().newChangeBuffer();
        return PersistencePromise.forEach(this.b_, (n => {
            const r = DocumentKey.fromPath(n);
            return this.v_(e, r).next((e => {
                e || t.removeEntry(r, SnapshotVersion.min());
            }));
        })).next((() => (this.y_ = null, t.apply(e))));
    }
    updateLimboDocument(e, t) {
        return this.v_(e, t).next((e => {
            e ? this.b_.delete(t.toString()) : this.b_.add(t.toString());
        }));
    }
    V_(e) {
        // For eager GC, we don't care about the document size, there are no size thresholds.
        return 0;
    }
    v_(e, t) {
        return PersistencePromise.or([ () => PersistencePromise.resolve(this.g_.containsKey(t)), () => this.persistence.getTargetCache().containsKey(e, t), () => this.persistence.p_(e, t) ]);
    }
}

class __PRIVATE_MemoryLruDelegate {
    constructor(e, t) {
        this.persistence = e, this.S_ = new ObjectMap((e => __PRIVATE_encodeResourcePath(e.path)), ((e, t) => e.isEqual(t))), 
        this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t);
    }
    static w_(e, t) {
        return new __PRIVATE_MemoryLruDelegate(e, t);
    }
    // No-ops, present so memory persistence doesn't have to care which delegate
    // it has.
    f_() {}
    m_(e) {
        return PersistencePromise.resolve();
    }
    forEachTarget(e, t) {
        return this.persistence.getTargetCache().forEachTarget(e, t);
    }
    rr(e) {
        const t = this.xs(e);
        return this.persistence.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t))));
    }
    xs(e) {
        let t = 0;
        return this.ir(e, (e => {
            t++;
        })).next((() => t));
    }
    ir(e, t) {
        return PersistencePromise.forEach(this.S_, ((n, r) => this.Fs(e, n, r).next((e => e ? PersistencePromise.resolve() : t(r)))));
    }
    removeTargets(e, t, n) {
        return this.persistence.getTargetCache().removeTargets(e, t, n);
    }
    removeOrphanedDocuments(e, t) {
        let n = 0;
        const r = this.persistence.getRemoteDocumentCache(), i = r.newChangeBuffer();
        return r.u_(e, (r => this.Fs(e, r, t).next((e => {
            e || (n++, i.removeEntry(r, SnapshotVersion.min()));
        })))).next((() => i.apply(e))).next((() => n));
    }
    markPotentiallyOrphaned(e, t) {
        return this.S_.set(t, e.currentSequenceNumber), PersistencePromise.resolve();
    }
    removeTarget(e, t) {
        const n = t.withSequenceNumber(e.currentSequenceNumber);
        return this.persistence.getTargetCache().updateTargetData(e, n);
    }
    addReference(e, t, n) {
        return this.S_.set(n, e.currentSequenceNumber), PersistencePromise.resolve();
    }
    removeReference(e, t, n) {
        return this.S_.set(n, e.currentSequenceNumber), PersistencePromise.resolve();
    }
    updateLimboDocument(e, t) {
        return this.S_.set(t, e.currentSequenceNumber), PersistencePromise.resolve();
    }
    V_(e) {
        let t = e.key.toString().length;
        return e.isFoundDocument() && (t += __PRIVATE_estimateByteSize(e.data.value)), t;
    }
    Fs(e, t, n) {
        return PersistencePromise.or([ () => this.persistence.p_(e, t), () => this.persistence.getTargetCache().containsKey(e, t), () => {
            const e = this.S_.get(t);
            return PersistencePromise.resolve(void 0 !== e && e > n);
        } ]);
    }
    getCacheSize(e) {
        return this.persistence.getRemoteDocumentCache().getSize(e);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** Performs database creation and schema upgrades. */ class __PRIVATE_SchemaConverter {
    constructor(e) {
        this.serializer = e;
    }
    /**
     * Performs database creation and schema upgrades.
     *
     * Note that in production, this method is only ever used to upgrade the schema
     * to SCHEMA_VERSION. Different values of toVersion are only used for testing
     * and local feature development.
     */    Mn(e, t, n, r) {
        const i = new __PRIVATE_SimpleDbTransaction("createOrUpgrade", t);
        n < 1 && r >= 1 && (!function __PRIVATE_createPrimaryClientStore(e) {
            e.createObjectStore(Qt);
        }(e), function __PRIVATE_createMutationQueue(e) {
            e.createObjectStore(zt, {
                keyPath: jt
            });
            const t = e.createObjectStore(Ht, {
                keyPath: Jt,
                autoIncrement: true
            });
            t.createIndex(Yt, Zt, {
                unique: true
            }), e.createObjectStore(en);
        }
        /**
 * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
 * and rewrites all data.
 */ (e), __PRIVATE_createQueryCache(e), function __PRIVATE_createLegacyRemoteDocumentCache(e) {
            e.createObjectStore(Wt);
        }(e));
        // Migration 2 to populate the targetGlobal object no longer needed since
        // migration 3 unconditionally clears it.
                let s = PersistencePromise.resolve();
        return n < 3 && r >= 3 && (
        // Brand new clients don't need to drop and recreate--only clients that
        // potentially have corrupt data.
        0 !== n && (!function __PRIVATE_dropQueryCache(e) {
            e.deleteObjectStore(Tn), e.deleteObjectStore(cn), e.deleteObjectStore(Vn);
        }(e), __PRIVATE_createQueryCache(e)), s = s.next((() => 
        /**
 * Creates the target global singleton row.
 *
 * @param txn - The version upgrade transaction for indexeddb
 */
        function __PRIVATE_writeEmptyTargetGlobalEntry(e) {
            const t = e.store(Vn), n = {
                highestTargetId: 0,
                highestListenSequenceNumber: 0,
                lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),
                targetCount: 0
            };
            return t.put(An, n);
        }(i)))), n < 4 && r >= 4 && (0 !== n && (
        // Schema version 3 uses auto-generated keys to generate globally unique
        // mutation batch IDs (this was previously ensured internally by the
        // client). To migrate to the new schema, we have to read all mutations
        // and write them back out. We preserve the existing batch IDs to guarantee
        // consistency with other object stores. Any further mutation batch IDs will
        // be auto-generated.
        s = s.next((() => function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e, t) {
            const n = t.store(Ht);
            return n.Kn().next((n => {
                e.deleteObjectStore(Ht);
                e.createObjectStore(Ht, {
                    keyPath: Jt,
                    autoIncrement: true
                }).createIndex(Yt, Zt, {
                    unique: true
                });
                const r = t.store(Ht), i = n.map((e => r.put(e)));
                return PersistencePromise.waitFor(i);
            }));
        }(e, i)))), s = s.next((() => {
            !function __PRIVATE_createClientMetadataStore(e) {
                e.createObjectStore(mn, {
                    keyPath: pn
                });
            }(e);
        }))), n < 5 && r >= 5 && (s = s.next((() => this.D_(i)))), n < 6 && r >= 6 && (s = s.next((() => (function __PRIVATE_createDocumentGlobalStore(e) {
            e.createObjectStore(an);
        }(e), this.x_(i))))), n < 7 && r >= 7 && (s = s.next((() => this.C_(i)))), n < 8 && r >= 8 && (s = s.next((() => this.F_(e, i)))), 
        n < 9 && r >= 9 && (s = s.next((() => {
            // Multi-Tab used to manage its own changelog, but this has been moved
            // to the DbRemoteDocument object store itself. Since the previous change
            // log only contained transient data, we can drop its object store.
            !function __PRIVATE_dropRemoteDocumentChangesStore(e) {
                e.objectStoreNames.contains("remoteDocumentChanges") && e.deleteObjectStore("remoteDocumentChanges");
            }(e);
            // Note: Schema version 9 used to create a read time index for the
            // RemoteDocumentCache. This is now done with schema version 13.
                }))), n < 10 && r >= 10 && (s = s.next((() => this.O_(i)))), n < 11 && r >= 11 && (s = s.next((() => {
            !function __PRIVATE_createBundlesStore(e) {
                e.createObjectStore(gn, {
                    keyPath: yn
                });
            }(e), function __PRIVATE_createNamedQueriesStore(e) {
                e.createObjectStore(wn, {
                    keyPath: bn
                });
            }(e);
        }))), n < 12 && r >= 12 && (s = s.next((() => {
            !function __PRIVATE_createDocumentOverlayStore(e) {
                const t = e.createObjectStore(kn, {
                    keyPath: qn
                });
                t.createIndex($n, Kn, {
                    unique: false
                }), t.createIndex(Wn, Qn, {
                    unique: false
                });
            }(e);
        }))), n < 13 && r >= 13 && (s = s.next((() => function __PRIVATE_createRemoteDocumentCache(e) {
            const t = e.createObjectStore(tn, {
                keyPath: nn
            });
            t.createIndex(rn, sn), t.createIndex(_n, on);
        }(e))).next((() => this.M_(e, i))).next((() => e.deleteObjectStore(Wt)))), n < 14 && r >= 14 && (s = s.next((() => this.N_(e, i)))), 
        n < 15 && r >= 15 && (s = s.next((() => function __PRIVATE_createFieldIndex(e) {
            const t = e.createObjectStore(vn, {
                keyPath: Sn,
                autoIncrement: true
            });
            t.createIndex(Dn, xn, {
                unique: false
            });
            const n = e.createObjectStore(Cn, {
                keyPath: Fn
            });
            n.createIndex(On, Mn, {
                unique: false
            });
            const r = e.createObjectStore(Nn, {
                keyPath: Ln
            });
            r.createIndex(Bn, Un, {
                unique: false
            });
        }(e)))), n < 16 && r >= 16 && (
        // Clear the object stores to remove possibly corrupted index entries
        s = s.next((() => {
            t.objectStore(Cn).clear();
        })).next((() => {
            t.objectStore(Nn).clear();
        }))), n < 17 && r >= 17 && (s = s.next((() => {
            !function __PRIVATE_createGlobalsStore(e) {
                e.createObjectStore(Gn, {
                    keyPath: zn
                });
            }(e);
        }))), n < 18 && r >= 18 && util.isSafariOrWebkit() && (s = s.next((() => {
            t.objectStore(Cn).clear();
        })).next((() => {
            t.objectStore(Nn).clear();
        }))), s;
    }
    x_(e) {
        let t = 0;
        return e.store(Wt).jn(((e, n) => {
            t += __PRIVATE_dbDocumentSize(n);
        })).next((() => {
            const n = {
                byteSize: t
            };
            return e.store(an).put(un, n);
        }));
    }
    D_(e) {
        const t = e.store(zt), n = e.store(Ht);
        return t.Kn().next((t => PersistencePromise.forEach(t, (t => {
            const r = IDBKeyRange.bound([ t.userId, Ke ], [ t.userId, t.lastAcknowledgedBatchId ]);
            return n.Kn(Yt, r).next((n => PersistencePromise.forEach(n, (n => {
                __PRIVATE_hardAssert(n.userId === t.userId, 18650, "Cannot process batch from unexpected user", {
                    batchId: n.batchId
                });
                const r = __PRIVATE_fromDbMutationBatch(this.serializer, n);
                return removeMutationBatch(e, t.userId, r).next((() => {}));
            }))));
        }))));
    }
    /**
     * Ensures that every document in the remote document cache has a corresponding sentinel row
     * with a sequence number. Missing rows are given the most recently used sequence number.
     */    C_(e) {
        const t = e.store(Tn), n = e.store(Wt);
        return e.store(Vn).get(An).next((e => {
            const r = [];
            return n.jn(((n, i) => {
                const s = new ResourcePath(n), _ = function __PRIVATE_sentinelKey(e) {
                    return [ 0, __PRIVATE_encodeResourcePath(e) ];
                }(s);
                r.push(t.get(_).next((n => n ? PersistencePromise.resolve() : (n => t.put({
                    targetId: 0,
                    path: __PRIVATE_encodeResourcePath(n),
                    sequenceNumber: e.highestListenSequenceNumber
                }))(s))));
            })).next((() => PersistencePromise.waitFor(r)));
        }));
    }
    F_(e, t) {
        // Create the index.
        e.createObjectStore(dn, {
            keyPath: fn
        });
        const n = t.store(dn), r = new __PRIVATE_MemoryCollectionParentIndex, addEntry = e => {
            if (r.add(e)) {
                const t = e.lastSegment(), r = e.popLast();
                return n.put({
                    collectionId: t,
                    parent: __PRIVATE_encodeResourcePath(r)
                });
            }
        };
        // Helper to add an index entry iff we haven't already written it.
                // Index existing remote documents.
        return t.store(Wt).jn({
            zn: true
        }, ((e, t) => {
            const n = new ResourcePath(e);
            return addEntry(n.popLast());
        })).next((() => t.store(en).jn({
            zn: true
        }, (([e, t, n], r) => {
            const i = __PRIVATE_decodeResourcePath(t);
            return addEntry(i.popLast());
        }))));
    }
    O_(e) {
        const t = e.store(cn);
        return t.jn(((e, n) => {
            const r = __PRIVATE_fromDbTarget(this.serializer, n), i = __PRIVATE_toDbTarget(this.serializer, r);
            return t.put(i);
        }));
    }
    M_(e, t) {
        const n = t.store(Wt), r = [];
        return n.jn(((e, n) => {
            const i = t.store(tn), s = function __PRIVATE_extractKey(e) {
                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) : l(36783);
            }
            /**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (n).path.toArray(), _ = {
                prefixPath: s.slice(0, s.length - 2),
                collectionGroup: s[s.length - 2],
                documentId: s[s.length - 1],
                readTime: n.readTime || [ 0, 0 ],
                unknownDocument: n.unknownDocument,
                noDocument: n.noDocument,
                document: n.document,
                hasCommittedMutations: !!n.hasCommittedMutations
            };
            r.push(i.put(_));
        })).next((() => PersistencePromise.waitFor(r)));
    }
    N_(e, t) {
        const n = t.store(Ht), r = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.w_, this.serializer.qr);
        return n.Kn().next((e => {
            const n = new Map;
            return e.forEach((e => {
                let t = n.get(e.userId) ?? __PRIVATE_documentKeySet();
                __PRIVATE_fromDbMutationBatch(this.serializer, e).keys().forEach((e => t = t.add(e))), 
                n.set(e.userId, t);
            })), PersistencePromise.forEach(n, ((e, n) => {
                const s = new User(n), _ = __PRIVATE_IndexedDbDocumentOverlayCache.Kr(this.serializer, s), o = i.getIndexManager(s), a = __PRIVATE_IndexedDbMutationQueue.Kr(s, this.serializer, o, i.referenceDelegate);
                return new LocalDocumentsView(r, a, _, o).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t, __PRIVATE_ListenSequence.yn), e).next();
            }));
        }));
    }
}

function __PRIVATE_createQueryCache(e) {
    e.createObjectStore(Tn, {
        keyPath: Pn
    }).createIndex(Rn, In, {
        unique: true
    });
    // NOTE: This is unique only because the TargetId is the suffix.
    e.createObjectStore(cn, {
        keyPath: "targetId"
    }).createIndex(En, hn, {
        unique: true
    }), e.createObjectStore(Vn);
}

const sr = "IndexedDbPersistence", _r = 18e5, ar = 5e3, ur = "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.", cr = "main";

/**
 * Oldest acceptable age in milliseconds for client metadata before the client
 * is considered inactive and its associated data is garbage collected.
 */
/**
 * An IndexedDB-backed instance of Persistence. Data is stored persistently
 * across sessions.
 *
 * On Web only, the Firestore SDKs support shared access to its persistence
 * layer. This allows multiple browser tabs to read and write to IndexedDb and
 * to synchronize state even without network connectivity. Shared access is
 * currently optional and not enabled unless all clients invoke
 * `enablePersistence()` with `{synchronizeTabs:true}`.
 *
 * In multi-tab mode, if multiple clients are active at the same time, the SDK
 * will designate one client as the "primary client". An effort is made to pick
 * a visible, network-connected and active client, and this client is
 * responsible for letting other clients know about its presence. The primary
 * client writes a unique client-generated identifier (the client ID) to
 * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to
 * update this entry, another client can acquire the lease and take over as
 * primary.
 *
 * Some persistence operations in the SDK are designated as primary-client only
 * operations. This includes the acknowledgment of mutations and all updates of
 * remote documents. The effects of these operations are written to persistence
 * and then broadcast to other tabs via LocalStorage (see
 * `WebStorageSharedClientState`), which then refresh their state from
 * persistence.
 *
 * Similarly, the primary client listens to notifications sent by secondary
 * clients to discover persistence changes written by secondary clients, such as
 * the addition of new mutations and query targets.
 *
 * If multi-tab is not enabled and another tab already obtained the primary
 * lease, IndexedDbPersistence enters a failed state and all subsequent
 * operations will automatically fail.
 *
 * Additionally, there is an optimization so that when a tab is closed, the
 * primary lease is released immediately (this is especially important to make
 * sure that a refreshed tab is able to immediately re-acquire the primary
 * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload
 * since it is an asynchronous API. So in addition to attempting to give up the
 * lease, the leaseholder writes its client ID to a "zombiedClient" entry in
 * LocalStorage which acts as an indicator that another tab should go ahead and
 * take the primary lease immediately regardless of the current lease timestamp.
 *
 * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no
 * longer optional.
 */
class __PRIVATE_IndexedDbPersistence {
    constructor(
    /**
     * Whether to synchronize the in-memory state of multiple tabs and share
     * access to local persistence.
     */
    e, t, n, r, i, _, o, a, u, 
    /**
     * If set to true, forcefully obtains database access. Existing tabs will
     * no longer be able to access IndexedDB.
     */
    c, l = 18) {
        if (this.allowTabSynchronization = e, this.persistenceKey = t, this.clientId = n, 
        this.xt = i, this.window = _, this.document = o, this.L_ = u, this.B_ = c, this.U_ = l, 
        this.P_ = null, this.R_ = false, this.isPrimary = false, this.networkEnabled = true, 
        /** Our window.unload handler, if registered. */
        this.k_ = null, this.inForeground = false, 
        /** Our 'visibilitychange' listener if registered. */
        this.q_ = null, 
        /** The client metadata refresh task. */
        this.K_ = null, 
        /** The last time we garbage collected the client metadata object store. */
        this.W_ = Number.NEGATIVE_INFINITY, 
        /** A listener to notify on primary state changes. */
        this.Q_ = e => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.Je()) throw new s(aa.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
        this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r), this.G_ = t + cr, 
        this.serializer = new __PRIVATE_LocalSerializer(a), this.z_ = new __PRIVATE_SimpleDb(this.G_, this.U_, new __PRIVATE_SchemaConverter(this.serializer)), 
        this.I_ = new __PRIVATE_IndexedDbGlobalsCache, this.A_ = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), 
        this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), 
        this.d_ = new __PRIVATE_IndexedDbBundleCache, this.window && this.window.localStorage ? this.j_ = this.window.localStorage : (this.j_ = null, 
        false === c && __PRIVATE_logError(sr, "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page."));
    }
    /**
     * Attempt to start IndexedDb persistence.
     *
     * @returns Whether persistence was enabled.
     */    start() {
        // NOTE: This is expected to fail sometimes (in the case of another tab
        // already having the persistence lock), so it's the first thing we should
        // do.
        return this.H_().then((() => {
            if (!this.isPrimary && !this.allowTabSynchronization) 
            // Fail `start()` if `synchronizeTabs` is disabled and we cannot
            // obtain the primary lease.
            throw new s(aa.FAILED_PRECONDITION, ur);
            return this.J_(), this.Y_(), this.Z_(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (e => this.A_.getHighestSequenceNumber(e)));
        })).then((e => {
            this.P_ = new __PRIVATE_ListenSequence(e, this.L_);
        })).then((() => {
            this.R_ = true;
        })).catch((e => (this.z_ && this.z_.close(), Promise.reject(e))));
    }
    /**
     * Registers a listener that gets called when the primary state of the
     * instance changes. Upon registering, this listener is invoked immediately
     * with the current primary state.
     *
     * PORTING NOTE: This is only used for Web multi-tab.
     */    X_(e) {
        return this.Q_ = async t => {
            if (this.started) return e(t);
        }, e(this.isPrimary);
    }
    /**
     * Registers a listener that gets called when the database receives a
     * version change event indicating that it has deleted.
     *
     * PORTING NOTE: This is only used for Web multi-tab.
     */    setDatabaseDeletedListener(e) {
        this.z_.Ln((async t => {
            // Check if an attempt is made to delete IndexedDB.
            null === t.newVersion && await e();
        }));
    }
    /**
     * Adjusts the current network state in the client's metadata, potentially
     * affecting the primary lease.
     *
     * PORTING NOTE: This is only used for Web multi-tab.
     */    setNetworkEnabled(e) {
        this.networkEnabled !== e && (this.networkEnabled = e, 
        // Schedule a primary lease refresh for immediate execution. The eventual
        // lease update will be propagated via `primaryStateListener`.
        this.xt.enqueueAndForget((async () => {
            this.started && await this.H_();
        })));
    }
    /**
     * Updates the client metadata in IndexedDb and attempts to either obtain or
     * extend the primary lease for the local client. Asynchronously notifies the
     * primary state listener if the client either newly obtained or released its
     * primary lease.
     */    H_() {
        return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (e => __PRIVATE_clientMetadataStore(e).put({
            clientId: this.clientId,
            updateTimeMs: Date.now(),
            networkEnabled: this.networkEnabled,
            inForeground: this.inForeground
        }).next((() => {
            if (this.isPrimary) return this.eo(e).next((e => {
                e || (this.isPrimary = false, this.xt.enqueueRetryable((() => this.Q_(false))));
            }));
        })).next((() => this.no(e))).next((t => this.isPrimary && !t ? this.ro(e).next((() => false)) : !!t && this.io(e).next((() => true)))))).catch((e => {
            if (__PRIVATE_isIndexedDbTransactionError(e)) 
            // Proceed with the existing state. Any subsequent access to
            // IndexedDB will verify the lease.
            return __PRIVATE_logDebug(sr, "Failed to extend owner lease: ", e), this.isPrimary;
            if (!this.allowTabSynchronization) throw e;
            return __PRIVATE_logDebug(sr, "Releasing owner lease after error during lease refresh", e), 
            /* isPrimary= */ false;
        })).then((e => {
            this.isPrimary !== e && this.xt.enqueueRetryable((() => this.Q_(e))), this.isPrimary = e;
        }));
    }
    eo(e) {
        return __PRIVATE_primaryClientStore(e).get(Gt).next((e => PersistencePromise.resolve(this.so(e))));
    }
    _o(e) {
        return __PRIVATE_clientMetadataStore(e).delete(this.clientId);
    }
    /**
     * If the garbage collection threshold has passed, prunes the
     * RemoteDocumentChanges and the ClientMetadata store based on the last update
     * time of all clients.
     */    async oo() {
        if (this.isPrimary && !this.ao(this.W_, _r)) {
            this.W_ = Date.now();
            const e = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (e => {
                const t = __PRIVATE_getStore(e, mn);
                return t.Kn().next((e => {
                    const n = this.uo(e, _r), r = e.filter((e => -1 === n.indexOf(e)));
                    // Delete metadata for clients that are no longer considered active.
                    return PersistencePromise.forEach(r, (e => t.delete(e.clientId))).next((() => r));
                }));
            })).catch((() => []));
            // Delete potential leftover entries that may continue to mark the
            // inactive clients as zombied in LocalStorage.
            // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for
            // the client atomically, but we can't. So we opt to delete the IndexedDb
            // entries first to avoid potentially reviving a zombied client.
                        if (this.j_) for (const t of e) this.j_.removeItem(this.co(t.clientId));
        }
    }
    /**
     * Schedules a recurring timer to update the client metadata and to either
     * extend or acquire the primary lease if the client is eligible.
     */    Z_() {
        this.K_ = this.xt.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.H_().then((() => this.oo())).then((() => this.Z_()))));
    }
    /** Checks whether `client` is the local client. */    so(e) {
        return !!e && e.ownerId === this.clientId;
    }
    /**
     * Evaluate the state of all active clients and determine whether the local
     * client is or can act as the holder of the primary lease. Returns whether
     * the client is eligible for the lease, but does not actually acquire it.
     * May return 'false' even if there is no active leaseholder and another
     * (foreground) client should become leaseholder instead.
     */    no(e) {
        if (this.B_) return PersistencePromise.resolve(true);
        return __PRIVATE_primaryClientStore(e).get(Gt).next((t => {
            // A client is eligible for the primary lease if:
            // - its network is enabled and the client's tab is in the foreground.
            // - its network is enabled and no other client's tab is in the
            //   foreground.
            // - every clients network is disabled and the client's tab is in the
            //   foreground.
            // - every clients network is disabled and no other client's tab is in
            //   the foreground.
            // - the `forceOwningTab` setting was passed in.
            if (null !== t && this.ao(t.leaseTimestampMs, ar) && !this.lo(t.ownerId)) {
                if (this.so(t) && this.networkEnabled) return true;
                if (!this.so(t)) {
                    if (!t.allowTabSynchronization) 
                    // Fail the `canActAsPrimary` check if the current leaseholder has
                    // not opted into multi-tab synchronization. If this happens at
                    // client startup, we reject the Promise returned by
                    // `enablePersistence()` and the user can continue to use Firestore
                    // with in-memory persistence.
                    // If this fails during a lease refresh, we will instead block the
                    // AsyncQueue from executing further operations. Note that this is
                    // acceptable since mixing & matching different `synchronizeTabs`
                    // settings is not supported.
                    // TODO(b/114226234): Remove this check when `synchronizeTabs` can
                    // no longer be turned off.
                    throw new s(aa.FAILED_PRECONDITION, ur);
                    return false;
                }
            }
            return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e).Kn().next((e => void 0 === this.uo(e, ar).find((e => {
                if (this.clientId !== e.clientId) {
                    const t = !this.networkEnabled && e.networkEnabled, n = !this.inForeground && e.inForeground, r = this.networkEnabled === e.networkEnabled;
                    if (t || n && r) return true;
                }
                return false;
            }))));
        })).next((e => (this.isPrimary !== e && __PRIVATE_logDebug(sr, `Client ${e ? "is" : "is not"} eligible for a primary lease.`), 
        e)));
    }
    async shutdown() {
        // The shutdown() operations are idempotent and can be called even when
        // start() aborted (e.g. because it couldn't acquire the persistence lease).
        this.R_ = false, this.Eo(), this.K_ && (this.K_.cancel(), this.K_ = null), this.ho(), 
        this.To(), 
        // Use `SimpleDb.runTransaction` directly to avoid failing if another tab
        // has obtained the primary lease.
        await this.z_.runTransaction("shutdown", "readwrite", [ Qt, mn ], (e => {
            const t = new __PRIVATE_IndexedDbTransaction(e, __PRIVATE_ListenSequence.yn);
            return this.ro(t).next((() => this._o(t)));
        })), this.z_.close(), 
        // Remove the entry marking the client as zombied from LocalStorage since
        // we successfully deleted its metadata from IndexedDb.
        this.Po();
    }
    /**
     * Returns clients that are not zombied and have an updateTime within the
     * provided threshold.
     */    uo(e, t) {
        return e.filter((e => this.ao(e.updateTimeMs, t) && !this.lo(e.clientId)));
    }
    /**
     * Returns the IDs of the clients that are currently active. If multi-tab
     * is not supported, returns an array that only contains the local client's
     * ID.
     *
     * PORTING NOTE: This is only used for Web multi-tab.
     */    Ro() {
        return this.runTransaction("getActiveClients", "readonly", (e => __PRIVATE_clientMetadataStore(e).Kn().next((e => this.uo(e, _r).map((e => e.clientId))))));
    }
    get started() {
        return this.R_;
    }
    getGlobalsCache() {
        return this.I_;
    }
    getMutationQueue(e, t) {
        return __PRIVATE_IndexedDbMutationQueue.Kr(e, this.serializer, t, this.referenceDelegate);
    }
    getTargetCache() {
        return this.A_;
    }
    getRemoteDocumentCache() {
        return this.remoteDocumentCache;
    }
    getIndexManager(e) {
        return new __PRIVATE_IndexedDbIndexManager(e, this.serializer.qr.databaseId);
    }
    getDocumentOverlayCache(e) {
        return __PRIVATE_IndexedDbDocumentOverlayCache.Kr(this.serializer, e);
    }
    getBundleCache() {
        return this.d_;
    }
    runTransaction(e, t, n) {
        __PRIVATE_logDebug(sr, "Starting transaction:", e);
        const r = "readonly" === t ? "readonly" : "readwrite", i = 
        /** Returns the object stores for the provided schema. */
        function __PRIVATE_getObjectStores(e) {
            return 18 === e ? tr : 17 === e ? er : 16 === e ? Xn : 15 === e ? Zn : 14 === e ? Yn : 13 === e ? Jn : 12 === e ? Hn : 11 === e ? jn : void l(60245);
        }(this.U_);
        let _;
        // Do all transactions as readwrite against all object stores, since we
        // are the only reader/writer.
                return this.z_.runTransaction(e, r, i, (r => (_ = new __PRIVATE_IndexedDbTransaction(r, this.P_ ? this.P_.next() : __PRIVATE_ListenSequence.yn), 
        "readwrite-primary" === t ? this.eo(_).next((e => !!e || this.no(_))).next((t => {
            if (!t) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`), 
            this.isPrimary = false, this.xt.enqueueRetryable((() => this.Q_(false))), new s(aa.FAILED_PRECONDITION, pt);
            return n(_);
        })).next((e => this.io(_).next((() => e)))) : this.Io(_).next((() => n(_)))))).then((e => (_.raiseOnCommittedEvent(), 
        e)));
    }
    /**
     * Verifies that the current tab is the primary leaseholder or alternatively
     * that the leaseholder has opted into multi-tab synchronization.
     */
    // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer
    // be turned off.
    Io(e) {
        return __PRIVATE_primaryClientStore(e).get(Gt).next((e => {
            if (null !== e && this.ao(e.leaseTimestampMs, ar) && !this.lo(e.ownerId) && !this.so(e) && !(this.B_ || this.allowTabSynchronization && e.allowTabSynchronization)) throw new s(aa.FAILED_PRECONDITION, ur);
        }));
    }
    /**
     * Obtains or extends the new primary lease for the local client. This
     * method does not verify that the client is eligible for this lease.
     */    io(e) {
        const t = {
            ownerId: this.clientId,
            allowTabSynchronization: this.allowTabSynchronization,
            leaseTimestampMs: Date.now()
        };
        return __PRIVATE_primaryClientStore(e).put(Gt, t);
    }
    static Je() {
        return __PRIVATE_SimpleDb.Je();
    }
    /** Checks the primary lease and removes it if we are the current primary. */    ro(e) {
        const t = __PRIVATE_primaryClientStore(e);
        return t.get(Gt).next((e => this.so(e) ? (__PRIVATE_logDebug(sr, "Releasing primary lease."), 
        t.delete(Gt)) : PersistencePromise.resolve()));
    }
    /** Verifies that `updateTimeMs` is within `maxAgeMs`. */    ao(e, t) {
        const n = Date.now();
        return !(e < n - t) && (!(e > n) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${n}`), 
        false));
    }
    J_() {
        null !== this.document && "function" == typeof this.document.addEventListener && (this.q_ = () => {
            this.xt.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState, 
            this.H_())));
        }, this.document.addEventListener("visibilitychange", this.q_), this.inForeground = "visible" === this.document.visibilityState);
    }
    ho() {
        this.q_ && (this.document.removeEventListener("visibilitychange", this.q_), this.q_ = null);
    }
    /**
     * Attaches a window.unload handler that will synchronously write our
     * clientId to a "zombie client id" location in LocalStorage. This can be used
     * by tabs trying to acquire the primary lease to determine that the lease
     * is no longer valid even if the timestamp is recent. This is particularly
     * important for the refresh case (so the tab correctly re-acquires the
     * primary lease). LocalStorage is used for this rather than IndexedDb because
     * it is a synchronous API and so can be used reliably from  an unload
     * handler.
     */    Y_() {
        "function" == typeof this.window?.addEventListener && (this.k_ = () => {
            // Note: In theory, this should be scheduled on the AsyncQueue since it
            // accesses internal state. We execute this code directly during shutdown
            // to make sure it gets a chance to run.
            this.Eo();
            const e = /(?:Version|Mobile)\/1[456]/;
            util.isSafari() && (navigator.appVersion.match(e) || navigator.userAgent.match(e)) && 
            // On Safari 14, 15, and 16, we do not run any cleanup actions as it might
            // trigger a bug that prevents Safari from re-opening IndexedDB during
            // the next page load.
            // See https://bugs.webkit.org/show_bug.cgi?id=226547
            this.xt.enterRestrictedMode(/* purgeExistingTasks= */ true), this.xt.enqueueAndForget((() => this.shutdown()));
        }, this.window.addEventListener("pagehide", this.k_));
    }
    To() {
        this.k_ && (this.window.removeEventListener("pagehide", this.k_), this.k_ = null);
    }
    /**
     * Returns whether a client is "zombied" based on its LocalStorage entry.
     * Clients become zombied when their tab closes without running all of the
     * cleanup logic in `shutdown()`.
     */    lo(e) {
        try {
            const t = null !== this.j_?.getItem(this.co(e));
            return __PRIVATE_logDebug(sr, `Client '${e}' ${t ? "is" : "is not"} zombied in LocalStorage`), 
            t;
        } catch (e) {
            // Gracefully handle if LocalStorage isn't working.
            return __PRIVATE_logError(sr, "Failed to get zombied client id.", e), false;
        }
    }
    /**
     * Record client as zombied (a client that had its tab closed). Zombied
     * clients are ignored during primary tab selection.
     */    Eo() {
        if (this.j_) try {
            this.j_.setItem(this.co(this.clientId), String(Date.now()));
        } catch (e) {
            // Gracefully handle if LocalStorage isn't available / working.
            __PRIVATE_logError("Failed to set zombie client id.", e);
        }
    }
    /** Removes the zombied client entry if it exists. */    Po() {
        if (this.j_) try {
            this.j_.removeItem(this.co(this.clientId));
        } catch (e) {
            // Ignore
        }
    }
    co(e) {
        return `firestore_zombie_${this.persistenceKey}_${e}`;
    }
}

/**
 * Helper to get a typed SimpleDbStore for the primary client object store.
 */ function __PRIVATE_primaryClientStore(e) {
    return __PRIVATE_getStore(e, Qt);
}

/**
 * Helper to get a typed SimpleDbStore for the client metadata object store.
 */ function __PRIVATE_clientMetadataStore(e) {
    return __PRIVATE_getStore(e, mn);
}

/**
 * Generates a string used as a prefix when storing data in IndexedDB and
 * LocalStorage.
 */ function __PRIVATE_indexedDbStoragePrefix(e, t) {
    // Use two different prefix formats:
    //   * firestore / persistenceKey / projectID . databaseID / ...
    //   * firestore / persistenceKey / projectID / ...
    // projectIDs are DNS-compatible names and cannot contain dots
    // so there's no danger of collisions.
    let n = e.projectId;
    return e.isDefaultDatabase || (n += "." + e.database), "firestore/" + t + "/" + n + "/";
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A set of changes to what documents are currently in view and out of view for
 * a given query. These changes are sent to the LocalStore by the View (via
 * the SyncEngine) and are used to pin / unpin documents as appropriate.
 */
class __PRIVATE_LocalViewChanges {
    constructor(e, t, n, r) {
        this.targetId = e, this.fromCache = t, this.Ao = n, this.Vo = r;
    }
    static fo(e, t) {
        let n = __PRIVATE_documentKeySet(), r = __PRIVATE_documentKeySet();
        for (const e of t.docChanges) switch (e.type) {
          case 0 /* ChangeType.Added */ :
            n = n.add(e.doc.key);
            break;

          case 1 /* ChangeType.Removed */ :
            r = r.add(e.doc.key);
 // do nothing
                }
        return new __PRIVATE_LocalViewChanges(e, t.fromCache, n, r);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ function __PRIVATE_compareByKey(e, t) {
    return DocumentKey.comparator(e.key, t.key);
}

/**
 * @license
 * Copyright 2023 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A tracker to keep a record of important details during database local query
 * execution.
 */ class QueryContext {
    constructor() {
        /**
         * Counts the number of documents passed through during local query execution.
         */
        this._documentReadCount = 0;
    }
    get documentReadCount() {
        return this._documentReadCount;
    }
    incrementDocumentReadCount(e) {
        this._documentReadCount += e;
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * The Firestore query engine.
 *
 * Firestore queries can be executed in three modes. The Query Engine determines
 * what mode to use based on what data is persisted. The mode only determines
 * the runtime complexity of the query - the result set is equivalent across all
 * implementations.
 *
 * The Query engine will use indexed-based execution if a user has configured
 * any index that can be used to execute query (via `setIndexConfiguration()`).
 * Otherwise, the engine will try to optimize the query by re-using a previously
 * persisted query result. If that is not possible, the query will be executed
 * via a full collection scan.
 *
 * Index-based execution is the default when available. The query engine
 * supports partial indexed execution and merges the result from the index
 * lookup with documents that have not yet been indexed. The index evaluation
 * matches the backend's format and as such, the SDK can use indexing for all
 * queries that the backend supports.
 *
 * If no index exists, the query engine tries to take advantage of the target
 * document mapping in the TargetCache. These mappings exists for all queries
 * that have been synced with the backend at least once and allow the query
 * engine to only read documents that previously matched a query plus any
 * documents that were edited after the query was last listened to.
 *
 * There are some cases when this optimization is not guaranteed to produce
 * the same results as full collection scans. In these cases, query
 * processing falls back to full scans. These cases are:
 *
 * - Limit queries where a document that matched the query previously no longer
 *   matches the query.
 *
 * - Limit queries where a document edit may cause the document to sort below
 *   another document that is in the local cache.
 *
 * - Queries that have never been CURRENT or free of limbo documents.
 */
class __PRIVATE_QueryEngine {
    constructor() {
        this.mo = false, this.po = false, 
        /**
         * SDK only decides whether it should create index when collection size is
         * larger than this.
         */
        this.yo = 100, this.wo = 
        /**
 * This cost represents the evaluation result of
 * (([index, docKey] + [docKey, docContent]) per document in the result set)
 * / ([docKey, docContent] per documents in full collection scan) coming from
 * experiment [enter PR experiment URL here].
 */
        function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument() {
            // These values were derived from an experiment where several members of the
            // Firestore SDK team ran a performance test in various environments.
            // Googlers can see b/299284287 for details.
            return util.isSafari() ? 8 : __PRIVATE_getAndroidVersion(util.getUA()) > 0 ? 6 : 4;
        }();
    }
    /** Sets the document view to query against. */    initialize(e, t) {
        this.bo = e, this.indexManager = t, this.mo = true;
    }
    /** Returns all local documents matching the specified query. */    getDocumentsMatchingQuery(e, t, n, r) {
        // Stores the result from executing the query; using this object is more
        // convenient than passing the result between steps of the persistence
        // transaction and improves readability comparatively.
        const i = {
            result: null
        };
        return this.vo(e, t).next((e => {
            i.result = e;
        })).next((() => {
            if (!i.result) return this.So(e, t, r, n).next((e => {
                i.result = e;
            }));
        })).next((() => {
            if (i.result) return;
            const n = new QueryContext;
            return this.Do(e, t, n).next((r => {
                if (i.result = r, this.po) return this.xo(e, t, n, r.size);
            }));
        })).next((() => i.result));
    }
    xo(e, t, n, r) {
        return __PRIVATE_isPipeline(t) ? PersistencePromise.resolve() : n.documentReadCount < this.yo ? (__PRIVATE_getLogLevel() <= logger.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.yo, "documents"), 
        PersistencePromise.resolve()) : (__PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Query:", __PRIVATE_stringifyQuery(t), "scans", n.documentReadCount, "local documents and returns", r, "documents as results."), 
        n.documentReadCount > this.wo * r ? (__PRIVATE_getLogLevel() <= logger.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."), 
        this.indexManager.createTargetIndexes(e, __PRIVATE_queryToTarget(t))) : PersistencePromise.resolve());
    }
    /**
     * Performs an indexed query that evaluates the query based on a collection's
     * persisted index values. Returns `null` if an index is not available.
     */    vo(e, t) {
        if (__PRIVATE_isPipeline(t)) return PersistencePromise.resolve(null);
        let n = t;
        if (__PRIVATE_queryMatchesAllDocuments(n)) 
        // Queries that match all documents don't benefit from using
        // key-based lookups. It is more efficient to scan all documents in a
        // collection, rather than to perform individual lookups.
        return PersistencePromise.resolve(null);
        let r = __PRIVATE_queryToTarget(n);
        return this.indexManager.getIndexType(e, r).next((t => 0 /* IndexType.NONE */ === t ? null : (null !== n.limit && 1 /* IndexType.PARTIAL */ === t && (
        // We cannot apply a limit for targets that are served using a partial
        // index. If a partial index will be used to serve the target, the
        // query may return a superset of documents that match the target
        // (e.g. if the index doesn't include all the target's filters), or
        // may return the correct set of documents in the wrong order (e.g. if
        // the index doesn't include a segment for one of the orderBys).
        // Therefore, a limit should not be applied in such cases.
        n = __PRIVATE_queryWithLimit(n, null, "F" /* LimitType.First */), r = __PRIVATE_queryToTarget(n)), 
        this.indexManager.getDocumentsMatchingTarget(e, r).next((t => {
            const i = __PRIVATE_documentKeySet(...t);
            return this.bo.getDocuments(e, i).next((t => this.indexManager.getMinOffset(e, r).next((r => {
                const s = this.Co(n, t);
                return this.Fo(n, s, i, r.readTime) ? this.vo(e, __PRIVATE_queryWithLimit(n, null, "F" /* LimitType.First */)) : this.Oo(e, s, n, r);
            }))));
        })))));
    }
    /**
     * Performs a query based on the target's persisted query mapping. Returns
     * `null` if the mapping is not available or cannot be used.
     */    So(e, t, n, r) {
        return (__PRIVATE_isPipeline(t) ? function __PRIVATE_pipelineMatchesAllDocuments(e) {
            for (const t of e.stages) {
                if (t instanceof v || t instanceof I) return false;
                // Check if it's the special 'exists(__name__)' case
                                if (t instanceof A) {
                    if (t.condition instanceof __PRIVATE_BooleanFunctionExpression && "exists" === t.condition._expr.name && t.condition._expr.params[0] instanceof o && t.condition._expr.params[0].fieldName === Ce) continue;
                    return false;
                }
            }
            return true;
        }(t) : __PRIVATE_queryMatchesAllDocuments(t)) || r.isEqual(SnapshotVersion.min()) ? PersistencePromise.resolve(null) : this.bo.getDocuments(e, n).next((i => {
            const s = this.Co(t, i);
            return this.Fo(t, s, n, r) ? PersistencePromise.resolve(null) : (__PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Re-using previous result from %s to execute query: %s", r.toString(), __PRIVATE_stringifyQueryOrPipeline(t)), 
            this.Oo(e, s, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, Xe)).next((e => e)));
        }));
        // Queries that have never seen a snapshot without limbo free documents
        // should also be run as a full collection scan.
        }
    /** Applies the query filter and sorting to the provided documents.  */    Co(e, t) {
        let n, r;
        return __PRIVATE_isPipeline(e) ? (
        // TODO(pipeline): the order here does not actually matter, not until we implement
        // refill logic for pipelines as well.
        n = new SortedSet(__PRIVATE_compareByKey), r = t => __PRIVATE_pipelineMatches(e, t)) : (
        // Sort the documents and re-apply the query filter since previously
        // matching documents do not necessarily still match the query.
        n = new SortedSet(__PRIVATE_newQueryComparator(e)), r = t => __PRIVATE_queryMatches(e, t)), 
        t.forEach(((e, t) => {
            r(t) && (n = n.add(t));
        })), n;
    }
    /**
     * Determines if a limit query needs to be refilled from cache, making it
     * ineligible for index-free execution.
     *
     * @param query - The query.
     * @param sortedPreviousResults - The documents that matched the query when it
     * was last synchronized, sorted by the query's comparator.
     * @param remoteKeys - The document keys that matched the query at the last
     * snapshot.
     * @param limboFreeSnapshotVersion - The version of the snapshot when the
     * query was last synchronized.
     */    Fo(e, t, n, r) {
        // TODO(pipeline): For pipelines it is simple for now, we refill for all limit/offset.
        // we should implement a similar approach for query at some point.
        if (__PRIVATE_isPipeline(e)) return function __PRIVATE_pipelineHasRanges(e) {
            return e.stages.some((e => e instanceof v || e instanceof I));
        }(e);
        if (null === e.limit) 
        // Queries without limits do not need to be refilled.
        return false;
        if (n.size !== t.size) 
        // The query needs to be refilled if a previously matching document no
        // longer matches.
        return true;
        // Limit queries are not eligible for index-free query execution if there is
        // a potential that an older document from cache now sorts before a document
        // that was previously part of the limit. This, however, can only happen if
        // the document at the edge of the limit goes out of limit.
        // If a document that is not the limit boundary sorts differently,
        // the boundary of the limit itself did not change and documents from cache
        // will continue to be "rejected" by this boundary. Therefore, we can ignore
        // any modifications that don't affect the last document.
                const i = "F" /* LimitType.First */ === e.limitType ? t.last() : t.first();
        return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0);
    }
    Do(e, t, n) {
        return __PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Using full collection scan to execute query:", __PRIVATE_stringifyQueryOrPipeline(t)), 
        this.bo.getDocumentsMatchingQuery(e, t, IndexOffset.min(), n);
    }
    /**
     * Combines the results from an indexed execution with the remaining documents
     * that have not yet been indexed.
     */    Oo(e, t, n, r) {
        // Retrieve all results for documents that were updated since the offset.
        return this.bo.getDocumentsMatchingQuery(e, n, r).next((e => (
        // Merge with existing results
        t.forEach((t => {
            e = e.insert(t.key, t);
        })), e)));
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const lr = "LocalStore", Er = 3e8;

/**
 * The maximum time to leave a resume token buffered without writing it out.
 * This value is arbitrary: it's long enough to avoid several writes
 * (possibly indefinitely if updates come more frequently than this) but
 * short enough that restarting after crashing will still have a pretty
 * recent resume token.
 */
/**
 * Implements `LocalStore` interface.
 *
 * Note: some field defined in this class might have public access level, but
 * the class is not exported so they are only accessible from this module.
 * This is useful to implement optional features (like bundles) in free
 * functions, such that they are tree-shakeable.
 */
class __PRIVATE_LocalStoreImpl {
    constructor(
    /** Manages our in-memory or durable persistence. */
    e, t, n, r) {
        this.persistence = e, this.Mo = t, this.serializer = r, 
        /**
         * Maps a targetID to data about its target.
         *
         * PORTING NOTE: We are using an immutable data structure on Web to make re-runs
         * of `applyRemoteEvent()` idempotent.
         */
        this.No = new SortedMap(__PRIVATE_primitiveComparator), 
        /** Maps a target to its targetID. */
        // TODO(wuandy): Evaluate if TargetId can be part of Target.
        this.Lo = new ObjectMap((e => __PRIVATE_canonifyTargetOrPipeline(e)), __PRIVATE_targetOrPipelineEqual), 
        /**
         * A per collection group index of the last read time processed by
         * `getNewDocumentChanges()`.
         *
         * PORTING NOTE: This is only used for multi-tab synchronization.
         */
        this.Bo = new Map, this.Uo = e.getRemoteDocumentCache(), this.A_ = e.getTargetCache(), 
        this.d_ = e.getBundleCache(), this.ko(n);
    }
    ko(e) {
        // TODO(indexing): Add spec tests that test these components change after a
        // user change
        this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e), this.indexManager = this.persistence.getIndexManager(e), 
        this.mutationQueue = this.persistence.getMutationQueue(e, this.indexManager), this.localDocuments = new LocalDocumentsView(this.Uo, this.mutationQueue, this.documentOverlayCache, this.indexManager), 
        this.Uo.setIndexManager(this.indexManager), this.Mo.initialize(this.localDocuments, this.indexManager);
    }
    collectGarbage(e) {
        return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (t => e.collect(t, this.No)));
    }
}

function __PRIVATE_newLocalStore(
/** Manages our in-memory or durable persistence. */
e, t, n, r) {
    return new __PRIVATE_LocalStoreImpl(e, t, n, r);
}

/**
 * Tells the LocalStore that the currently authenticated user has changed.
 *
 * In response the local store switches the mutation queue to the new user and
 * returns any resulting document changes.
 */
// PORTING NOTE: Android and iOS only return the documents affected by the
// change.
async function __PRIVATE_localStoreHandleUserChange(e, t) {
    const n = __PRIVATE_debugCast(e);
    return await n.persistence.runTransaction("Handle user change", "readonly", (e => {
        // Swap out the mutation queue, grabbing the pending mutation batches
        // before and after.
        let r;
        return n.mutationQueue.getAllMutationBatches(e).next((i => (r = i, n.ko(t), n.mutationQueue.getAllMutationBatches(e)))).next((t => {
            const i = [], s = [];
            // Union the old/new changed keys.
            let _ = __PRIVATE_documentKeySet();
            for (const e of r) {
                i.push(e.batchId);
                for (const t of e.mutations) _ = _.add(t.key);
            }
            for (const e of t) {
                s.push(e.batchId);
                for (const t of e.mutations) _ = _.add(t.key);
            }
            // Return the set of all (potentially) changed documents and the list
            // of mutation batch IDs that were affected by change.
                        return n.localDocuments.getDocuments(e, _).next((e => ({
                qo: e,
                removedBatchIds: i,
                addedBatchIds: s
            })));
        }));
    }));
}

/* Accepts locally generated Mutations and commit them to storage. */
/**
 * Acknowledges the given batch.
 *
 * On the happy path when a batch is acknowledged, the local store will
 *
 *  + remove the batch from the mutation queue;
 *  + apply the changes to the remote document cache;
 *  + recalculate the latency compensated view implied by those changes (there
 *    may be mutations in the queue that affect the documents but haven't been
 *    acknowledged yet); and
 *  + give the changed documents back the sync engine
 *
 * @returns The resulting (modified) documents.
 */
function __PRIVATE_localStoreAcknowledgeBatch(e, t) {
    const n = __PRIVATE_debugCast(e);
    return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (e => {
        const r = t.batch.keys(), i = n.Uo.newChangeBuffer({
            trackRemovals: true
        });
        return function __PRIVATE_applyWriteToRemoteDocuments(e, t, n, r) {
            const i = n.batch, s = i.keys();
            let _ = PersistencePromise.resolve();
            return s.forEach((e => {
                _ = _.next((() => r.getEntry(t, e))).next((t => {
                    const s = n.docVersions.get(e);
                    __PRIVATE_hardAssert(null !== s, 48541), t.version.compareTo(s) < 0 && (i.applyToRemoteDocument(t, n), 
                    t.isValidDocument() && (
                    // We use the commitVersion as the readTime rather than the
                    // document's updateTime since the updateTime is not advanced
                    // for updates that do not modify the underlying document.
                    t.setReadTime(n.commitVersion), r.addEntry(t)));
                }));
            })), _.next((() => e.mutationQueue.removeMutationBatch(t, i)));
        }
        /** Returns the local view of the documents affected by a mutation batch. */
        // PORTING NOTE: Multi-Tab only.
        (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) {
            let t = __PRIVATE_documentKeySet();
            for (let n = 0; n < e.mutationResults.length; ++n) {
                e.mutationResults[n].transformResults.length > 0 && (t = t.add(e.batch.mutations[n].key));
            }
            return t;
        }
        /**
 * Removes mutations from the MutationQueue for the specified batch;
 * LocalDocuments will be recalculated.
 *
 * @returns The resulting modified documents.
 */ (t)))).next((() => n.localDocuments.getDocuments(e, r)));
    }));
}

/**
 * Returns the last consistent snapshot processed (used by the RemoteStore to
 * determine whether to buffer incoming snapshots from the backend).
 */
function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e) {
    const t = __PRIVATE_debugCast(e);
    return t.persistence.runTransaction("Get last remote snapshot version", "readonly", (e => t.A_.getLastRemoteSnapshotVersion(e)));
}

/**
 * Updates the "ground-state" (remote) documents. We assume that the remote
 * event reflects any write batches that have been acknowledged or rejected
 * (i.e. we do not re-apply local mutations to updates from this event).
 *
 * LocalDocuments are re-calculated if there are remaining mutations in the
 * queue.
 */ function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e, t) {
    const n = __PRIVATE_debugCast(e), r = t.snapshotVersion;
    let i = n.No;
    return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (e => {
        const s = n.Uo.newChangeBuffer({
            trackRemovals: true
        });
        // Reset newTargetDataByTargetMap in case this transaction gets re-run.
                i = n.No;
        const _ = [];
        t.targetChanges.forEach(((s, o) => {
            const a = i.get(o);
            if (!a) return;
            // Only update the remote keys if the target is still active. This
            // ensures that we can persist the updated target data along with
            // the updated assignment.
                        _.push(n.A_.removeMatchingKeys(e, s.removedDocuments, o).next((() => n.A_.addMatchingKeys(e, s.addedDocuments, o))));
            let u = a.withSequenceNumber(e.currentSequenceNumber);
            null !== t.targetMismatches.get(o) ? u = u.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s.resumeToken.approximateByteSize() > 0 && (u = u.withResumeToken(s.resumeToken, r)), 
            i = i.insert(o, u), 
            // Update the target data if there are target changes (or if
            // sufficient time has passed since the last update).
            /**
 * Returns true if the newTargetData should be persisted during an update of
 * an active target. TargetData should always be persisted when a target is
 * being released and should not call this function.
 *
 * While the target is active, TargetData updates can be omitted when nothing
 * about the target has changed except metadata like the resume token or
 * snapshot version. Occasionally it's worth the extra write to prevent these
 * values from getting too stale after a crash, but this doesn't have to be
 * too frequent.
 */
            function __PRIVATE_shouldPersistTargetData(e, t, n) {
                // Always persist target data if we don't already have a resume token.
                if (0 === e.resumeToken.approximateByteSize()) return true;
                // Don't allow resume token changes to be buffered indefinitely. This
                // allows us to be reasonably up-to-date after a crash and avoids needing
                // to loop over all active queries on shutdown. Especially in the browser
                // we may not get time to do anything interesting while the current tab is
                // closing.
                                const r = t.snapshotVersion.toMicroseconds() - e.snapshotVersion.toMicroseconds();
                if (r >= Er) return true;
                // Otherwise if the only thing that has changed about a target is its resume
                // token it's not worth persisting. Note that the RemoteStore keeps an
                // in-memory view of the currently active targets which includes the current
                // resume token, so stream failure or user changes will still use an
                // up-to-date resume token regardless of what we do here.
                                const i = n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size;
                return i > 0;
            }
            /**
 * Notifies local store of the changed views to locally pin documents.
 */ (a, u, s) && _.push(n.A_.updateTargetData(e, u));
        }));
        let o = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();
        // HACK: The only reason we allow a null snapshot version is so that we
        // can synthesize remote events when we get permission denied errors while
        // trying to resolve the state of a locally cached document that is in
        // limbo.
        if (t.documentUpdates.forEach((r => {
            t.resolvedLimboDocuments.has(r) && _.push(n.persistence.referenceDelegate.updateLimboDocument(e, r));
        })), 
        // Each loop iteration only affects its "own" doc, so it's safe to get all
        // the remote documents in advance in a single call.
        _.push(__PRIVATE_populateDocumentChangeBuffer(e, s, t.documentUpdates).next((e => {
            o = e.$o, a = e.Ko;
        }))), !r.isEqual(SnapshotVersion.min())) {
            const t = n.A_.getLastRemoteSnapshotVersion(e).next((t => n.A_.setTargetsMetadata(e, e.currentSequenceNumber, r)));
            _.push(t);
        }
        return PersistencePromise.waitFor(_).next((() => s.apply(e))).next((() => n.localDocuments.getLocalViewOfDocuments(e, o, a))).next((() => o));
    })).then((e => (n.No = i, e)));
}

/**
 * Populates document change buffer with documents from backend or a bundle.
 * Returns the document changes resulting from applying those documents, and
 * also a set of documents whose existence state are changed as a result.
 *
 * @param txn - Transaction to use to read existing documents from storage.
 * @param documentBuffer - Document buffer to collect the resulted changes to be
 *        applied to storage.
 * @param documents - Documents to be applied.
 */ function __PRIVATE_populateDocumentChangeBuffer(e, t, n) {
    let r = __PRIVATE_documentKeySet(), i = __PRIVATE_documentKeySet();
    return n.forEach((e => r = r.add(e))), t.getEntries(e, r).next((e => {
        let r = __PRIVATE_mutableDocumentMap();
        return n.forEach(((n, s) => {
            const _ = e.get(n);
            // Check if see if there is a existence state change for this document.
                        s.isFoundDocument() !== _.isFoundDocument() && (i = i.add(n)), 
            // Note: The order of the steps below is important, since we want
            // to ensure that rejected limbo resolutions (which fabricate
            // NoDocuments with SnapshotVersion.min()) never add documents to
            // cache.
            s.isNoDocument() && s.version.isEqual(SnapshotVersion.min()) ? (
            // NoDocuments with SnapshotVersion.min() are used in manufactured
            // events. We remove these documents from cache since we lost
            // access.
            t.removeEntry(n, s.readTime), r = r.insert(n, s)) : !_.isValidDocument() || s.version.compareTo(_.version) > 0 || 0 === s.version.compareTo(_.version) && _.hasPendingWrites ? (t.addEntry(s), 
            r = r.insert(n, s)) : __PRIVATE_logDebug(lr, "Ignoring outdated watch update for ", n, ". Current version:", _.version, " Watch version:", s.version);
        })), {
            $o: r,
            Ko: i
        };
    }));
}

/**
 * Gets the mutation batch after the passed in batchId in the mutation queue
 * or null if empty.
 * @param afterBatchId - If provided, the batch to search after.
 * @returns The next mutation or null if there wasn't one.
 */
function __PRIVATE_localStoreGetNextMutationBatch(e, t) {
    const n = __PRIVATE_debugCast(e);
    return n.persistence.runTransaction("Get next mutation batch", "readonly", (e => (void 0 === t && (t = Ke), 
    n.mutationQueue.getNextMutationBatchAfterBatchId(e, t))));
}

/**
 * Reads the current value of a Document with a given key or null if not
 * found - used for testing.
 */
/**
 * Assigns the given target an internal ID so that its results can be pinned so
 * they don't get GC'd. A target must be allocated in the local store before
 * the store can be used to manage its view.
 *
 * Allocating an already allocated `Target` will return the existing `TargetData`
 * for that `Target`.
 */
function __PRIVATE_localStoreAllocateTarget(e, t) {
    const n = __PRIVATE_debugCast(e);
    return n.persistence.runTransaction("Allocate target", "readwrite", (e => {
        let r;
        return n.A_.getTargetData(e, t).next((i => i ? (
        // This target has been listened to previously, so reuse the
        // previous targetID.
        // TODO(mcg): freshen last accessed date?
        r = i, PersistencePromise.resolve(r)) : n.A_.allocateTargetId(e).next((i => (r = new TargetData(t, i, "TargetPurposeListen" /* TargetPurpose.Listen */ , e.currentSequenceNumber), 
        n.A_.addTargetData(e, r).next((() => r)))))));
    })).then((e => {
        // If Multi-Tab is enabled, the existing target data may be newer than
        // the in-memory data
        const r = n.No.get(e.targetId);
        return (null === r || e.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.No = n.No.insert(e.targetId, e), 
        n.Lo.set(t, e.targetId)), e;
    }));
}

/**
 * Returns the TargetData as seen by the LocalStore, including updates that may
 * have not yet been persisted to the TargetCache.
 */
// Visible for testing.
/**
 * Unpins all the documents associated with the given target. If
 * `keepPersistedTargetData` is set to false and Eager GC enabled, the method
 * directly removes the associated target data from the target cache.
 *
 * Releasing a non-existing `Target` is a no-op.
 */
// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.
async function __PRIVATE_localStoreReleaseTarget(e, t, n) {
    const r = __PRIVATE_debugCast(e), i = r.No.get(t), s = n ? "readwrite" : "readwrite-primary";
    try {
        n || await r.persistence.runTransaction("Release target", s, (e => r.persistence.referenceDelegate.removeTarget(e, i)));
    } catch (e) {
        if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;
        // All `releaseTarget` does is record the final metadata state for the
        // target, but we've been recording this periodically during target
        // activity. If we lose this write this could cause a very slight
        // difference in the order of target deletion during GC, but we
        // don't define exact LRU semantics so this is acceptable.
        __PRIVATE_logDebug(lr, `Failed to update sequence numbers for target ${t}: ${e}`);
    }
    r.No = r.No.remove(t), 
    // TODO(pipeline): This needs to handle pipeline properly.
    r.Lo.delete(i.target);
}

/**
 * Runs the specified query against the local store and returns the results,
 * potentially taking advantage of query data from previous executions (such
 * as the set of remote keys).
 *
 * @param usePreviousResults - Whether results from previous executions can
 * be used to optimize this query execution.
 */ function __PRIVATE_localStoreExecuteQuery(e, t, n) {
    const r = __PRIVATE_debugCast(e);
    let i = SnapshotVersion.min(), s = __PRIVATE_documentKeySet();
    return r.persistence.runTransaction("Execute query", "readwrite", (// Use readwrite instead of readonly so indexes can be created
    // Use readwrite instead of readonly so indexes can be created
    e => function __PRIVATE_localStoreGetTargetData(e, t, n) {
        const r = __PRIVATE_debugCast(e), i = r.Lo.get(n);
        return void 0 !== i ? PersistencePromise.resolve(r.No.get(i)) : r.A_.getTargetData(t, n);
    }(r, e, __PRIVATE_isPipeline(t) ? t : __PRIVATE_queryToTarget(t)).next((t => {
        if (t) return i = t.lastLimboFreeSnapshotVersion, r.A_.getMatchingKeysForTargetId(e, t.targetId).next((e => {
            s = e;
        }));
    })).next((() => r.Mo.getDocumentsMatchingQuery(e, t, n ? i : SnapshotVersion.min(), n ? s : __PRIVATE_documentKeySet()))).next((e => (
    // TODO(pipeline): this needs to be adapted to support other pipeline flavors.
    // For now, only 'exact' flavor is supported and it is enough.
    __PRIVATE_setMaxReadTime(r, e), {
        documents: e,
        Wo: s
    })))));
}

// PORTING NOTE: Multi-Tab only.
function __PRIVATE_localStoreGetCachedTarget(e, t) {
    const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.A_), i = n.No.get(t);
    return i ? Promise.resolve(i.target ?? null) : n.persistence.runTransaction("Get target data", "readonly", (e => r.ge(e, t).next((e => e?.target ?? null))));
}

// PORTING NOTE: Multi-Tab only.
/**
 * Returns the set of documents that have been updated since the last call.
 * If this is the first call, returns the set of changes since client
 * initialization. Further invocations will return document that have changed
 * since the prior call.
 */
// PORTING NOTE: Multi-Tab only.
function __PRIVATE_localStoreGetNewDocumentChanges(e, t) {
    const n = __PRIVATE_debugCast(e), r = n.Bo.get(t) || SnapshotVersion.min();
    // Get the current maximum read time for the collection. This should always
    // exist, but to reduce the chance for regressions we default to
    // SnapshotVersion.Min()
    // TODO(indexing): Consider removing the default value.
        return n.persistence.runTransaction("Get new document changes", "readonly", (e => n.Uo.getAllFromCollectionGroup(e, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, Xe), 
    /* limit= */ Number.MAX_SAFE_INTEGER))).then((e => (__PRIVATE_setMaxReadTime(n, e), 
    e)));
}

/** Sets the collection group's maximum read time from the given documents. */
// PORTING NOTE: Multi-Tab only.
function __PRIVATE_setMaxReadTime(e, t) {
    t.forEach(((t, n) => {
        const r = n.key.getCollectionGroup(), i = e.Bo.get(r) || SnapshotVersion.min();
        n.readTime.compareTo(i) > 0 && e.Bo.set(r, n.readTime);
    }));
}

/**
 * Creates a new target using the given bundle name, which will be used to
 * hold the keys of all documents from the bundle in query-document mappings.
 * This ensures that the loaded documents do not get garbage collected
 * right away.
 */
/**
 * Applies the documents from a bundle to the "ground-state" (remote)
 * documents.
 *
 * LocalDocuments are re-calculated if there are remaining mutations in the
 * queue.
 */
async function __PRIVATE_localStoreApplyBundledDocuments(e, t, n, r) {
    const i = __PRIVATE_debugCast(e);
    let s = __PRIVATE_documentKeySet(), _ = __PRIVATE_mutableDocumentMap();
    for (const e of n) {
        const n = t.Qo(e.metadata.name);
        e.document && (s = s.add(n));
        const r = t.Go(e);
        r.setReadTime(t.zo(e.metadata.readTime)), _ = _.insert(n, r);
    }
    const o = i.Uo.newChangeBuffer({
        trackRemovals: true
    }), a = await __PRIVATE_localStoreAllocateTarget(i, function __PRIVATE_umbrellaTarget(e) {
        // It is OK that the path used for the query is not valid, because this will
        // not be read and queried.
        return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`)));
    }(r));
    // Allocates a target to hold all document keys from the bundle, such that
    // they will not get garbage collected right away.
        return i.persistence.runTransaction("Apply bundle documents", "readwrite", (e => __PRIVATE_populateDocumentChangeBuffer(e, o, _).next((t => (o.apply(e), 
    t))).next((t => i.A_.removeMatchingKeysForTargetId(e, a.targetId).next((() => i.A_.addMatchingKeys(e, s, a.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(e, t.$o, t.Ko))).next((() => t.$o))))));
}

/**
 * Returns a promise of a boolean to indicate if the given bundle has already
 * been loaded and the create time is newer than the current loading bundle.
 */
/**
 * Saves the given `NamedQuery` to local persistence.
 */
async function __PRIVATE_localStoreSaveNamedQuery(e, t, n = __PRIVATE_documentKeySet()) {
    // Allocate a target for the named query such that it can be resumed
    // from associated read time if users use it to listen.
    // NOTE: this also means if no corresponding target exists, the new target
    // will remain active and will not get collected, unless users happen to
    // unlisten the query somehow.
    const r = await __PRIVATE_localStoreAllocateTarget(e, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t.bundledQuery))), i = __PRIVATE_debugCast(e);
    return i.persistence.runTransaction("Save named query", "readwrite", (e => {
        const s = __PRIVATE_fromVersion(t.readTime);
        // Simply save the query itself if it is older than what the SDK already
        // has.
                if (r.snapshotVersion.compareTo(s) >= 0) return i.d_.saveNamedQuery(e, t);
        // Update existing target data because the query from the bundle is newer.
                const _ = r.withResumeToken(ByteString.EMPTY_BYTE_STRING, s);
        return i.No = i.No.insert(_.targetId, _), i.A_.updateTargetData(e, _).next((() => i.A_.removeMatchingKeysForTargetId(e, r.targetId))).next((() => i.A_.addMatchingKeys(e, n, r.targetId))).next((() => i.d_.saveNamedQuery(e, t)));
    }));
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A complete element in the bundle stream, together with the byte length it
 * occupies in the stream.
 */
class __PRIVATE_SizedBundleElement {
    constructor(e, 
    // How many bytes this element takes to store in the bundle.
    t) {
        this.jo = e, this.byteLength = t;
    }
    Ho() {
        return "metadata" in this.jo;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * How many bytes to read each time when `ReadableStreamReader.read()` is
 * called. Only applicable for byte streams that we control (e.g. those backed
 * by an UInt8Array).
 */
/**
 * Builds a `ByteStreamReader` from a UInt8Array.
 * @param source - The data source to use.
 * @param bytesPerRead - How many bytes each `read()` from the returned reader
 *        will read.
 */
function __PRIVATE_toByteStreamReaderHelper(e, t = 10240) {
    let n = 0;
    // The TypeScript definition for ReadableStreamReader changed. We use
    // `any` here to allow this code to compile with different versions.
    // See https://github.com/microsoft/TypeScript/issues/42970
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        async read() {
            if (n < e.byteLength) {
                const r = {
                    value: e.slice(n, n + t),
                    done: false
                };
                return n += t, r;
            }
            return {
                done: true
            };
        },
        async cancel() {},
        releaseLock() {},
        closed: Promise.resolve()
    };
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.
 */
/**
 * A component used by the RemoteStore to track the OnlineState (that is,
 * whether or not the client as a whole should be considered to be online or
 * offline), implementing the appropriate heuristics.
 *
 * In particular, when the client is trying to connect to the backend, we
 * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for
 * a connection to succeed. If we have too many failures or the timeout elapses,
 * then we set the OnlineState to Offline, and the client will behave as if
 * it is offline (get()s will return cached data, etc.).
 */
class __PRIVATE_OnlineStateTracker {
    constructor(e, t) {
        this.asyncQueue = e, this.onlineStateHandler = t, 
        /** The current OnlineState. */
        this.state = "Unknown" /* OnlineState.Unknown */ , 
        /**
         * A count of consecutive failures to open the stream. If it reaches the
         * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to
         * Offline.
         */
        this.Jo = 0, 
        /**
         * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we
         * transition from OnlineState.Unknown to OnlineState.Offline without waiting
         * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).
         */
        this.Yo = null, 
        /**
         * Whether the client should log a warning message if it fails to connect to
         * the backend (initially true, cleared after a successful stream, or if we've
         * logged the message already).
         */
        this.Zo = true;
    }
    /**
     * Called by RemoteStore when a watch stream is started (including on each
     * backoff attempt).
     *
     * If this is the first attempt, it sets the OnlineState to Unknown and starts
     * the onlineStateTimer.
     */    Xo() {
        0 === this.Jo && (this.ea("Unknown" /* OnlineState.Unknown */), this.Yo = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this.Yo = null, 
        this.ta("Backend didn't respond within 10 seconds."), this.ea("Offline" /* OnlineState.Offline */), 
        Promise.resolve()))));
    }
    /**
     * Updates our OnlineState as appropriate after the watch stream reports a
     * failure. The first failure moves us to the 'Unknown' state. We then may
     * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we
     * actually transition to the 'Offline' state.
     */    na(e) {
        "Online" /* OnlineState.Online */ === this.state ? this.ea("Unknown" /* OnlineState.Unknown */) : (this.Jo++, 
        this.Jo >= 1 && (this.ra(), this.ta(`Connection failed 1 times. Most recent error: ${e.toString()}`), 
        this.ea("Offline" /* OnlineState.Offline */)));
    }
    /**
     * Explicitly sets the OnlineState to the specified state.
     *
     * Note that this resets our timers / failure counters, etc. used by our
     * Offline heuristics, so must not be used in place of
     * handleWatchStreamStart() and handleWatchStreamFailure().
     */    set(e) {
        this.ra(), this.Jo = 0, "Online" /* OnlineState.Online */ === e && (
        // We've connected to watch at least once. Don't warn the developer
        // about being offline going forward.
        this.Zo = false), this.ea(e);
    }
    ea(e) {
        e !== this.state && (this.state = e, this.onlineStateHandler(e));
    }
    ta(e) {
        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.`;
        this.Zo ? (__PRIVATE_logError(t), this.Zo = false) : __PRIVATE_logDebug("OnlineStateTracker", t);
    }
    ra() {
        null !== this.Yo && (this.Yo.cancel(), this.Yo = null);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const hr = "RemoteStore";

// TODO(b/35853402): Negotiate this with the stream.
class __PRIVATE_RemoteStoreImpl {
    constructor(
    /**
     * The local store, used to fill the write pipeline with outbound mutations.
     */
    e, 
    /** The client-side proxy for interacting with the backend. */
    t, n, r, i) {
        this.localStore = e, this.datastore = t, this.asyncQueue = n, this.remoteSyncer = {}, 
        /**
         * A list of up to MAX_PENDING_WRITES writes that we have fetched from the
         * LocalStore via fillWritePipeline() and have or will send to the write
         * stream.
         *
         * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or
         * restart the write stream. When the stream is established the writes in the
         * pipeline will be sent in order.
         *
         * Writes remain in writePipeline until they are acknowledged by the backend
         * and thus will automatically be re-sent if the stream is interrupted /
         * restarted before they're acknowledged.
         *
         * Write responses from the backend are linked to their originating request
         * purely based on order, and so we can just shift() writes from the front of
         * the writePipeline as we receive responses.
         */
        this.ia = [], 
        /**
         * A mapping of watched targets that the client cares about tracking and the
         * user has explicitly called a 'listen' for this target.
         *
         * These targets may or may not have been sent to or acknowledged by the
         * server. On re-establishing the listen stream, these targets should be sent
         * to the server. The targets removed with unlistens are removed eagerly
         * without waiting for confirmation from the listen stream.
         */
        this.sa = new Map, this._a = new Map, this.oa = new Map, this.aa = new __PRIVATE_TargetIdGenerator(1e3), 
        this.ua = new __PRIVATE_TargetIdGenerator(1001), 
        /**
         * A set of reasons for why the RemoteStore may be offline. If empty, the
         * RemoteStore may start its network connections.
         */
        this.ca = new Set, 
        /**
         * Event handlers that get called when the network is disabled or enabled.
         *
         * PORTING NOTE: These functions are used on the Web client to create the
         * underlying streams (to support tree-shakeable streams). On Android and iOS,
         * the streams are created during construction of RemoteStore.
         */
        this.la = [], this.Ea = i, this.Ea.Ke((e => {
            n.enqueueAndForget((async () => {
                // Porting Note: Unlike iOS, `restartNetwork()` is called even when the
                // network becomes unreachable as we don't have any other way to tear
                // down our streams.
                __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(hr, "Restarting streams for network reachability change."), 
                await async function __PRIVATE_restartNetwork(e) {
                    const t = __PRIVATE_debugCast(e);
                    t.ca.add(4 /* OfflineCause.ConnectivityChange */), await __PRIVATE_disableNetworkInternal(t), 
                    t.ha.set("Unknown" /* OnlineState.Unknown */), t.ca.delete(4 /* OfflineCause.ConnectivityChange */), 
                    await __PRIVATE_enableNetworkInternal(t);
                }(this));
            }));
        })), this.ha = new __PRIVATE_OnlineStateTracker(n, r);
    }
}

async function __PRIVATE_enableNetworkInternal(e) {
    if (__PRIVATE_canUseNetwork(e)) for (const t of e.la) await t(/* enabled= */ true);
}

/**
 * Temporarily disables the network. The network can be re-enabled using
 * enableNetwork().
 */ async function __PRIVATE_disableNetworkInternal(e) {
    for (const t of e.la) await t(/* enabled= */ false);
}

/**
 * Returns the remote target ID currently mapped to this
 * sdkTargetId. Or returns `0` if the SDK target ID
 * is not currently mapped.
 * @param remoteStoreImpl
 * @param sdkTargetId
 */
function __PRIVATE_getRemoteTargetId(e, t) {
    return e._a.get(t) || void 0;
}

/**
 * Generates a new remote target ID that is acceptable
 * to map to the given SDK target ID.
 * @param remoteStoreImpl
 * @param sdkTargetId
 */
/**
 * Starts new listen for the given target. Uses resume token if provided. It
 * is a no-op if the target of given `TargetData` is already being listened to.
 */
function __PRIVATE_remoteStoreListen(e, t) {
    const n = __PRIVATE_debugCast(e), r = __PRIVATE_getRemoteTargetId(n, t.targetId);
    // Get any remote target ID currently mapped to the targetData
        // If remote store is still listening for this remote target ID, this is a no-op.
    if (void 0 !== r && n.sa.has(r)) return;
    // Generate and map a new remote ID to the SDK target ID
        const i = 
    /**
 * Generate a new remote target ID for the given SDK target ID.
 * Re-map the given SDK to the new remote ID.
 * Delete any mapping of the old remote ID, if given.
 * @param remoteStoreImpl
 * @param sdkTargetId
 * @return The new remote ID.
 */
    function __PRIVATE_allocateRemoteTargetId(e, t) {
        const n = __PRIVATE_getRemoteTargetId(e, t);
        void 0 !== n && 
        // If there was an existing remote target ID mapped to that SDK target ID, forget about the old remote ID.
        e.oa.delete(n);
        // Generate a new unique remote target ID
                const r = function __PRIVATE_generateRemoteTargetId(e, t) {
            // If the given sdkTargetId is odd, map it to an odd (sync engine) target ID
            return t % 2 != 0 ? e.ua.next() : e.aa.next();
        }(e, t);
        return e._a.set(t, r), e.oa.set(r, t), r;
    }(n, t.targetId);
    __PRIVATE_logDebug(hr, "remoteStoreListen mapping SDK target ID to remote", t.targetId, i);
    // Create a new TargetData for remote use, which uses
    // the remote TargetID.
    const s = new TargetData(t.target, i, t.purpose, t.sequenceNumber, t.snapshotVersion, t.lastLimboFreeSnapshotVersion, t.resumeToken);
    // Mark this as something the client is currently listening for.
        n.sa.set(i, s), __PRIVATE_shouldStartWatchStream(n) ? 
    // The listen will be sent in onWatchStreamOpen
    __PRIVATE_startWatchStream(n) : __PRIVATE_ensureWatchStream(n).Jt() && __PRIVATE_sendWatchRequest(n, s);
}

/**
 * Removes the listen from server. It is a no-op if the given target id is
 * not being listened to.
 */ function __PRIVATE_remoteStoreUnlisten(e, t) {
    const n = __PRIVATE_debugCast(e), r = __PRIVATE_ensureWatchStream(n), i = __PRIVATE_getRemoteTargetId(n, t);
    __PRIVATE_logDebug(hr, "remoteStoreUnlisten removing mapping of SDK target ID to remote", t, i), 
    n.sa.delete(i), n._a.delete(t), n.oa.delete(i), r.Jt() && __PRIVATE_sendUnwatchRequest(n, i), 
    0 === n.sa.size && (r.Jt() ? r.Xt() : __PRIVATE_canUseNetwork(n) && 
    // Revert to OnlineState.Unknown if the watch stream is not open and we
    // have no listeners, since without any listens to send we cannot
    // confirm if the stream is healthy and upgrade to OnlineState.Online.
    n.ha.set("Unknown" /* OnlineState.Unknown */));
}

/**
 * We need to increment the expected number of pending responses we're due
 * from watch so we wait for the ack to process any messages from this target.
 */ function __PRIVATE_sendWatchRequest(e, t) {
    if (e.Ta.H(t.targetId), t.resumeToken.approximateByteSize() > 0 || t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) {
        const n = e.oa.get(t.targetId);
        if (void 0 === n) 
        // There's already a new remoteStoreListen request for the original
        // target, so ignore this.
        return void __PRIVATE_logDebug(hr, "SDK target ID not found for remote ID: " + t.targetId);
        const r = e.remoteSyncer.getRemoteKeysForTarget(n).size;
        t = t.withExpectedCount(r);
    }
    __PRIVATE_ensureWatchStream(e).Tn(t);
}

/**
 * We need to increment the expected number of pending responses we're due
 * from watch so we wait for the removal on the server before we process any
 * messages from this target.
 */ function __PRIVATE_sendUnwatchRequest(e, t) {
    e.Ta.H(t), __PRIVATE_ensureWatchStream(e).Pn(t);
}

function __PRIVATE_startWatchStream(e) {
    e.Ta = new __PRIVATE_WatchChangeAggregator({
        getRemoteKeysForTarget: t => {
            // Remote syncer uses SDK target IDs, so we need to map the remote
            // id to external id
            const n = e.oa.get(t);
            // If no sdkTargetId is mapped, return an empty key set
                        return void 0 !== n ? e.remoteSyncer.getRemoteKeysForTarget(n) : __PRIVATE_documentKeySet();
        },
        ge: t => e.sa.get(t) || null,
        Ae: () => e.datastore.serializer.databaseId
    }), __PRIVATE_ensureWatchStream(e).start(), e.ha.Xo();
}

/**
 * Returns whether the watch stream should be started because it's necessary
 * and has not yet been started.
 */ function __PRIVATE_shouldStartWatchStream(e) {
    return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWatchStream(e).Ht() && e.sa.size > 0;
}

function __PRIVATE_canUseNetwork(e) {
    return 0 === __PRIVATE_debugCast(e).ca.size;
}

function __PRIVATE_cleanUpWatchStreamState(e) {
    e.Ta = void 0;
}

async function __PRIVATE_onWatchStreamConnected(e) {
    // Mark the client as online since we got a "connected" notification.
    e.ha.set("Online" /* OnlineState.Online */);
}

async function __PRIVATE_onWatchStreamOpen(e) {
    e.sa.forEach(((t, n) => {
        __PRIVATE_sendWatchRequest(e, t);
    }));
}

async function __PRIVATE_onWatchStreamClose(e, t) {
    __PRIVATE_cleanUpWatchStreamState(e), 
    // If we still need the watch stream, retry the connection.
    __PRIVATE_shouldStartWatchStream(e) ? (e.ha.na(t), __PRIVATE_startWatchStream(e)) : 
    // No need to restart watch stream because there are no active targets.
    // The online state is set to unknown because there is no active attempt
    // at establishing a connection
    e.ha.set("Unknown" /* OnlineState.Unknown */);
}

async function __PRIVATE_onWatchStreamChange(e, t, n) {
    if (
    // Mark the client as online since we got a message from the server
    e.ha.set("Online" /* OnlineState.Online */), t instanceof __PRIVATE_WatchTargetChange && 2 /* WatchTargetChangeState.Removed */ === t.state && t.cause) 
    // There was an error on a target, don't wait for a consistent snapshot
    // to raise events
    try {
        /** Handles an error on a target */
        await async function __PRIVATE_handleTargetError(e, t) {
            const n = t.cause;
            for (const r of t.targetIds) {
                // A watched target might have been removed already.
                if (e.sa.has(r)) {
                    const t = e.oa.get(r);
                    // If we still track the remote target ID, then notify the remoteSyncer
                    // of the error and then free up the remote ID.
                                        void 0 !== t && (await e.remoteSyncer.rejectListen(t, n), e._a.delete(t), 
                    e.oa.delete(r)), e.sa.delete(r);
                }
                e.Ta.removeTarget(r);
            }
        }
        /**
 * Attempts to fill our write pipeline with writes from the LocalStore.
 *
 * Called internally to bootstrap or refill the write pipeline and by
 * SyncEngine whenever there are new mutations to process.
 *
 * Starts the write stream if necessary.
 */ (e, t);
    } catch (n) {
        __PRIVATE_logDebug(hr, "Failed to remove targets %s: %s ", t.targetIds.join(","), n), 
        await __PRIVATE_disableNetworkUntilRecovery(e, n);
    } else if (t instanceof __PRIVATE_DocumentWatchChange ? e.Ta.se(t) : t instanceof __PRIVATE_ExistenceFilterChange ? e.Ta.Ee(t) : e.Ta.ae(t), 
    !n.isEqual(SnapshotVersion.min())) try {
        const t = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore);
        n.compareTo(t) >= 0 && 
        // We have received a target change with a global snapshot if the snapshot
        // version is not equal to SnapshotVersion.min().
        /**
 * Takes a batch of changes from the Datastore, repackages them as a
 * RemoteEvent, and passes that on to the listener, which is typically the
 * SyncEngine.
 */
        await function __PRIVATE_raiseWatchSnapshot(e, t) {
            const n = e.Ta.de(t);
            // Update in-memory resume tokens. LocalStore will update the
            // persistent view of these when applying the completed RemoteEvent.
                        n.targetChanges.forEach(((n, r) => {
                if (n.resumeToken.approximateByteSize() > 0) {
                    const i = e.sa.get(r);
                    // A watched target might have been removed already.
                                        i && e.sa.set(r, i.withResumeToken(n.resumeToken, t));
                }
            })), 
            // Re-establish listens for the targets that have been invalidated by
            // existence filter mismatches.
            // TODO ideally this would use a new remote target ID
            n.targetMismatches.forEach(((t, n) => {
                const r = e.sa.get(t);
                if (!r) 
                // A watched target might have been removed already.
                return;
                // Clear the resume token for the target, since we're in a known mismatch
                // state.
                                e.sa.set(t, r.withResumeToken(ByteString.EMPTY_BYTE_STRING, r.snapshotVersion)), 
                // Cause a hard reset by unwatching and rewatching immediately, but
                // deliberately don't send a resume token so that we get a full update.
                __PRIVATE_sendUnwatchRequest(e, t);
                // Mark the target we send as being on behalf of an existence filter
                // mismatch, but don't actually retain that in listenTargets. This ensures
                // that we flag the first re-listen this way without impacting future
                // listens of this target (that might happen e.g. on reconnect).
                const i = new TargetData(r.target, t, n, r.sequenceNumber);
                __PRIVATE_sendWatchRequest(e, i);
            }));
            const r = 
            /**
 * Convert a RemoteEvent with remote IDs to a RemoteEvent with
 * SDK IDs and dropped updates
 * for any targets we no longer track.
 *
 * @param remoteStoreImpl
 * @param remoteEvent
 * @return a new RemoteEvent with SDK IDs and dropped updates
 * for any targets we no longer track.
 */
            function __PRIVATE_toSdkRemoteEvent(e, t) {
                // Map TargetChanges to TargetChanges with SDK ID
                const n = new Map;
                t.targetChanges.forEach(((t, r) => {
                    // If we no longer track the remote ID, then drop the TargetChange
                    // otherwise propagate the TargetChange
                    const i = e.oa.get(r);
                    void 0 !== i && n.set(i, t);
                }));
                // Map target mismatches to target mismatches with SDK ID
                let r = new SortedMap(__PRIVATE_primitiveComparator);
                return t.targetMismatches.forEach(((t, n) => {
                    // If we no longer track the remote ID, then drop the target mismatch
                    // otherwise propagate the target mismatch
                    const i = e.oa.get(t);
                    void 0 !== i && (r = r.insert(i, n));
                })), new RemoteEvent(t.snapshotVersion, n, r, t.documentUpdates, t.augmentedDocumentUpdates, t.resolvedLimboDocuments);
            }(e, n);
            return e.remoteSyncer.applyRemoteEvent(r);
        }(e, n);
    } catch (t) {
        __PRIVATE_logDebug(hr, "Failed to raise snapshot:", t), await __PRIVATE_disableNetworkUntilRecovery(e, t);
    }
}

/**
 * Recovery logic for IndexedDB errors that takes the network offline until
 * `op` succeeds. Retries are scheduled with backoff using
 * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is
 * validated via a generic operation.
 *
 * The returned Promise is resolved once the network is disabled and before
 * any retry attempt.
 */ async function __PRIVATE_disableNetworkUntilRecovery(e, t, n) {
    if (!__PRIVATE_isIndexedDbTransactionError(t)) throw t;
    e.ca.add(1 /* OfflineCause.IndexedDbFailed */), 
    // Disable network and raise offline snapshots
    await __PRIVATE_disableNetworkInternal(e), e.ha.set("Offline" /* OnlineState.Offline */), 
    n || (
    // Use a simple read operation to determine if IndexedDB recovered.
    // Ideally, we would expose a health check directly on SimpleDb, but
    // RemoteStore only has access to persistence through LocalStore.
    n = () => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)), 
    // Probe IndexedDB periodically and re-enable network
    e.asyncQueue.enqueueRetryable((async () => {
        __PRIVATE_logDebug(hr, "Retrying IndexedDB access"), await n(), e.ca.delete(1 /* OfflineCause.IndexedDbFailed */), 
        await __PRIVATE_enableNetworkInternal(e);
    }));
}

/**
 * Executes `op`. If `op` fails, takes the network offline until `op`
 * succeeds. Returns after the first attempt.
 */ function __PRIVATE_executeWithRecovery(e, t) {
    return t().catch((n => __PRIVATE_disableNetworkUntilRecovery(e, n, t)));
}

async function __PRIVATE_fillWritePipeline(e) {
    const t = __PRIVATE_debugCast(e), n = __PRIVATE_ensureWriteStream(t);
    let r = t.ia.length > 0 ? t.ia[t.ia.length - 1].batchId : Ke;
    for (;__PRIVATE_canAddToWritePipeline(t); ) try {
        const e = await __PRIVATE_localStoreGetNextMutationBatch(t.localStore, r);
        if (null === e) {
            0 === t.ia.length && n.Xt();
            break;
        }
        r = e.batchId, __PRIVATE_addToWritePipeline(t, e);
    } catch (e) {
        await __PRIVATE_disableNetworkUntilRecovery(t, e);
    }
    __PRIVATE_shouldStartWriteStream(t) && __PRIVATE_startWriteStream(t);
}

/**
 * Returns true if we can add to the write pipeline (i.e. the network is
 * enabled and the write pipeline is not full).
 */ function __PRIVATE_canAddToWritePipeline(e) {
    return __PRIVATE_canUseNetwork(e) && e.ia.length < 10;
}

/**
 * Queues additional writes to be sent to the write stream, sending them
 * immediately if the write stream is established.
 */ function __PRIVATE_addToWritePipeline(e, t) {
    e.ia.push(t);
    const n = __PRIVATE_ensureWriteStream(e);
    n.Jt() && n.Rn && n.In(t.mutations);
}

function __PRIVATE_shouldStartWriteStream(e) {
    return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWriteStream(e).Ht() && e.ia.length > 0;
}

function __PRIVATE_startWriteStream(e) {
    __PRIVATE_ensureWriteStream(e).start();
}

async function __PRIVATE_onWriteStreamOpen(e) {
    __PRIVATE_ensureWriteStream(e).dn();
}

async function __PRIVATE_onWriteHandshakeComplete(e) {
    const t = __PRIVATE_ensureWriteStream(e);
    // Send the write pipeline now that the stream is established.
        for (const n of e.ia) t.In(n.mutations);
}

async function __PRIVATE_onMutationResult(e, t, n) {
    const r = e.ia.shift(), i = MutationBatchResult.from(r, t, n);
    await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.applySuccessfulWrite(i))), 
    // It's possible that with the completion of this mutation another
    // slot has freed up.
    await __PRIVATE_fillWritePipeline(e);
}

async function __PRIVATE_onWriteStreamClose(e, t) {
    // If the write stream closed after the write handshake completes, a write
    // operation failed and we fail the pending operation.
    t && __PRIVATE_ensureWriteStream(e).Rn && 
    // This error affects the actual write.
    await async function __PRIVATE_handleWriteError(e, t) {
        // Only handle permanent errors here. If it's transient, just let the retry
        // logic kick in.
        if (function __PRIVATE_isPermanentWriteError(e) {
            return __PRIVATE_isPermanentError(e) && e !== aa.ABORTED;
        }(t.code)) {
            // This was a permanent error, the request itself was the problem
            // so it's not going to succeed if we resend it.
            const n = e.ia.shift();
            // In this case it's also unlikely that the server itself is melting
            // down -- this was just a bad request so inhibit backoff on the next
            // restart.
                        __PRIVATE_ensureWriteStream(e).Zt(), await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.rejectFailedWrite(n.batchId, t))), 
            // It's possible that with the completion of this mutation
            // another slot has freed up.
            await __PRIVATE_fillWritePipeline(e);
        }
    }(e, t), 
    // The write stream might have been started by refilling the write
    // pipeline for failed writes
    __PRIVATE_shouldStartWriteStream(e) && __PRIVATE_startWriteStream(e);
}

async function __PRIVATE_remoteStoreHandleCredentialChange(e, t) {
    const n = __PRIVATE_debugCast(e);
    n.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(hr, "RemoteStore received new credentials");
    const r = __PRIVATE_canUseNetwork(n);
    // Tear down and re-create our network streams. This will ensure we get a
    // fresh auth token for the new user and re-fill the write pipeline with
    // new mutations from the LocalStore (since mutations are per-user).
        n.ca.add(3 /* OfflineCause.CredentialChange */), await __PRIVATE_disableNetworkInternal(n), 
    r && 
    // Don't set the network status to Unknown if we are offline.
    n.ha.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(t), 
    n.ca.delete(3 /* OfflineCause.CredentialChange */), await __PRIVATE_enableNetworkInternal(n);
}

/**
 * Toggles the network state when the client gains or loses its primary lease.
 */ async function __PRIVATE_remoteStoreApplyPrimaryState(e, t) {
    const n = __PRIVATE_debugCast(e);
    t ? (n.ca.delete(2 /* OfflineCause.IsSecondary */), await __PRIVATE_enableNetworkInternal(n)) : t || (n.ca.add(2 /* OfflineCause.IsSecondary */), 
    await __PRIVATE_disableNetworkInternal(n), n.ha.set("Unknown" /* OnlineState.Unknown */));
}

/**
 * If not yet initialized, registers the WatchStream and its network state
 * callback with `remoteStoreImpl`. Returns the existing stream if one is
 * already available.
 *
 * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.
 * This is not done on Web to allow it to be tree-shaken.
 */ function __PRIVATE_ensureWatchStream(e) {
    return e.Pa || (
    // Create stream (but note that it is not started yet).
    e.Pa = function __PRIVATE_newPersistentWatchStream(e, t, n) {
        const r = __PRIVATE_debugCast(e);
        return r.mn(), new __PRIVATE_PersistentListenStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);
    }(e.datastore, e.asyncQueue, {
        ut: __PRIVATE_onWatchStreamConnected.bind(null, e),
        lt: __PRIVATE_onWatchStreamOpen.bind(null, e),
        ht: __PRIVATE_onWatchStreamClose.bind(null, e),
        hn: __PRIVATE_onWatchStreamChange.bind(null, e)
    }), e.la.push((async t => {
        t ? (e.Pa.Zt(), __PRIVATE_shouldStartWatchStream(e) ? __PRIVATE_startWatchStream(e) : e.ha.set("Unknown" /* OnlineState.Unknown */)) : (await e.Pa.stop(), 
        __PRIVATE_cleanUpWatchStreamState(e));
    }))), e.Pa;
}

/**
 * If not yet initialized, registers the WriteStream and its network state
 * callback with `remoteStoreImpl`. Returns the existing stream if one is
 * already available.
 *
 * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.
 * This is not done on Web to allow it to be tree-shaken.
 */ function __PRIVATE_ensureWriteStream(e) {
    return e.Ra || (
    // Create stream (but note that it is not started yet).
    e.Ra = function __PRIVATE_newPersistentWriteStream(e, t, n) {
        const r = __PRIVATE_debugCast(e);
        return r.mn(), new __PRIVATE_PersistentWriteStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n);
    }(e.datastore, e.asyncQueue, {
        ut: () => Promise.resolve(),
        lt: __PRIVATE_onWriteStreamOpen.bind(null, e),
        ht: __PRIVATE_onWriteStreamClose.bind(null, e),
        An: __PRIVATE_onWriteHandshakeComplete.bind(null, e),
        Vn: __PRIVATE_onMutationResult.bind(null, e)
    }), e.la.push((async t => {
        t ? (e.Ra.Zt(), 
        // This will start the write stream if necessary.
        await __PRIVATE_fillWritePipeline(e)) : (await e.Ra.stop(), e.ia.length > 0 && (__PRIVATE_logDebug(hr, `Stopping write stream with ${e.ia.length} pending writes`), 
        e.ia = []));
    }))), e.Ra;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 * A wrapper implementation of Observer<T> that will dispatch events
 * asynchronously. To allow immediate silencing, a mute call is added which
 * causes events scheduled to no longer be raised.
 */ class __PRIVATE_AsyncObserver {
    constructor(e) {
        this.observer = e, 
        /**
         * When set to true, will not raise future events. Necessary to deal with
         * async detachment of listener.
         */
        this.muted = false;
    }
    next(e) {
        this.muted || this.observer.next && this.Ia(this.observer.next, e);
    }
    error(e) {
        this.muted || (this.observer.error ? this.Ia(this.observer.error, e) : __PRIVATE_logError("Uncaught Error in snapshot listener:", e.toString()));
    }
    Aa() {
        this.muted = true;
    }
    Ia(e, t) {
        setTimeout((() => {
            this.muted || e(t);
        }), 0);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents an operation scheduled to be run in the future on an AsyncQueue.
 *
 * It is created via DelayedOperation.createAndSchedule().
 *
 * Supports cancellation (via cancel()) and early execution (via skipDelay()).
 *
 * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type
 * in newer versions of TypeScript defines `finally`, which is not available in
 * IE.
 */
class DelayedOperation {
    constructor(e, t, n, r, i) {
        this.asyncQueue = e, this.timerId = t, this.targetTimeMs = n, this.op = r, this.removalCallback = i, 
        this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), 
        // It's normal for the deferred promise to be canceled (due to cancellation)
        // and so we attach a dummy catch callback to avoid
        // 'UnhandledPromiseRejectionWarning' log spam.
        this.deferred.promise.catch((e => {}));
    }
    get promise() {
        return this.deferred.promise;
    }
    /**
     * Creates and returns a DelayedOperation that has been scheduled to be
     * executed on the provided asyncQueue after the provided delayMs.
     *
     * @param asyncQueue - The queue to schedule the operation on.
     * @param id - A Timer ID identifying the type of operation this is.
     * @param delayMs - The delay (ms) before the operation should be scheduled.
     * @param op - The operation to run.
     * @param removalCallback - A callback to be called synchronously once the
     *   operation is executed or canceled, notifying the AsyncQueue to remove it
     *   from its delayedOperations list.
     *   PORTING NOTE: This exists to prevent making removeDelayedOperation() and
     *   the DelayedOperation class public.
     */    static createAndSchedule(e, t, n, r, i) {
        const s = Date.now() + n, _ = new DelayedOperation(e, t, s, r, i);
        return _.start(n), _;
    }
    /**
     * Starts the timer. This is called immediately after construction by
     * createAndSchedule().
     */    start(e) {
        this.timerHandle = setTimeout((() => this.handleDelayElapsed()), e);
    }
    /**
     * Queues the operation to run immediately (if it hasn't already been run or
     * canceled).
     */    skipDelay() {
        return this.handleDelayElapsed();
    }
    /**
     * Cancels the operation if it hasn't already been executed or canceled. The
     * promise will be rejected.
     *
     * As long as the operation has not yet been run, calling cancel() provides a
     * guarantee that the operation will not be run.
     */    cancel(e) {
        null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new s(aa.CANCELLED, "Operation cancelled" + (e ? ": " + e : ""))));
    }
    handleDelayElapsed() {
        this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), 
        this.op().then((e => this.deferred.resolve(e)))) : Promise.resolve()));
    }
    clearTimeout() {
        null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), 
        this.timerHandle = null);
    }
}

/**
 * Returns a FirestoreError that can be surfaced to the user if the provided
 * error is an IndexedDbTransactionError. Re-throws the error otherwise.
 */ function __PRIVATE_wrapInUserErrorIfRecoverable(e, t) {
    if (__PRIVATE_logError("AsyncQueue", `${t}: ${e}`), __PRIVATE_isIndexedDbTransactionError(e)) return new s(aa.UNAVAILABLE, `${t}: ${e}`);
    throw e;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A class representing a bundle.
 *
 * Takes a bundle stream or buffer, and presents abstractions to read bundled
 * elements out of the underlying content.
 */ class __PRIVATE_BundleReaderImpl {
    constructor(
    /** The reader to read from underlying binary bundle data source. */
    e, t) {
        this.Va = e, this.serializer = t, 
        /** Cached bundle metadata. */
        this.metadata = new __PRIVATE_Deferred, 
        /**
         * Internal buffer to hold bundle content, accumulating incomplete element
         * content.
         */
        this.buffer = new Uint8Array, this.da = function __PRIVATE_newTextDecoder() {
            return new TextDecoder("utf-8");
        }(), 
        // Read the metadata (which is the first element).
        this.fa().then((e => {
            e && e.Ho() ? this.metadata.resolve(e.jo.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n             ${JSON.stringify(e?.jo)}`));
        }), (e => this.metadata.reject(e)));
    }
    close() {
        return this.Va.cancel();
    }
    async getMetadata() {
        return this.metadata.promise;
    }
    async ma() {
        // Makes sure metadata is read before proceeding.
        return await this.getMetadata(), this.fa();
    }
    /**
     * Reads from the head of internal buffer, and pulling more data from
     * underlying stream if a complete element cannot be found, until an
     * element(including the prefixed length and the JSON string) is found.
     *
     * Once a complete element is read, it is dropped from internal buffer.
     *
     * Returns either the bundled element, or null if we have reached the end of
     * the stream.
     */    async fa() {
        const e = await this.pa();
        if (null === e) return null;
        const t = this.da.decode(e), n = Number(t);
        isNaN(n) && this.ga(`length string (${t}) is not valid number`);
        const r = await this.ya(n);
        return new __PRIVATE_SizedBundleElement(JSON.parse(r), e.length + n);
    }
    /** First index of '{' from the underlying buffer. */    wa() {
        return this.buffer.findIndex((e => e === "{".charCodeAt(0)));
    }
    /**
     * Reads from the beginning of the internal buffer, until the first '{', and
     * return the content.
     *
     * If reached end of the stream, returns a null.
     */    async pa() {
        for (;this.wa() < 0; ) {
            if (await this.ba()) break;
        }
        // Broke out of the loop because underlying stream is closed, and there
        // happens to be no more data to process.
                if (0 === this.buffer.length) return null;
        const e = this.wa();
        // Broke out of the loop because underlying stream is closed, but still
        // cannot find an open bracket.
                e < 0 && this.ga("Reached the end of bundle when a length string is expected.");
        const t = this.buffer.slice(0, e);
        // Update the internal buffer to drop the read length.
                return this.buffer = this.buffer.slice(e), t;
    }
    /**
     * Reads from a specified position from the internal buffer, for a specified
     * number of bytes, pulling more data from the underlying stream if needed.
     *
     * Returns a string decoded from the read bytes.
     */    async ya(e) {
        for (;this.buffer.length < e; ) {
            await this.ba() && this.ga("Reached the end of bundle when more is expected.");
        }
        const t = this.da.decode(this.buffer.slice(0, e));
        // Update the internal buffer to drop the read json string.
                return this.buffer = this.buffer.slice(e), t;
    }
    ga(e) {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        throw this.Va.cancel(), new Error(`Invalid bundle format: ${e}`);
    }
    /**
     * Pulls more data from underlying stream to internal buffer.
     * Returns a boolean indicating whether the stream is finished.
     */    async ba() {
        const e = await this.Va.read();
        if (!e.done) {
            const t = new Uint8Array(this.buffer.length + e.value.length);
            t.set(this.buffer), t.set(e.value, this.buffer.length), this.buffer = t;
        }
        return e.done;
    }
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * A class that can parse a bundle form the string serialization of a bundle.
 */
class __PRIVATE_BundleReaderSyncImpl {
    constructor(e, t) {
        this.bundleData = e, this.serializer = t, this.cursor = 0, this.elements = [];
        let n = this.ma();
        if (!n || !n.Ho()) throw new Error(`The first element of the bundle is not a metadata object, it is\n         ${JSON.stringify(n?.jo)}`);
        this.metadata = n;
        do {
            n = this.ma(), null !== n && this.elements.push(n);
        } while (null !== n);
    }
    /* Returns the parsed metadata of the bundle. */    getMetadata() {
        return this.metadata;
    }
    /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */    va() {
        return this.elements;
    }
    /**
     * Parses the next element of the bundle.
     *
     * @returns a SizedBundleElement representation of the next element in the bundle, or null if
     * no more elements exist.
     */    ma() {
        if (this.cursor === this.bundleData.length) return null;
        const e = this.pa(), t = this.ya(e);
        return new __PRIVATE_SizedBundleElement(JSON.parse(t), e);
    }
    /**
     * Reads from a specified position from the bundleData string, for a specified
     * number of bytes.
     *
     * @param length - how many characters to read.
     * @returns a string parsed from the bundle.
     */    ya(e) {
        if (this.cursor + e > this.bundleData.length) throw new s(aa.INTERNAL, "Reached the end of bundle when more is expected.");
        return this.bundleData.slice(this.cursor, this.cursor += e);
    }
    /**
     * Reads from the current cursor until the first '{'.
     *
     * @returns  A string to integer represention of the parsed value.
     * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths
     * prefix bundle objects.
     */    pa() {
        const e = this.cursor;
        let t = this.cursor;
        for (;t < this.bundleData.length; ) {
            if ("{" === this.bundleData[t]) {
                if (t === e) throw new Error("First character is a bracket and not a number");
                return this.cursor = t, Number(this.bundleData.slice(e, t));
            }
            t++;
        }
        throw new Error("Reached the end of bundle when more is expected.");
    }
}

/**
 *  Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type.
 */ const Tr = "IndexBackfiller";

/** How long we wait to try running index backfill after SDK initialization. */
/** This class is responsible for the scheduling of Index Backfiller. */
class __PRIVATE_IndexBackfillerScheduler {
    constructor(e, t) {
        this.asyncQueue = e, this.Sa = t, this.task = null;
    }
    start() {
        this.Da(15e3);
    }
    stop() {
        this.task && (this.task.cancel(), this.task = null);
    }
    get started() {
        return null !== this.task;
    }
    Da(e) {
        __PRIVATE_logDebug(Tr, `Scheduled in ${e}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , e, (async () => {
            this.task = null;
            try {
                const e = await this.Sa.xa();
                __PRIVATE_logDebug(Tr, `Documents written: ${e}`);
            } catch (e) {
                __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(Tr, "Ignoring IndexedDB error during index backfill: ", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);
            }
            await this.Da(6e4);
        }));
    }
}

/** Implements the steps for backfilling indexes. */ class __PRIVATE_IndexBackfiller {
    constructor(
    /**
     * LocalStore provides access to IndexManager and LocalDocumentView.
     * These properties will update when the user changes. Consequently,
     * making a local copy of IndexManager and LocalDocumentView will require
     * updates over time. The simpler solution is to rely on LocalStore to have
     * an up-to-date references to IndexManager and LocalDocumentStore.
     */
    e, t) {
        this.localStore = e, this.persistence = t;
    }
    async xa(e = 50) {
        return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (t => this.Ca(t, e)));
    }
    /** Writes index entries until the cap is reached. Returns the number of documents processed. */    Ca(e, t) {
        const n = new Set;
        let r = t, i = true;
        return PersistencePromise.doWhile((() => true === i && r > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t => {
            if (null !== t && !n.has(t)) return __PRIVATE_logDebug(Tr, `Processing collection: ${t}`), 
            this.Fa(e, t, r).next((e => {
                r -= e, n.add(t);
            }));
            i = false;
        })))).next((() => t - r));
    }
    /**
     * Writes entries for the provided collection group. Returns the number of documents processed.
     */    Fa(e, t, n) {
        // Use the earliest offset of all field indexes to query the local cache.
        return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e, t).next((r => this.localStore.localDocuments.getNextDocuments(e, t, r, n).next((n => {
            const i = n.changes;
            return this.localStore.indexManager.updateIndexEntries(e, i).next((() => this.Oa(r, n))).next((n => (__PRIVATE_logDebug(Tr, `Updating offset: ${n}`), 
            this.localStore.indexManager.updateCollectionGroup(e, t, n)))).next((() => i.size));
        }))));
    }
    /** Returns the next offset based on the provided documents. */    Oa(e, t) {
        let n = e;
        return t.changes.forEach(((e, t) => {
            const r = __PRIVATE_newIndexOffsetFromDocument(t);
            __PRIVATE_indexOffsetComparator(r, n) > 0 && (n = r);
        })), new IndexOffset(n.readTime, n.documentKey, Math.max(t.batchId, e.largestBatchId));
    }
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
// The format of the LocalStorage key that stores the client state is:
//     firestore_clients_<persistence_prefix>_<instance_key>
const Pr = "firestore_clients";

/** Assembles the key for a client state in WebStorage */ function createWebStorageClientStateKey(e, t) {
    return `${Pr}_${e}_${t}`;
}

// The format of the WebStorage key that stores the mutation state is:
//     firestore_mutations_<persistence_prefix>_<batch_id>
//     (for unauthenticated users)
// or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>

// 'user_uid' is last to avoid needing to escape '_' characters that it might
// contain.
const Rr = "firestore_mutations";

/** Assembles the key for a mutation batch in WebStorage */ function createWebStorageMutationBatchKey(e, t, n) {
    let r = `${Rr}_${e}_${n}`;
    return t.isAuthenticated() && (r += `_${t.uid}`), r;
}

// The format of the WebStorage key that stores a query target's metadata is:
//     firestore_targets_<persistence_prefix>_<target_id>
const Ir = "firestore_targets";

/** Assembles the key for a query state in WebStorage */ function createWebStorageQueryTargetMetadataKey(e, t) {
    return `${Ir}_${e}_${t}`;
}

// The WebStorage prefix that stores the primary tab's online state. The
// format of the key is:
//     firestore_online_state_<persistence_prefix>
/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const Ar = "SharedClientState";

/**
 * Holds the state of a mutation batch, including its user ID, batch ID and
 * whether the batch is 'pending', 'acknowledged' or 'rejected'.
 */
// Visible for testing
class __PRIVATE_MutationMetadata {
    constructor(e, t, n, r) {
        this.user = e, this.batchId = t, this.state = n, this.error = r;
    }
    /**
     * Parses a MutationMetadata from its JSON representation in WebStorage.
     * Logs a warning and returns null if the format of the data is not valid.
     */    static Ma(e, t, n) {
        const r = JSON.parse(n);
        let i, _ = "object" == typeof r && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(r.state) && (void 0 === r.error || "object" == typeof r.error);
        return _ && r.error && (_ = "string" == typeof r.error.message && "string" == typeof r.error.code, 
        _ && (i = new s(r.error.code, r.error.message))), _ ? new __PRIVATE_MutationMetadata(e, t, r.state, i) : (__PRIVATE_logError(Ar, `Failed to parse mutation state for ID '${t}': ${n}`), 
        null);
    }
    Na() {
        const e = {
            state: this.state,
            updateTimeMs: Date.now()
        };
        return this.error && (e.error = {
            code: this.error.code,
            message: this.error.message
        }), JSON.stringify(e);
    }
}

/**
 * Holds the state of a query target, including its target ID and whether the
 * target is 'not-current', 'current' or 'rejected'.
 */
// Visible for testing
class __PRIVATE_QueryTargetMetadata {
    constructor(e, t, n) {
        this.targetId = e, this.state = t, this.error = n;
    }
    /**
     * Parses a QueryTargetMetadata from its JSON representation in WebStorage.
     * Logs a warning and returns null if the format of the data is not valid.
     */    static Ma(e, t) {
        const n = JSON.parse(t);
        let r, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error);
        return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code, 
        i && (r = new s(n.error.code, n.error.message))), i ? new __PRIVATE_QueryTargetMetadata(e, n.state, r) : (__PRIVATE_logError(Ar, `Failed to parse target state for ID '${e}': ${t}`), 
        null);
    }
    Na() {
        const e = {
            state: this.state,
            updateTimeMs: Date.now()
        };
        return this.error && (e.error = {
            code: this.error.code,
            message: this.error.message
        }), JSON.stringify(e);
    }
}

/**
 * This class represents the immutable ClientState for a client read from
 * WebStorage, containing the list of active query targets.
 */ class __PRIVATE_RemoteClientState {
    constructor(e, t) {
        this.clientId = e, this.activeTargetIds = t;
    }
    /**
     * Parses a RemoteClientState from the JSON representation in WebStorage.
     * Logs a warning and returns null if the format of the data is not valid.
     */    static Ma(e, t) {
        const n = JSON.parse(t);
        let r = "object" == typeof n && n.activeTargetIds instanceof Array, i = __PRIVATE_targetIdSet();
        for (let e = 0; r && e < n.activeTargetIds.length; ++e) r = isSafeInteger(n.activeTargetIds[e]), 
        i = i.add(n.activeTargetIds[e]);
        return r ? new __PRIVATE_RemoteClientState(e, i) : (__PRIVATE_logError(Ar, `Failed to parse client data for instance '${e}': ${t}`), 
        null);
    }
}

/**
 * This class represents the online state for all clients participating in
 * multi-tab. The online state is only written to by the primary client, and
 * used in secondary clients to update their query views.
 */ class __PRIVATE_SharedOnlineState {
    constructor(e, t) {
        this.clientId = e, this.onlineState = t;
    }
    /**
     * Parses a SharedOnlineState from its JSON representation in WebStorage.
     * Logs a warning and returns null if the format of the data is not valid.
     */    static Ma(e) {
        const t = JSON.parse(e);
        return "object" == typeof t && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(t.onlineState) && "string" == typeof t.clientId ? new __PRIVATE_SharedOnlineState(t.clientId, t.onlineState) : (__PRIVATE_logError(Ar, `Failed to parse online state: ${e}`), 
        null);
    }
}

/**
 * Metadata state of the local client. Unlike `RemoteClientState`, this class is
 * mutable and keeps track of all pending mutations, which allows us to
 * update the range of pending mutation batch IDs as new mutations are added or
 * removed.
 *
 * The data in `LocalClientState` is not read from WebStorage and instead
 * updated via its instance methods. The updated state can be serialized via
 * `toWebStorageJSON()`.
 */
// Visible for testing.
class __PRIVATE_LocalClientState {
    constructor() {
        this.activeTargetIds = __PRIVATE_targetIdSet();
    }
    La(e) {
        this.activeTargetIds = this.activeTargetIds.add(e);
    }
    Ba(e) {
        this.activeTargetIds = this.activeTargetIds.delete(e);
    }
    /**
     * Converts this entry into a JSON-encoded format we can use for WebStorage.
     * Does not encode `clientId` as it is part of the key in WebStorage.
     */    Na() {
        const e = {
            activeTargetIds: this.activeTargetIds.toArray(),
            updateTimeMs: Date.now()
        };
        return JSON.stringify(e);
    }
}

/**
 * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the
 * backing store for the SharedClientState. It keeps track of all active
 * clients and supports modifications of the local client's data.
 */ class __PRIVATE_WebStorageSharedClientState {
    constructor(e, t, n, r, i) {
        this.window = e, this.xt = t, this.persistenceKey = n, this.Ua = r, this.syncEngine = null, 
        this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.ka = this.qa.bind(this), 
        this.$a = new SortedMap(__PRIVATE_primitiveComparator), this.started = false, 
        /**
         * Captures WebStorage events that occur before `start()` is called. These
         * events are replayed once `WebStorageSharedClientState` is started.
         */
        this.Ka = [];
        // Escape the special characters mentioned here:
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
        const s = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        this.storage = this.window.localStorage, this.currentUser = i, this.Wa = createWebStorageClientStateKey(this.persistenceKey, this.Ua), 
        this.Qa = 
        /** Assembles the key for the current sequence number. */
        function createWebStorageSequenceNumberKey(e) {
            return `firestore_sequence_number_${e}`;
        }(this.persistenceKey), this.$a = this.$a.insert(this.Ua, new __PRIVATE_LocalClientState), 
        this.Ga = new RegExp(`^${Pr}_${s}_([^_]*)$`), this.za = new RegExp(`^${Rr}_${s}_(\\d+)(?:_(.*))?$`), 
        this.ja = new RegExp(`^${Ir}_${s}_(\\d+)$`), this.Ha = 
        /** Assembles the key for the online state of the primary tab. */
        function createWebStorageOnlineStateKey(e) {
            return `firestore_online_state_${e}`;
        }
        // The WebStorage prefix that plays as a event to indicate the remote documents
        // might have changed due to some secondary tabs loading a bundle.
        // format of the key is:
        //     firestore_bundle_loaded_v2_<persistenceKey>
        // The version ending with "v2" stores the list of modified collection groups.
        (this.persistenceKey), this.Ja = function createBundleLoadedKey(e) {
            return `firestore_bundle_loaded_v2_${e}`;
        }
        // The WebStorage key prefix for the key that stores the last sequence number allocated. The key
        // looks like 'firestore_sequence_number_<persistence_prefix>'.
        (this.persistenceKey), 
        // Rather than adding the storage observer during start(), we add the
        // storage observer during initialization. This ensures that we collect
        // events before other components populate their initial state (during their
        // respective start() calls). Otherwise, we might for example miss a
        // mutation that is added after LocalStore's start() processed the existing
        // mutations but before we observe WebStorage events.
        this.window.addEventListener("storage", this.ka);
    }
    /** Returns 'true' if WebStorage is available in the current environment. */    static Je(e) {
        return !(!e || !e.localStorage);
    }
    async start() {
        // Retrieve the list of existing clients to backfill the data in
        // SharedClientState.
        const e = await this.syncEngine.Ro();
        for (const t of e) {
            if (t === this.Ua) continue;
            const e = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t));
            if (e) {
                const n = __PRIVATE_RemoteClientState.Ma(t, e);
                n && (this.$a = this.$a.insert(n.clientId, n));
            }
        }
        this.Ya();
        // Check if there is an existing online state and call the callback handler
        // if applicable.
        const t = this.storage.getItem(this.Ha);
        if (t) {
            const e = this.Za(t);
            e && this.Xa(e);
        }
        for (const e of this.Ka) this.qa(e);
        this.Ka = [], 
        // Register a window unload hook to remove the client metadata entry from
        // WebStorage even if `shutdown()` was not called.
        this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = true;
    }
    writeSequenceNumber(e) {
        this.setItem(this.Qa, JSON.stringify(e));
    }
    getAllActiveQueryTargets() {
        return this.eu(this.$a);
    }
    isActiveQueryTarget(e) {
        let t = false;
        return this.$a.forEach(((n, r) => {
            r.activeTargetIds.has(e) && (t = true);
        })), t;
    }
    addPendingMutation(e) {
        this.tu(e, "pending");
    }
    updateMutationState(e, t, n) {
        this.tu(e, t, n), 
        // Once a final mutation result is observed by other clients, they no longer
        // access the mutation's metadata entry. Since WebStorage replays events
        // in order, it is safe to delete the entry right after updating it.
        this.nu(e);
    }
    addLocalQueryTarget(e, t = true) {
        let n = "not-current";
        // Lookup an existing query state if the target ID was already registered
        // by another tab
                if (this.isActiveQueryTarget(e)) {
            const t = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));
            if (t) {
                const r = __PRIVATE_QueryTargetMetadata.Ma(e, t);
                r && (n = r.state);
            }
        }
        // If the query is listening to cache only, the target ID should not be registered with the
        // local Firestore client as an active watch target.
                return t && this.ru.La(e), this.Ya(), n;
    }
    removeLocalQueryTarget(e) {
        this.ru.Ba(e), this.Ya();
    }
    isLocalQueryTarget(e) {
        return this.ru.activeTargetIds.has(e);
    }
    clearQueryState(e) {
        this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e));
    }
    updateQueryState(e, t, n) {
        this.iu(e, t, n);
    }
    handleUserChange(e, t, n) {
        t.forEach((e => {
            this.nu(e);
        })), this.currentUser = e, n.forEach((e => {
            this.addPendingMutation(e);
        }));
    }
    setOnlineState(e) {
        this.su(e);
    }
    notifyBundleLoaded(e) {
        this._u(e);
    }
    shutdown() {
        this.started && (this.window.removeEventListener("storage", this.ka), this.removeItem(this.Wa), 
        this.started = false);
    }
    getItem(e) {
        const t = this.storage.getItem(e);
        return __PRIVATE_logDebug(Ar, "READ", e, t), t;
    }
    setItem(e, t) {
        __PRIVATE_logDebug(Ar, "SET", e, t), this.storage.setItem(e, t);
    }
    removeItem(e) {
        __PRIVATE_logDebug(Ar, "REMOVE", e), this.storage.removeItem(e);
    }
    qa(e) {
        // Note: The function is typed to take Event to be interface-compatible with
        // `Window.addEventListener`.
        const t = e;
        if (t.storageArea === this.storage) {
            if (__PRIVATE_logDebug(Ar, "EVENT", t.key, t.newValue), t.key === this.Wa) return void __PRIVATE_logError("Received WebStorage notification for local change. Another client might have garbage-collected our state");
            this.xt.enqueueRetryable((async () => {
                if (this.started) {
                    if (null !== t.key) if (this.Ga.test(t.key)) {
                        if (null == t.newValue) {
                            const e = this.ou(t.key);
                            return this.au(e, null);
                        }
                        {
                            const e = this.uu(t.key, t.newValue);
                            if (e) return this.au(e.clientId, e);
                        }
                    } else if (this.za.test(t.key)) {
                        if (null !== t.newValue) {
                            const e = this.cu(t.key, t.newValue);
                            if (e) return this.lu(e);
                        }
                    } else if (this.ja.test(t.key)) {
                        if (null !== t.newValue) {
                            const e = this.Eu(t.key, t.newValue);
                            if (e) return this.hu(e);
                        }
                    } else if (t.key === this.Ha) {
                        if (null !== t.newValue) {
                            const e = this.Za(t.newValue);
                            if (e) return this.Xa(e);
                        }
                    } else if (t.key === this.Qa) {
                        const e = function __PRIVATE_fromWebStorageSequenceNumber(e) {
                            let t = __PRIVATE_ListenSequence.yn;
                            if (null != e) try {
                                const n = JSON.parse(e);
                                __PRIVATE_hardAssert("number" == typeof n, 30636, {
                                    Tu: e
                                }), t = n;
                            } catch (e) {
                                __PRIVATE_logError(Ar, "Failed to read sequence number from WebStorage", e);
                            }
                            return t;
                        }
                        /**
 * `MemorySharedClientState` is a simple implementation of SharedClientState for
 * clients using memory persistence. The state in this class remains fully
 * isolated and no synchronization is performed.
 */ (t.newValue);
                        e !== __PRIVATE_ListenSequence.yn && this.sequenceNumberHandler(e);
                    } else if (t.key === this.Ja) {
                        const e = this.Pu(t.newValue);
                        await Promise.all(e.map((e => this.syncEngine.Ru(e))));
                    }
                } else this.Ka.push(t);
            }));
        }
    }
    get ru() {
        return this.$a.get(this.Ua);
    }
    Ya() {
        this.setItem(this.Wa, this.ru.Na());
    }
    tu(e, t, n) {
        const r = new __PRIVATE_MutationMetadata(this.currentUser, e, t, n), i = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);
        this.setItem(i, r.Na());
    }
    nu(e) {
        const t = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e);
        this.removeItem(t);
    }
    su(e) {
        const t = {
            clientId: this.Ua,
            onlineState: e
        };
        this.storage.setItem(this.Ha, JSON.stringify(t));
    }
    iu(e, t, n) {
        const r = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e), i = new __PRIVATE_QueryTargetMetadata(e, t, n);
        this.setItem(r, i.Na());
    }
    _u(e) {
        const t = JSON.stringify(Array.from(e));
        this.setItem(this.Ja, t);
    }
    /**
     * Parses a client state key in WebStorage. Returns null if the key does not
     * match the expected key format.
     */    ou(e) {
        const t = this.Ga.exec(e);
        return t ? t[1] : null;
    }
    /**
     * Parses a client state in WebStorage. Returns 'null' if the value could not
     * be parsed.
     */    uu(e, t) {
        const n = this.ou(e);
        return __PRIVATE_RemoteClientState.Ma(n, t);
    }
    /**
     * Parses a mutation batch state in WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    cu(e, t) {
        const n = this.za.exec(e), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;
        return __PRIVATE_MutationMetadata.Ma(new User(i), r, t);
    }
    /**
     * Parses a query target state from WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    Eu(e, t) {
        const n = this.ja.exec(e), r = Number(n[1]);
        return __PRIVATE_QueryTargetMetadata.Ma(r, t);
    }
    /**
     * Parses an online state from WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    Za(e) {
        return __PRIVATE_SharedOnlineState.Ma(e);
    }
    Pu(e) {
        return JSON.parse(e);
    }
    async lu(e) {
        if (e.user.uid === this.currentUser.uid) return this.syncEngine.Iu(e.batchId, e.state, e.error);
        __PRIVATE_logDebug(Ar, `Ignoring mutation for non-active user ${e.user.uid}`);
    }
    hu(e) {
        return this.syncEngine.Au(e.targetId, e.state, e.error);
    }
    au(e, t) {
        const n = t ? this.$a.insert(e, t) : this.$a.remove(e), r = this.eu(this.$a), i = this.eu(n), s = [], _ = [];
        return i.forEach((e => {
            r.has(e) || s.push(e);
        })), r.forEach((e => {
            i.has(e) || _.push(e);
        })), this.syncEngine.Vu(s, _).then((() => {
            this.$a = n;
        }));
    }
    Xa(e) {
        // We check whether the client that wrote this online state is still active
        // by comparing its client ID to the list of clients kept active in
        // IndexedDb. If a client does not update their IndexedDb client state
        // within 5 seconds, it is considered inactive and we don't emit an online
        // state event.
        this.$a.get(e.clientId) && this.onlineStateHandler(e.onlineState);
    }
    eu(e) {
        let t = __PRIVATE_targetIdSet();
        return e.forEach(((e, n) => {
            t = t.unionWith(n.activeTargetIds);
        })), t;
    }
}

class __PRIVATE_MemorySharedClientState {
    constructor() {
        this.du = new __PRIVATE_LocalClientState, this.fu = {}, this.onlineStateHandler = null, 
        this.sequenceNumberHandler = null;
    }
    addPendingMutation(e) {
        // No op.
    }
    updateMutationState(e, t, n) {
        // No op.
    }
    addLocalQueryTarget(e, t = true) {
        return t && this.du.La(e), this.fu[e] || "not-current";
    }
    updateQueryState(e, t, n) {
        this.fu[e] = t;
    }
    removeLocalQueryTarget(e) {
        this.du.Ba(e);
    }
    isLocalQueryTarget(e) {
        return this.du.activeTargetIds.has(e);
    }
    clearQueryState(e) {
        delete this.fu[e];
    }
    getAllActiveQueryTargets() {
        return this.du.activeTargetIds;
    }
    isActiveQueryTarget(e) {
        return this.du.activeTargetIds.has(e);
    }
    start() {
        return this.du = new __PRIVATE_LocalClientState, Promise.resolve();
    }
    handleUserChange(e, t, n) {
        // No op.
    }
    setOnlineState(e) {
        // No op.
    }
    shutdown() {}
    writeSequenceNumber(e) {}
    notifyBundleLoaded(e) {
        // No op.
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/** The Platform's 'window' implementation or null if not available. */ function __PRIVATE_getWindow() {
    // `window` is not always available, e.g. in ReactNative and WebWorkers.
    // eslint-disable-next-line no-restricted-globals
    return "undefined" != typeof window ? window : null;
}

/** The Platform's 'document' implementation or null if not available. */ function getDocument() {
    // `document` is not always available, e.g. in ReactNative and WebWorkers.
    // eslint-disable-next-line no-restricted-globals
    return "undefined" != typeof document ? document : null;
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * DocumentSet is an immutable (copy-on-write) collection that holds documents
 * in order specified by the provided comparator. We always add a document key
 * comparator on top of what is provided to guarantee document equality based on
 * the key.
 */ class DocumentSet {
    /**
     * Returns an empty copy of the existing DocumentSet, using the same
     * comparator.
     */
    static emptySet(e) {
        return new DocumentSet(e.comparator);
    }
    /** The default ordering is by key if the comparator is omitted */    constructor(e) {
        // We are adding document key comparator to the end as it's the only
        // guaranteed unique property of a document.
        this.comparator = e ? (t, n) => e(t, n) || DocumentKey.comparator(t.key, n.key) : (e, t) => DocumentKey.comparator(e.key, t.key), 
        this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator);
    }
    has(e) {
        return null != this.keyedMap.get(e);
    }
    get(e) {
        return this.keyedMap.get(e);
    }
    first() {
        return this.sortedSet.minKey();
    }
    last() {
        return this.sortedSet.maxKey();
    }
    isEmpty() {
        return this.sortedSet.isEmpty();
    }
    /**
     * Returns the index of the provided key in the document set, or -1 if the
     * document key is not present in the set;
     */    indexOf(e) {
        const t = this.keyedMap.get(e);
        return t ? this.sortedSet.indexOf(t) : -1;
    }
    get size() {
        return this.sortedSet.size;
    }
    /** Iterates documents in order defined by "comparator" */    forEach(e) {
        this.sortedSet.inorderTraversal(((t, n) => (e(t), false)));
    }
    /** Inserts or updates a document with the same key */    add(e) {
        // First remove the element if we have it.
        const t = this.delete(e.key);
        return t.copy(t.keyedMap.insert(e.key, e), t.sortedSet.insert(e, null));
    }
    /** Deletes a document with a given key */    delete(e) {
        const t = this.get(e);
        return t ? this.copy(this.keyedMap.remove(e), this.sortedSet.remove(t)) : this;
    }
    isEqual(e) {
        if (!(e instanceof DocumentSet)) return false;
        if (this.size !== e.size) return false;
        const t = this.sortedSet.getIterator(), n = e.sortedSet.getIterator();
        for (;t.hasNext(); ) {
            const e = t.getNext().key, r = n.getNext().key;
            if (!e.isEqual(r)) return false;
        }
        return true;
    }
    toString() {
        const e = [];
        return this.forEach((t => {
            e.push(t.toString());
        })), 0 === e.length ? "DocumentSet ()" : "DocumentSet (\n  " + e.join("  \n") + "\n)";
    }
    copy(e, t) {
        const n = new DocumentSet;
        return n.comparator = this.comparator, n.keyedMap = e, n.sortedSet = t, n;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
 * duplicate events for the same doc.
 */ class __PRIVATE_DocumentChangeSet {
    constructor() {
        this.mu = new SortedMap(DocumentKey.comparator);
    }
    track(e) {
        const t = e.doc.key, n = this.mu.get(t);
        n ? 
        // Merge the new change with the existing change.
        0 /* ChangeType.Added */ !== e.type && 3 /* ChangeType.Metadata */ === n.type ? this.mu = this.mu.insert(t, e) : 3 /* ChangeType.Metadata */ === e.type && 1 /* ChangeType.Removed */ !== n.type ? this.mu = this.mu.insert(t, {
            type: n.type,
            doc: e.doc
        }) : 2 /* ChangeType.Modified */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.mu = this.mu.insert(t, {
            type: 2 /* ChangeType.Modified */ ,
            doc: e.doc
        }) : 2 /* ChangeType.Modified */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.mu = this.mu.insert(t, {
            type: 0 /* ChangeType.Added */ ,
            doc: e.doc
        }) : 1 /* ChangeType.Removed */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.mu = this.mu.remove(t) : 1 /* ChangeType.Removed */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.mu = this.mu.insert(t, {
            type: 1 /* ChangeType.Removed */ ,
            doc: n.doc
        }) : 0 /* ChangeType.Added */ === e.type && 1 /* ChangeType.Removed */ === n.type ? this.mu = this.mu.insert(t, {
            type: 2 /* ChangeType.Modified */ ,
            doc: e.doc
        }) : 
        // This includes these cases, which don't make sense:
        // Added->Added
        // Removed->Removed
        // Modified->Added
        // Removed->Modified
        // Metadata->Added
        // Removed->Metadata
        l(63341, {
            ye: e,
            pu: n
        }) : this.mu = this.mu.insert(t, e);
    }
    gu() {
        const e = [];
        return this.mu.inorderTraversal(((t, n) => {
            e.push(n);
        })), e;
    }
}

class ViewSnapshot {
    constructor(e, t, n, r, i, s, _, o, a) {
        this.query = e, this.docs = t, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i, 
        this.fromCache = s, this.syncStateChanged = _, this.excludesMetadataChanges = o, 
        this.hasCachedResults = a;
    }
    /** Returns a view snapshot as if all documents in the snapshot were added. */    static fromInitialDocuments(e, t, n, r, i) {
        const s = [];
        return t.forEach((e => {
            s.push({
                type: 0 /* ChangeType.Added */ ,
                doc: e
            });
        })), new ViewSnapshot(e, t, DocumentSet.emptySet(t), s, n, r, 
        /* syncStateChanged= */ true, 
        /* excludesMetadataChanges= */ false, i);
    }
    get hasPendingWrites() {
        return !this.mutatedKeys.isEmpty();
    }
    isEqual(e) {
        if (!(this.fromCache === e.fromCache && this.hasCachedResults === e.hasCachedResults && this.syncStateChanged === e.syncStateChanged && this.mutatedKeys.isEqual(e.mutatedKeys) && __PRIVATE_queryOrPipelineEqual(this.query, e.query) && this.docs.isEqual(e.docs) && this.oldDocs.isEqual(e.oldDocs))) return false;
        const t = this.docChanges, n = e.docChanges;
        if (t.length !== n.length) return false;
        for (let e = 0; e < t.length; e++) if (t[e].type !== n[e].type || !t[e].doc.isEqual(n[e].doc)) return false;
        return true;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Holds the listeners and the last received ViewSnapshot for a query being
 * tracked by EventManager.
 */ class __PRIVATE_QueryListenersInfo {
    constructor() {
        this.yu = void 0, this.wu = [];
    }
    // Helper methods that checks if the query has listeners that listening to remote store
    bu() {
        return this.wu.some((e => e.vu()));
    }
}

class __PRIVATE_EventManagerImpl {
    constructor() {
        this.queries = __PRIVATE_newQueriesObjectMap(), this.onlineState = "Unknown" /* OnlineState.Unknown */ , 
        this.Su = new Set;
    }
    terminate() {
        !function __PRIVATE_errorAllTargets(e, t) {
            const n = __PRIVATE_debugCast(e), r = n.queries;
            // Prevent further access by clearing ObjectMap.
            n.queries = __PRIVATE_newQueriesObjectMap(), r.forEach(((e, n) => {
                for (const e of n.wu) e.onError(t);
            }));
        }
        // Call all global snapshot listeners that have been set.
        (this, new s(aa.ABORTED, "Firestore shutting down"));
    }
}

function __PRIVATE_newQueriesObjectMap() {
    return new ObjectMap((e => __PRIVATE_canonifyQueryOrPipeline(e)), __PRIVATE_queryOrPipelineEqual);
}

async function __PRIVATE_eventManagerListen(e, t) {
    const n = __PRIVATE_debugCast(e);
    let r = 3 /* ListenerSetupAction.NoActionRequired */;
    const i = t.query;
    let s = n.queries.get(i);
    s ? !s.bu() && t.vu() && (
    // Query has been listening to local cache, and tries to add a new listener sourced from watch.
    r = 2 /* ListenerSetupAction.RequireWatchConnectionOnly */) : (s = new __PRIVATE_QueryListenersInfo, 
    r = t.vu() ? 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : 1 /* ListenerSetupAction.InitializeLocalListenOnly */);
    try {
        switch (r) {
          case 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ :
            s.yu = await n.onListen(i, 
            /** enableRemoteListen= */ !0);
            break;

          case 1 /* ListenerSetupAction.InitializeLocalListenOnly */ :
            s.yu = await n.onListen(i, 
            /** enableRemoteListen= */ !1);
            break;

          case 2 /* ListenerSetupAction.RequireWatchConnectionOnly */ :
            await n.onFirstRemoteStoreListen(i);
        }
    } catch (e) {
        const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Initialization of query '${__PRIVATE_isPipeline(t.query) ? __PRIVATE_canonifyPipeline(t.query) : __PRIVATE_stringifyQuery(t.query)}' failed`);
        return void t.onError(n);
    }
    if (n.queries.set(i, s), s.wu.push(t), 
    // Run global snapshot listeners if a consistent snapshot has been emitted.
    t.Du(n.onlineState), s.yu) {
        t.xu(s.yu) && __PRIVATE_raiseSnapshotsInSyncEvent(n);
    }
}

async function __PRIVATE_eventManagerUnlisten(e, t) {
    const n = __PRIVATE_debugCast(e), r = t.query;
    let i = 3 /* ListenerRemovalAction.NoActionRequired */;
    const s = n.queries.get(r);
    if (s) {
        const e = s.wu.indexOf(t);
        e >= 0 && (s.wu.splice(e, 1), 0 === s.wu.length ? i = t.vu() ? 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : !s.bu() && t.vu() && (
        // The removed listener is the last one that sourced from watch.
        i = 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */));
    }
    switch (i) {
      case 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ :
        return n.queries.delete(r), n.onUnlisten(r, 
        /** disableRemoteListen= */ true);

      case 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ :
        return n.queries.delete(r), n.onUnlisten(r, 
        /** disableRemoteListen= */ false);

      case 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */ :
        return n.onLastRemoteStoreUnlisten(r);

      default:
        return;
    }
}

function __PRIVATE_eventManagerOnWatchChange(e, t) {
    const n = __PRIVATE_debugCast(e);
    let r = false;
    for (const e of t) {
        const t = e.query, i = n.queries.get(t);
        if (i) {
            for (const t of i.wu) t.xu(e) && (r = true);
            i.yu = e;
        }
    }
    r && __PRIVATE_raiseSnapshotsInSyncEvent(n);
}

function __PRIVATE_eventManagerOnWatchError(e, t, n) {
    const r = __PRIVATE_debugCast(e), i = r.queries.get(t);
    if (i) for (const e of i.wu) e.onError(n);
    // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
    // after an error.
        r.queries.delete(t);
}

function __PRIVATE_raiseSnapshotsInSyncEvent(e) {
    e.Su.forEach((e => {
        e.next();
    }));
}

var Vr;

!function(e) {
    /** Listen to both cache and server changes */
    e.Default = "default", 
    /** Listen to changes in cache only */
    e.Cache = "cache";
}(Vr || (Vr = {}));

/**
 * QueryListener takes a series of internal view snapshots and determines
 * when to raise the event.
 *
 * It uses an Observer to dispatch events.
 */
class __PRIVATE_QueryListener {
    constructor(e, t, n) {
        this.query = e, this.Cu = t, 
        /**
         * Initial snapshots (e.g. from cache) may not be propagated to the wrapped
         * observer. This flag is set to true once we've actually raised an event.
         */
        this.Fu = false, this.Ou = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ , 
        this.options = n || {};
    }
    /**
     * Applies the new ViewSnapshot to this listener, raising a user-facing event
     * if applicable (depending on what changed, whether the user has opted into
     * metadata-only changes, etc.). Returns true if a user-facing event was
     * indeed raised.
     */    xu(e) {
        if (!this.options.includeMetadataChanges) {
            // Remove the metadata only changes.
            const t = [];
            for (const n of e.docChanges) 3 /* ChangeType.Metadata */ !== n.type && t.push(n);
            e = new ViewSnapshot(e.query, e.docs, e.oldDocs, t, e.mutatedKeys, e.fromCache, e.syncStateChanged, 
            /* excludesMetadataChanges= */ true, e.hasCachedResults);
        }
        let t = false;
        return this.Fu ? this.Mu(e) && (this.Cu.next(e), t = true) : this.Nu(e, this.onlineState) && (this.Lu(e), 
        t = true), this.Ou = e, t;
    }
    onError(e) {
        this.Cu.error(e);
    }
    /** Returns whether a snapshot was raised. */    Du(e) {
        this.onlineState = e;
        let t = false;
        return this.Ou && !this.Fu && this.Nu(this.Ou, e) && (this.Lu(this.Ou), t = true), 
        t;
    }
    Nu(e, t) {
        // Always raise the first event when we're synced
        if (!e.fromCache) return true;
        // Always raise event if listening to cache
                if (!this.vu()) return true;
        // NOTE: We consider OnlineState.Unknown as online (it should become Offline
        // or Online if we wait long enough).
                const n = "Offline" /* OnlineState.Offline */ !== t;
        // Don't raise the event if we're online, aren't synced yet (checked
        // above) and are waiting for a sync.
                return (!this.options.waitForSyncWhenOnline || !n) && (!e.docs.isEmpty() || e.hasCachedResults || "Offline" /* OnlineState.Offline */ === t);
        // Raise data from cache if we have any documents, have cached results before,
        // or we are offline.
        }
    Mu(e) {
        // We don't need to handle includeDocumentMetadataChanges here because
        // the Metadata only changes have already been stripped out if needed.
        // At this point the only changes we will see are the ones we should
        // propagate.
        if (e.docChanges.length > 0) return true;
        const t = this.Ou && this.Ou.hasPendingWrites !== e.hasPendingWrites;
        return !(!e.syncStateChanged && !t) && true === this.options.includeMetadataChanges;
        // Generally we should have hit one of the cases above, but it's possible
        // to get here if there were only metadata docChanges and they got
        // stripped out.
        }
    Lu(e) {
        e = ViewSnapshot.fromInitialDocuments(e.query, e.docs, e.mutatedKeys, e.fromCache, e.hasCachedResults), 
        this.Fu = true, this.Cu.next(e);
    }
    vu() {
        return this.options.source !== Vr.Cache;
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Helper to convert objects from bundles to model objects in the SDK.
 */ class __PRIVATE_BundleConverterImpl {
    constructor(e) {
        this.serializer = e;
    }
    Qo(e) {
        return fromName(this.serializer, e);
    }
    /**
     * Converts a BundleDocument to a MutableDocument.
     */    Go(e) {
        return e.metadata.exists ? fromDocument(this.serializer, e.document, false) : MutableDocument.newNoDocument(this.Qo(e.metadata.name), this.zo(e.metadata.readTime));
    }
    zo(e) {
        return __PRIVATE_fromVersion(e);
    }
}

/**
 * A class to process the elements from a bundle, and optionally load them into local
 * storage and provide progress update while loading.
 */ class __PRIVATE_BundleLoader {
    constructor(e, t) {
        this.Bu = e, this.serializer = t, 
        /** Batched queries to be saved into storage */
        this.Uu = [], 
        /** Batched documents to be saved into storage */
        this.ku = [], 
        /** The collection groups affected by this bundle. */
        this.collectionGroups = new Set, this.progress = __PRIVATE_bundleInitialProgress(e);
    }
    /**
     * Returns the named queries that have been parsed from the SizeBundleElements added by
     * calling {@link adSizedElement}.
     */    get queries() {
        return this.Uu;
    }
    /**
     * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by
     * calling {@link addSizedElement}.
     */    get documents() {
        return this.ku;
    }
    /**
     * Adds an element from the bundle to the loader.
     *
     * Returns a new progress if adding the element leads to a new progress,
     * otherwise returns null.
     */    qu(e) {
        this.progress.bytesLoaded += e.byteLength;
        let t = this.progress.documentsLoaded;
        if (e.jo.namedQuery) this.Uu.push(e.jo.namedQuery); else if (e.jo.documentMetadata) {
            this.ku.push({
                metadata: e.jo.documentMetadata
            }), e.jo.documentMetadata.exists || ++t;
            const n = ResourcePath.fromString(e.jo.documentMetadata.name);
            this.collectionGroups.add(n.get(n.length - 2));
        } else e.jo.document && (this.ku[this.ku.length - 1].document = e.jo.document, ++t);
        return t !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t, 
        {
            ...this.progress
        }) : null;
    }
    $u(e) {
        const t = new Map, n = new __PRIVATE_BundleConverterImpl(this.serializer);
        for (const r of e) if (r.metadata.queries) {
            const e = n.Qo(r.metadata.name);
            for (const n of r.metadata.queries) {
                const r = (t.get(n) || __PRIVATE_documentKeySet()).add(e);
                t.set(n, r);
            }
        }
        return t;
    }
    /**
     * Update the progress to 'Success' and return the updated progress.
     */    async Ku(e) {
        const t = await __PRIVATE_localStoreApplyBundledDocuments(e, new __PRIVATE_BundleConverterImpl(this.serializer), this.ku, this.Bu.id), n = this.$u(this.documents);
        for (const t of this.Uu) await __PRIVATE_localStoreSaveNamedQuery(e, t, n.get(t.name));
        return this.progress.taskState = "Success", {
            progress: this.progress,
            Wu: this.collectionGroups,
            Qu: t
        };
    }
}

/**
 * Returns a `LoadBundleTaskProgress` representing the initial progress of
 * loading a bundle.
 */ function __PRIVATE_bundleInitialProgress(e) {
    return {
        taskState: "Running",
        documentsLoaded: 0,
        bytesLoaded: 0,
        totalDocuments: e.totalDocuments,
        totalBytes: e.totalBytes
    };
}

/**
 * Returns a `LoadBundleTaskProgress` representing the progress that the loading
 * has succeeded.
 */
/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
class __PRIVATE_AddedLimboDocument {
    constructor(e) {
        this.key = e;
    }
}

class __PRIVATE_RemovedLimboDocument {
    constructor(e) {
        this.key = e;
    }
}

/**
 * View is responsible for computing the final merged truth of what docs are in
 * a query. It gets notified of local and remote changes to docs, and applies
 * the query filters and limits to determine the most correct possible results.
 */ class __PRIVATE_View {
    constructor(e, 
    /** Documents included in the remote target */
    t) {
        this.query = e, this.Gu = t, this.zu = null, this.hasCachedResults = false, 
        /**
         * A flag whether the view is current with the backend. A view is considered
         * current after it has seen the current flag from the backend and did not
         * lose consistency within the watch stream (e.g. because of an existence
         * filter mismatch).
         */
        this.current = false, 
        /** Documents in the view but not in the remote target */
        this.ju = __PRIVATE_documentKeySet(), 
        /** Document Keys that have local changes */
        this.mutatedKeys = __PRIVATE_documentKeySet(), this.Hu = __PRIVATE_isPipeline(e) ? __PRIVATE_newPipelineComparator(e) : __PRIVATE_newQueryComparator(e), 
        this.Ju = new DocumentSet(this.Hu);
    }
    /**
     * The set of remote documents that the server has told us belongs to the target associated with
     * this view.
     */    get Yu() {
        return this.Gu;
    }
    /**
     * Iterates over a set of doc changes, applies the query limit, and computes
     * what the new results should be, what the changes were, and whether we may
     * need to go back to the local cache for more results. Does not make any
     * changes to the view.
     * @param docChanges - The doc changes to apply to this view.
     * @param previousChanges - If this is being called with a refill, then start
     *        with this set of docs and changes instead of the current view.
     * @returns a new set of docs, changes, and refill flag.
     */    Zu(e, t) {
        const n = t ? t.Xu : new __PRIVATE_DocumentChangeSet, r = t ? t.Ju : this.Ju;
        let i = t ? t.mutatedKeys : this.mutatedKeys, s = r, _ = false;
        const [o, a] = this.ec(this.query, r);
        e.inorderTraversal(((e, t) => {
            const u = r.get(e), c = __PRIVATE_queryOrPipelineMatches(this.query, t) ? t : null, l = !!u && this.mutatedKeys.has(u.key), E = !!c && (c.hasLocalMutations || 
            // We only consider committed mutations for documents that were
            // mutated during the lifetime of the view.
            this.mutatedKeys.has(c.key) && c.hasCommittedMutations);
            let h = false;
            // Calculate change
                        if (u && c) {
                u.data.isEqual(c.data) ? l !== E && (n.track({
                    type: 3 /* ChangeType.Metadata */ ,
                    doc: c
                }), h = true) : this.tc(u, c) || (n.track({
                    type: 2 /* ChangeType.Modified */ ,
                    doc: c
                }), h = true, (o && this.Hu(c, o) > 0 || a && this.Hu(c, a) < 0) && (
                // This doc moved from inside the limit to outside the limit.
                // That means there may be some other doc in the local cache
                // that should be included instead.
                _ = true));
            } else !u && c ? (n.track({
                type: 0 /* ChangeType.Added */ ,
                doc: c
            }), h = true) : u && !c && (n.track({
                type: 1 /* ChangeType.Removed */ ,
                doc: u
            }), h = true, (o || a) && (
            // A doc was removed from a full limit query. We'll need to
            // requery from the local cache to see if we know about some other
            // doc that should be in the results.
            _ = true));
            h && (c ? (s = s.add(c), i = E ? i.add(e) : i.delete(e)) : (s = s.delete(e), i = i.delete(e)));
        }));
        // Drop documents out to meet limit/limitToLast requirement.
        const u = this.nc(this.query);
        if (u) if (__PRIVATE_isPipeline(this.query)) {
            // TODO(pipeline): Not very efficient obviously, but should be fine for now.
            // Longer term, limit queries should be evaluated from query engine as well.
            const e = [];
            s.forEach((t => e.push(t)));
            const t = __PRIVATE_runPipeline(this.query, e);
            let r = new DocumentSet(__PRIVATE_newPipelineComparator(this.query));
            for (const e of t) r = r.add(e);
            s.forEach((e => {
                r.has(e.key) || (i = i.delete(e.key), n.track({
                    type: 1 /* ChangeType.Removed */ ,
                    doc: e
                }));
            })), s = r;
        } else {
            const e = this.rc(this.query);
            for (;s.size > u; ) {
                const t = "F" /* LimitType.First */ === e ? s.last() : s.first();
                s = s.delete(t.key), i = i.delete(t.key), n.track({
                    type: 1 /* ChangeType.Removed */ ,
                    doc: t
                });
            }
        }
        return {
            Ju: s,
            Xu: n,
            Fo: _,
            mutatedKeys: i
        };
    }
    nc(e) {
        return __PRIVATE_isPipeline(e) ? __PRIVATE_getLastEffectiveLimit(e)?.limit : e.limit || void 0;
    }
    rc(e) {
        if (__PRIVATE_isPipeline(e)) {
            const t = __PRIVATE_getLastEffectiveLimit(e);
            return t && t.limit < 0 ? "L" /* LimitType.Last */ : "F" /* LimitType.First */;
        }
        return e.limitType;
    }
    ec(e, t) {
        if (__PRIVATE_isPipeline(e)) {
            const n = __PRIVATE_getLastEffectiveLimit(e)?.limit;
            return [ t.size === n ? t.last() : null, null ];
        }
        return [ "F" /* LimitType.First */ === e.limitType && t.size === this.nc(this.query) ? t.last() : null, "L" /* LimitType.Last */ === e.limitType && t.size === this.nc(this.query) ? t.first() : null ];
    }
    tc(e, t) {
        // We suppress the initial change event for documents that were modified as
        // part of a write acknowledgment (e.g. when the value of a server transform
        // is applied) as Watch will send us the same document again.
        // By suppressing the event, we only raise two user visible events (one with
        // `hasPendingWrites` and the final state of the document) instead of three
        // (one with `hasPendingWrites`, the modified document with
        // `hasPendingWrites` and the final state of the document).
        return e.hasLocalMutations && t.hasCommittedMutations && !t.hasLocalMutations;
    }
    /**
     * Updates the view with the given ViewDocumentChanges and optionally updates
     * limbo docs and sync state from the provided target change.
     * @param docChanges - The set of changes to make to the view's docs.
     * @param limboResolutionEnabled - Whether to update limbo documents based on
     *        this change.
     * @param targetChange - A target change to apply for computing limbo docs and
     *        sync state.
     * @param targetIsPendingReset - Whether the target is pending to reset due to
     *        existence filter mismatch. If not explicitly specified, it is treated
     *        equivalently to `false`.
     * @returns A new ViewChange with the given docs, changes, and sync state.
     */
    // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
    applyChanges(e, t, n, r) {
        const i = this.Ju;
        this.Ju = e.Ju, this.mutatedKeys = e.mutatedKeys;
        // Sort changes based on type and query comparator
        const s = e.Xu.gu();
        s.sort(((e, t) => function __PRIVATE_compareChangeType(e, t) {
            const order = e => {
                switch (e) {
                  case 0 /* ChangeType.Added */ :
                    return 1;

                  case 2 /* ChangeType.Modified */ :
                  case 3 /* ChangeType.Metadata */ :
                    // A metadata change is converted to a modified change at the public
                    // api layer.  Since we sort by document key and then change type,
                    // metadata and modified changes must be sorted equivalently.
                    return 2;

                  case 1 /* ChangeType.Removed */ :
                    return 0;

                  default:
                    return l(20277, {
                        ye: e
                    });
                }
            };
            return order(e) - order(t);
        }
        /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (e.type, t.type) || this.Hu(e.doc, t.doc))), this.sc(n), r = r ?? false;
        const _ = t && !r ? this._c() : [], o = 0 === this.ju.size && this.current && !r ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , a = o !== this.zu;
        // We are at synced state if there is no limbo docs are waiting to be resolved, view is current
        // with the backend, and the query is not pending to reset due to existence filter mismatch.
                if (this.zu = o, 0 !== s.length || a) {
            return {
                snapshot: new ViewSnapshot(this.query, e.Ju, i, s, e.mutatedKeys, 0 /* SyncState.Local */ === o, a, 
                /* excludesMetadataChanges= */ false, !!n && n.resumeToken.approximateByteSize() > 0),
                oc: _
            };
        }
        // no changes
        return {
            oc: _
        };
    }
    /**
     * Applies an OnlineState change to the view, potentially generating a
     * ViewChange if the view's syncState changes as a result.
     */    Du(e) {
        return this.current && "Offline" /* OnlineState.Offline */ === e ? (
        // If we're offline, set `current` to false and then call applyChanges()
        // to refresh our syncState and generate a ViewChange as appropriate. We
        // are guaranteed to get a new TargetChange that sets `current` back to
        // true once the client is back online.
        this.current = false, this.applyChanges({
            Ju: this.Ju,
            Xu: new __PRIVATE_DocumentChangeSet,
            mutatedKeys: this.mutatedKeys,
            Fo: false
        }, 
        /* limboResolutionEnabled= */ false)) : {
            oc: []
        };
    }
    /**
     * Returns whether the doc for the given key should be in limbo.
     */    ac(e) {
        // If the remote end says it's part of this query, it's not in limbo.
        return !this.Gu.has(e) && (
        // The local store doesn't think it's a result, so it shouldn't be in limbo.
        !!this.Ju.has(e) && !this.Ju.get(e).hasLocalMutations);
    }
    /**
     * Updates syncedDocuments, current, and limbo docs based on the given change.
     * Returns the list of changes to which docs are in limbo.
     */    sc(e) {
        e && (e.addedDocuments.forEach((e => this.Gu = this.Gu.add(e))), e.modifiedDocuments.forEach((e => {})), 
        e.removedDocuments.forEach((e => this.Gu = this.Gu.delete(e))), this.current = e.current);
    }
    _c() {
        // We can only determine limbo documents when we're in-sync with the server.
        if (!this.current) return [];
        // TODO(klimt): Do this incrementally so that it's not quadratic when
        // updating many documents.
                const e = this.ju;
        this.ju = __PRIVATE_documentKeySet(), this.Ju.forEach((e => {
            this.ac(e.key) && (this.ju = this.ju.add(e.key));
        }));
        // Diff the new limbo docs with the old limbo docs.
        const t = [];
        return e.forEach((e => {
            this.ju.has(e) || t.push(new __PRIVATE_RemovedLimboDocument(e));
        })), this.ju.forEach((n => {
            e.has(n) || t.push(new __PRIVATE_AddedLimboDocument(n));
        })), t;
    }
    /**
     * Update the in-memory state of the current view with the state read from
     * persistence.
     *
     * We update the query view whenever a client's primary status changes:
     * - When a client transitions from primary to secondary, it can miss
     *   LocalStorage updates and its query views may temporarily not be
     *   synchronized with the state on disk.
     * - For secondary to primary transitions, the client needs to update the list
     *   of `syncedDocuments` since secondary clients update their query views
     *   based purely on synthesized RemoteEvents.
     *
     * @param queryResult.documents - The documents that match the query according
     * to the LocalStore.
     * @param queryResult.remoteKeys - The keys of the documents that match the
     * query according to the backend.
     *
     * @returns The ViewChange that resulted from this synchronization.
     */
    // PORTING NOTE: Multi-tab only.
    uc(e) {
        this.Gu = e.Wo, this.ju = __PRIVATE_documentKeySet();
        const t = this.Zu(e.documents);
        return this.applyChanges(t, /* limboResolutionEnabled= */ true);
    }
    /**
     * Returns a view snapshot as if this query was just listened to. Contains
     * a document add for every existing document and the `fromCache` and
     * `hasPendingWrites` status of the already established view.
     */
    // PORTING NOTE: Multi-tab only.
    cc() {
        return ViewSnapshot.fromInitialDocuments(this.query, this.Ju, this.mutatedKeys, 0 /* SyncState.Local */ === this.zu, this.hasCachedResults);
    }
}

const dr = "SyncEngine";

/**
 * QueryView contains all of the data that SyncEngine needs to keep track of for
 * a particular query.
 */ class __PRIVATE_QueryView {
    constructor(
    /**
     * The query itself.
     */
    e, 
    /**
     * The target number created by the client that is used in the watch
     * stream to identify this query.
     */
    t, 
    /**
     * The view is responsible for computing the final merged truth of what
     * docs are in the query. It gets notified of local and remote changes,
     * and applies the query filters and limits to determine the most correct
     * possible results.
     */
    n) {
        this.query = e, this.targetId = t, this.view = n;
    }
}

/** Tracks a limbo resolution. */ class LimboResolution {
    constructor(e) {
        this.key = e, 
        /**
         * Set to true once we've received a document. This is used in
         * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to
         * decide whether it needs to manufacture a delete event for the target once
         * the target is CURRENT.
         */
        this.lc = false;
    }
}

/**
 * An implementation of `SyncEngine` coordinating with other parts of SDK.
 *
 * The parts of SyncEngine that act as a callback to RemoteStore need to be
 * registered individually. This is done in `syncEngineWrite()` and
 * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods
 * serve as entry points to RemoteStore's functionality.
 *
 * Note: some field defined in this class might have public access level, but
 * the class is not exported so they are only accessible from this module.
 * This is useful to implement optional features (like bundles) in free
 * functions, such that they are tree-shakeable.
 */ class __PRIVATE_SyncEngineImpl {
    constructor(e, t, n, 
    // PORTING NOTE: Manages state synchronization in multi-tab environments.
    r, i, s) {
        this.localStore = e, this.remoteStore = t, this.eventManager = n, this.sharedClientState = r, 
        this.currentUser = i, this.maxConcurrentLimboResolutions = s, this.Ec = {}, this.hc = new ObjectMap((e => __PRIVATE_canonifyQueryOrPipeline(e)), __PRIVATE_queryOrPipelineEqual), 
        this.Tc = new Map, 
        /**
         * The keys of documents that are in limbo for which we haven't yet started a
         * limbo resolution query. The strings in this set are the result of calling
         * `key.path.canonicalString()` where `key` is a `DocumentKey` object.
         *
         * The `Set` type was chosen because it provides efficient lookup and removal
         * of arbitrary elements and it also maintains insertion order, providing the
         * desired queue-like FIFO semantics.
         */
        this.Pc = new Set, 
        /**
         * Keeps track of the target ID for each document that is in limbo with an
         * active target.
         */
        this.Rc = new SortedMap(DocumentKey.comparator), 
        /**
         * Keeps track of the information about an active limbo resolution for each
         * active target ID that was started for the purpose of limbo resolution.
         */
        this.Ic = new Map, this.Ac = new __PRIVATE_ReferenceSet, 
        /** Stores user completion handlers, indexed by User and BatchId. */
        this.Vc = {}, 
        /** Stores user callbacks waiting for all pending writes to be acknowledged. */
        this.dc = new Map, this.fc = __PRIVATE_TargetIdGenerator.ws(), this.onlineState = "Unknown" /* OnlineState.Unknown */ , 
        // The primary state is set to `true` or `false` immediately after Firestore
        // startup. In the interim, a client should only be considered primary if
        // `isPrimary` is true.
        this.mc = void 0;
    }
    get isPrimaryClient() {
        return true === this.mc;
    }
}

/**
 * Initiates the new listen, resolves promise when listen enqueued to the
 * server. All the subsequent view snapshots or errors are sent to the
 * subscribed handlers. Returns the initial snapshot.
 */
async function __PRIVATE_syncEngineListen(e, t, n = true) {
    const r = __PRIVATE_ensureWatchCallbacks(e);
    let i;
    const s = r.hc.get(t);
    return s ? (
    // PORTING NOTE: With Multi-Tab Web, it is possible that a query view
    // already exists when EventManager calls us for the first time. This
    // happens when the primary tab is already listening to this query on
    // behalf of another tab and the user of the primary also starts listening
    // to the query. EventManager will not have an assigned target ID in this
    // case and calls `listen` to obtain this ID.
    r.sharedClientState.addLocalQueryTarget(s.targetId), i = s.view.cc()) : i = await __PRIVATE_allocateTargetAndMaybeListen(r, t, n, 
    /** shouldInitializeView= */ true), i;
}

/** Query has been listening to the cache, and tries to initiate the remote store listen */ async function __PRIVATE_triggerRemoteStoreListen(e, t) {
    const n = __PRIVATE_ensureWatchCallbacks(e);
    await __PRIVATE_allocateTargetAndMaybeListen(n, t, 
    /** shouldListenToRemote= */ true, 
    /** shouldInitializeView= */ false);
}

async function __PRIVATE_allocateTargetAndMaybeListen(e, t, n, r) {
    const i = await __PRIVATE_localStoreAllocateTarget(e.localStore, __PRIVATE_isPipeline(t) ? t : __PRIVATE_queryToTarget(t)), s = i.targetId, _ = e.sharedClientState.addLocalQueryTarget(s, n);
    let o;
    return r && (o = await __PRIVATE_initializeViewAndComputeSnapshot(e, t, s, "current" === _, i.resumeToken)), 
    e.isPrimaryClient && n && __PRIVATE_remoteStoreListen(e.remoteStore, i), o;
}

/**
 * Registers a view for a previously unknown query and computes its initial
 * snapshot.
 */ async function __PRIVATE_initializeViewAndComputeSnapshot(e, t, n, r, i) {
    // PORTING NOTE: On Web only, we inject the code that registers new Limbo
    // targets based on view changes. This allows us to only depend on Limbo
    // changes when user code includes queries.
    e.gc = (t, n, r) => async function __PRIVATE_applyDocChanges(e, t, n, r) {
        let i = t.view.Zu(n);
        i.Fo && (
        // The query has a limit and some docs were removed, so we need
        // to re-run the query against the local store to make sure we
        // didn't lose any good docs that had been past the limit.
        i = await __PRIVATE_localStoreExecuteQuery(e.localStore, t.query, 
        /* usePreviousResults= */ false).then((({documents: e}) => t.view.Zu(e, i))));
        const s = r && r.targetChanges.get(t.targetId), _ = r && null != r.targetMismatches.get(t.targetId), o = t.view.applyChanges(i, 
        /* limboResolutionEnabled= */ e.isPrimaryClient, s, _);
        return __PRIVATE_updateTrackedLimbos(e, t.targetId, o.oc), o.snapshot;
    }(e, t, n, r);
    const s = await __PRIVATE_localStoreExecuteQuery(e.localStore, t, 
    /* usePreviousResults= */ true), _ = new __PRIVATE_View(t, s.Wo), o = _.Zu(s.documents), a = TargetChange.createSynthesizedTargetChangeForCurrentChange(n, r && "Offline" /* OnlineState.Offline */ !== e.onlineState, i), u = _.applyChanges(o, 
    /* limboResolutionEnabled= */ e.isPrimaryClient, a);
    __PRIVATE_updateTrackedLimbos(e, n, u.oc);
    const c = new __PRIVATE_QueryView(t, n, _);
    return e.hc.set(t, c), e.Tc.has(n) ? e.Tc.get(n).push(t) : e.Tc.set(n, [ t ]), u.snapshot;
}

/** Stops listening to the query. */ async function __PRIVATE_syncEngineUnlisten(e, t, n) {
    const r = __PRIVATE_debugCast(e), i = r.hc.get(t), s = r.Tc.get(i.targetId);
    if (s.length > 1) return r.Tc.set(i.targetId, s.filter((e => !__PRIVATE_queryOrPipelineEqual(e, t)))), 
    void r.hc.delete(t);
    // No other queries are mapped to the target, clean up the query and the target.
        if (r.isPrimaryClient) {
        // We need to remove the local query target first to allow us to verify
        // whether any other client is still interested in this target.
        r.sharedClientState.removeLocalQueryTarget(i.targetId);
        r.sharedClientState.isActiveQueryTarget(i.targetId) || await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, 
        /*keepPersistedTargetData=*/ false).then((() => {
            r.sharedClientState.clearQueryState(i.targetId), n && __PRIVATE_remoteStoreUnlisten(r.remoteStore, i.targetId), 
            __PRIVATE_removeAndCleanupTarget(r, i.targetId);
        })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
    } else __PRIVATE_removeAndCleanupTarget(r, i.targetId), await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, 
    /*keepPersistedTargetData=*/ true);
}

/** Unlistens to the remote store while still listening to the cache. */ async function __PRIVATE_triggerRemoteStoreUnlisten(e, t) {
    const n = __PRIVATE_debugCast(e), r = n.hc.get(t), i = n.Tc.get(r.targetId);
    n.isPrimaryClient && 1 === i.length && (
    // PORTING NOTE: Unregister the target ID with local Firestore client as
    // watch target.
    n.sharedClientState.removeLocalQueryTarget(r.targetId), __PRIVATE_remoteStoreUnlisten(n.remoteStore, r.targetId));
}

/**
 * Initiates the write of local mutation batch which involves adding the
 * writes to the mutation queue, notifying the remote store about new
 * mutations and raising events for any changes this write caused.
 *
 * The promise returned by this call is resolved when the above steps
 * have completed, *not* when the write was acked by the backend. The
 * userCallback is resolved once the write was acked/rejected by the
 * backend (or failed locally for any other reason).
 */ async function __PRIVATE_syncEngineWrite(e, t, n) {
    const r = __PRIVATE_syncEngineEnsureWriteCallbacks(e);
    try {
        const e = await function __PRIVATE_localStoreWriteLocally(e, t) {
            const n = __PRIVATE_debugCast(e), r = Timestamp.now(), i = t.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet());
            let s, _;
            return n.persistence.runTransaction("Locally write mutations", "readwrite", (e => {
                // Figure out which keys do not have a remote version in the cache, this
                // is needed to create the right overlay mutation: if no remote version
                // presents, we do not need to create overlays as patch mutations.
                // TODO(Overlay): Is there a better way to determine this? Using the
                //  document version does not work because local mutations set them back
                //  to 0.
                let o = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet();
                return n.Uo.getEntries(e, i).next((e => {
                    o = e, o.forEach(((e, t) => {
                        t.isValidDocument() || (a = a.add(e));
                    }));
                })).next((() => n.localDocuments.getOverlayedDocuments(e, o))).next((i => {
                    s = i;
                    // For non-idempotent mutations (such as `FieldValue.increment()`),
                    // we record the base state in a separate patch mutation. This is
                    // later used to guarantee consistent values and prevents flicker
                    // even if the backend sends us an update that already includes our
                    // transform.
                    const _ = [];
                    for (const e of t) {
                        const t = __PRIVATE_mutationExtractBaseValue(e, s.get(e.key).overlayedDocument);
                        null != t && 
                        // NOTE: The base state should only be applied if there's some
                        // existing document to override, so use a Precondition of
                        // exists=true
                        _.push(new __PRIVATE_PatchMutation(e.key, t, __PRIVATE_extractFieldMask(t.value.mapValue), Precondition.exists(!0)));
                    }
                    return n.mutationQueue.addMutationBatch(e, r, _, t);
                })).next((t => {
                    _ = t;
                    const r = t.applyToLocalDocumentSet(s, a);
                    return n.documentOverlayCache.saveOverlays(e, t.batchId, r);
                }));
            })).then((() => ({
                batchId: _.batchId,
                changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s)
            })));
        }(r.localStore, t);
        r.sharedClientState.addPendingMutation(e.batchId), function __PRIVATE_addMutationCallback(e, t, n) {
            let r = e.Vc[e.currentUser.toKey()];
            r || (r = new SortedMap(__PRIVATE_primitiveComparator));
            r = r.insert(t, n), e.Vc[e.currentUser.toKey()] = r;
        }
        /**
 * Resolves or rejects the user callback for the given batch and then discards
 * it.
 */ (r, e.batchId, n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e.changes), 
        await __PRIVATE_fillWritePipeline(r.remoteStore);
    } catch (e) {
        // If we can't persist the mutation, we reject the user callback and
        // don't send the mutation. The user can then retry the write.
        const t = __PRIVATE_wrapInUserErrorIfRecoverable(e, "Failed to persist write");
        n.reject(t);
    }
}

/**
 * Applies one remote event to the sync engine, notifying any views of the
 * changes, and releasing any pending mutation batches that would become
 * visible because of the snapshot version the remote event contains.
 */ async function __PRIVATE_syncEngineApplyRemoteEvent(e, t) {
    const n = __PRIVATE_debugCast(e);
    try {
        const e = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n.localStore, t);
        // Update `receivedDocument` as appropriate for any limbo targets.
                t.targetChanges.forEach(((e, t) => {
            const r = n.Ic.get(t);
            r && (
            // Since this is a limbo resolution lookup, it's for a single document
            // and it could be added, modified, or removed, but not a combination.
            __PRIVATE_hardAssert(e.addedDocuments.size + e.modifiedDocuments.size + e.removedDocuments.size <= 1, 22616), 
            e.addedDocuments.size > 0 ? r.lc = !0 : e.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r.lc, 14607) : e.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r.lc, 42227), 
            r.lc = !1));
        })), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e, t);
    } catch (e) {
        await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);
    }
}

/**
 * Applies an OnlineState change to the sync engine and notifies any views of
 * the change.
 */ function __PRIVATE_syncEngineApplyOnlineStateChange(e, t, n) {
    const r = __PRIVATE_debugCast(e);
    // If we are the secondary client, we explicitly ignore the remote store's
    // online state (the local client may go offline, even though the primary
    // tab remains online) and only apply the primary tab's online state from
    // SharedClientState.
        if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {
        const e = [];
        r.hc.forEach(((n, r) => {
            const i = r.view.Du(t);
            i.snapshot && e.push(i.snapshot);
        })), function __PRIVATE_eventManagerOnOnlineStateChange(e, t) {
            const n = __PRIVATE_debugCast(e);
            n.onlineState = t;
            let r = false;
            n.queries.forEach(((e, n) => {
                for (const e of n.wu) 
                // Run global snapshot listeners if a consistent snapshot has been emitted.
                e.Du(t) && (r = true);
            })), r && __PRIVATE_raiseSnapshotsInSyncEvent(n);
        }(r.eventManager, t), e.length && r.Ec.hn(e), r.onlineState = t, r.isPrimaryClient && r.sharedClientState.setOnlineState(t);
    }
}

/**
 * Rejects the listen for the given targetID. This can be triggered by the
 * backend for any active target.
 *
 * @param syncEngine - The sync engine implementation.
 * @param targetId - The targetID corresponds to one previously initiated by the
 * user as part of TargetData passed to listen() on RemoteStore.
 * @param err - A description of the condition that has forced the rejection.
 * Nearly always this will be an indication that the user is no longer
 * authorized to see the data matching the target.
 */ async function __PRIVATE_syncEngineRejectListen(e, t, n) {
    const r = __PRIVATE_debugCast(e);
    // PORTING NOTE: Multi-tab only.
        r.sharedClientState.updateQueryState(t, "rejected", n);
    const i = r.Ic.get(t), s = i && i.key;
    if (s) {
        // TODO(klimt): We really only should do the following on permission
        // denied errors, but we don't have the cause code here.
        // It's a limbo doc. Create a synthetic event saying it was deleted.
        // This is kind of a hack. Ideally, we would have a method in the local
        // store to purge a document. However, it would be tricky to keep all of
        // the local store's invariants with another method.
        let e = new SortedMap(DocumentKey.comparator);
        // TODO(b/217189216): This limbo document should ideally have a read time,
        // so that it is picked up by any read-time based scans. The backend,
        // however, does not send a read time for target removals.
                e = e.insert(s, MutableDocument.newNoDocument(s, SnapshotVersion.min()));
        const n = __PRIVATE_documentKeySet().add(s), i = new RemoteEvent(SnapshotVersion.min(), 
        /* targetChanges= */ new Map, 
        /* targetMismatches= */ new SortedMap(__PRIVATE_primitiveComparator), e, __PRIVATE_mutableDocumentMap(), n);
        await __PRIVATE_syncEngineApplyRemoteEvent(r, i), 
        // Since this query failed, we won't want to manually unlisten to it.
        // We only remove it from bookkeeping after we successfully applied the
        // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to
        // this query when the RemoteStore restarts the Watch stream, which should
        // re-trigger the target failure.
        r.Rc = r.Rc.remove(s), r.Ic.delete(t), __PRIVATE_pumpEnqueuedLimboResolutions(r);
    } else await __PRIVATE_localStoreReleaseTarget(r.localStore, t, 
    /* keepPersistedTargetData */ false).then((() => __PRIVATE_removeAndCleanupTarget(r, t, n))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
}

async function __PRIVATE_syncEngineApplySuccessfulWrite(e, t) {
    const n = __PRIVATE_debugCast(e), r = t.batch.batchId;
    try {
        const e = await __PRIVATE_localStoreAcknowledgeBatch(n.localStore, t);
        // The local store may or may not be able to apply the write result and
        // raise events immediately (depending on whether the watcher is caught
        // up), so we raise user callbacks first so that they consistently happen
        // before listen events.
                __PRIVATE_processUserCallback(n, r, /*error=*/ null), __PRIVATE_triggerPendingWritesCallbacks(n, r), 
        n.sharedClientState.updateMutationState(r, "acknowledged"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e);
    } catch (e) {
        await __PRIVATE_ignoreIfPrimaryLeaseLoss(e);
    }
}

async function __PRIVATE_syncEngineRejectFailedWrite(e, t, n) {
    const r = __PRIVATE_debugCast(e);
    try {
        const e = await function __PRIVATE_localStoreRejectBatch(e, t) {
            const n = __PRIVATE_debugCast(e);
            return n.persistence.runTransaction("Reject batch", "readwrite-primary", (e => {
                let r;
                return n.mutationQueue.lookupMutationBatch(e, t).next((t => (__PRIVATE_hardAssert(null !== t, 37113), 
                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)));
            }));
        }
        /**
 * Returns the largest (latest) batch id in mutation queue that is pending
 * server response.
 *
 * Returns `BATCHID_UNKNOWN` if the queue is empty.
 */ (r.localStore, t);
        // The local store may or may not be able to apply the write result and
        // raise events immediately (depending on whether the watcher is caught up),
        // so we raise user callbacks first so that they consistently happen before
        // listen events.
                __PRIVATE_processUserCallback(r, t, n), __PRIVATE_triggerPendingWritesCallbacks(r, t), 
        r.sharedClientState.updateMutationState(t, "rejected", n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e);
    } catch (n) {
        await __PRIVATE_ignoreIfPrimaryLeaseLoss(n);
    }
}

/**
 * Registers a user callback that resolves when all pending mutations at the moment of calling
 * are acknowledged .
 */ async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e, t) {
    const n = __PRIVATE_debugCast(e);
    __PRIVATE_canUseNetwork(n.remoteStore) || __PRIVATE_logDebug(dr, "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
    try {
        const e = await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e) {
            const t = __PRIVATE_debugCast(e);
            return t.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (e => t.mutationQueue.getHighestUnacknowledgedBatchId(e)));
        }(n.localStore);
        if (e === Ke) 
        // Trigger the callback right away if there is no pending writes at the moment.
        return void t.resolve();
        const r = n.dc.get(e) || [];
        r.push(t), n.dc.set(e, r);
    } catch (e) {
        const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, "Initialization of waitForPendingWrites() operation failed");
        t.reject(n);
    }
}

/**
 * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
 * if there are any.
 */ function __PRIVATE_triggerPendingWritesCallbacks(e, t) {
    (e.dc.get(t) || []).forEach((e => {
        e.resolve();
    })), e.dc.delete(t);
}

/** Reject all outstanding callbacks waiting for pending writes to complete. */ function __PRIVATE_processUserCallback(e, t, n) {
    const r = __PRIVATE_debugCast(e);
    let i = r.Vc[r.currentUser.toKey()];
    // NOTE: Mutations restored from persistence won't have callbacks, so it's
    // okay for there to be no callback for this ID.
        if (i) {
        const e = i.get(t);
        e && (n ? e.reject(n) : e.resolve(), i = i.remove(t)), r.Vc[r.currentUser.toKey()] = i;
    }
}

function __PRIVATE_removeAndCleanupTarget(e, t, n = null) {
    e.sharedClientState.removeLocalQueryTarget(t);
    for (const r of e.Tc.get(t)) e.hc.delete(r), n && e.Ec.yc(r, n);
    if (e.Tc.delete(t), e.isPrimaryClient) {
        e.Ac.Xs(t).forEach((t => {
            e.Ac.containsKey(t) || 
            // We removed the last reference for this key
            __PRIVATE_removeLimboTarget(e, t);
        }));
    }
}

function __PRIVATE_removeLimboTarget(e, t) {
    e.Pc.delete(t.path.canonicalString());
    // It's possible that the target already got removed because the query failed. In that case,
    // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.
    const n = e.Rc.get(t);
    null !== n && (__PRIVATE_remoteStoreUnlisten(e.remoteStore, n), e.Rc = e.Rc.remove(t), 
    e.Ic.delete(n), __PRIVATE_pumpEnqueuedLimboResolutions(e));
}

function __PRIVATE_updateTrackedLimbos(e, t, n) {
    for (const r of n) if (r instanceof __PRIVATE_AddedLimboDocument) e.Ac.addReference(r.key, t), 
    __PRIVATE_trackLimboChange(e, r); else if (r instanceof __PRIVATE_RemovedLimboDocument) {
        __PRIVATE_logDebug(dr, "Document no longer in limbo: " + r.key), e.Ac.removeReference(r.key, t);
        e.Ac.containsKey(r.key) || 
        // We removed the last reference for this key
        __PRIVATE_removeLimboTarget(e, r.key);
    } else l(19791, {
        wc: r
    });
}

function __PRIVATE_trackLimboChange(e, t) {
    const n = t.key, r = n.path.canonicalString();
    e.Rc.get(n) || e.Pc.has(r) || (__PRIVATE_logDebug(dr, "New document in limbo: " + n), 
    e.Pc.add(r), __PRIVATE_pumpEnqueuedLimboResolutions(e));
}

/**
 * Starts listens for documents in limbo that are enqueued for resolution,
 * subject to a maximum number of concurrent resolutions.
 *
 * Without bounding the number of concurrent resolutions, the server can fail
 * with "resource exhausted" errors which can lead to pathological client
 * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.
 */ function __PRIVATE_pumpEnqueuedLimboResolutions(e) {
    for (;e.Pc.size > 0 && e.Rc.size < e.maxConcurrentLimboResolutions; ) {
        const t = e.Pc.values().next().value;
        e.Pc.delete(t);
        const n = new DocumentKey(ResourcePath.fromString(t)), r = e.fc.next();
        e.Ic.set(r, new LimboResolution(n)), e.Rc = e.Rc.insert(n, r), __PRIVATE_remoteStoreListen(e.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n.path)), r, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ , __PRIVATE_ListenSequence.yn));
    }
}

async function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, t, n) {
    const r = __PRIVATE_debugCast(e), i = [], s = [], _ = [];
    r.hc.isEmpty() || (r.hc.forEach(((e, o) => {
        _.push(r.gc(o, t, n).then((e => {
            // If there are changes, or we are handling a global snapshot, notify
            // secondary clients to update query state.
            if ((e || n) && r.isPrimaryClient) {
                // Query state is set to `current` if:
                // - There is a view change and it is up-to-date, or,
                // - There is a global snapshot, the Target is current, and no changes to be resolved
                const t = e ? !e.fromCache : n?.targetChanges.get(o.targetId)?.current;
                r.sharedClientState.updateQueryState(o.targetId, t ? "current" : "not-current");
            }
            // Update views if there are actual changes.
                        if (e) {
                i.push(e);
                const t = __PRIVATE_LocalViewChanges.fo(o.targetId, e);
                s.push(t);
            }
        })));
    })), await Promise.all(_), r.Ec.hn(i), await async function __PRIVATE_localStoreNotifyLocalViewChanges(e, t) {
        const n = __PRIVATE_debugCast(e);
        try {
            await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (e => PersistencePromise.forEach(t, (t => PersistencePromise.forEach(t.Ao, (r => n.persistence.referenceDelegate.addReference(e, t.targetId, r))).next((() => PersistencePromise.forEach(t.Vo, (r => n.persistence.referenceDelegate.removeReference(e, t.targetId, r)))))))));
        } catch (e) {
            if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;
            // If `notifyLocalViewChanges` fails, we did not advance the sequence
            // number for the documents that were included in this transaction.
            // This might trigger them to be deleted earlier than they otherwise
            // would have, but it should not invalidate the integrity of the data.
            __PRIVATE_logDebug(lr, "Failed to update sequence numbers: " + e);
        }
        for (const e of t) {
            const t = e.targetId;
            if (!e.fromCache) {
                const e = n.No.get(t), r = e.snapshotVersion, i = e.withLastLimboFreeSnapshotVersion(r);
                // Advance the last limbo free snapshot version
                                n.No = n.No.insert(t, i);
            }
        }
    }(r.localStore, s));
}

async function __PRIVATE_syncEngineHandleCredentialChange(e, t) {
    const n = __PRIVATE_debugCast(e);
    if (!n.currentUser.isEqual(t)) {
        __PRIVATE_logDebug(dr, "User change. New user:", t.toKey());
        const e = await __PRIVATE_localStoreHandleUserChange(n.localStore, t);
        n.currentUser = t, 
        // Fails tasks waiting for pending writes requested by previous user.
        function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e, t) {
            e.dc.forEach((e => {
                e.forEach((e => {
                    e.reject(new s(aa.CANCELLED, t));
                }));
            })), e.dc.clear();
        }(n, "'waitForPendingWrites' promise is rejected due to a user change."), 
        // TODO(b/114226417): Consider calling this only in the primary tab.
        n.sharedClientState.handleUserChange(t, e.removedBatchIds, e.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e.qo);
    }
}

function __PRIVATE_syncEngineGetRemoteKeysForTarget(e, t) {
    const n = __PRIVATE_debugCast(e), r = n.Ic.get(t);
    if (r && r.lc) return __PRIVATE_documentKeySet().add(r.key);
    {
        let e = __PRIVATE_documentKeySet();
        const r = n.Tc.get(t);
        if (!r) return e;
        for (const t of r ?? []) {
            const r = n.hc.get(t);
            e = e.unionWith(r.view.Yu);
        }
        return e;
    }
}

/**
 * Reconcile the list of synced documents in an existing view with those
 * from persistence.
 */ async function __PRIVATE_synchronizeViewAndComputeSnapshot(e, t) {
    const n = __PRIVATE_debugCast(e), r = await __PRIVATE_localStoreExecuteQuery(n.localStore, t.query, 
    /* usePreviousResults= */ true), i = t.view.uc(r);
    return n.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n, t.targetId, i.oc), 
    i;
}

/**
 * Retrieves newly changed documents from remote document cache and raises
 * snapshots if needed.
 */
// PORTING NOTE: Multi-Tab only.
async function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e, t) {
    const n = __PRIVATE_debugCast(e);
    return __PRIVATE_localStoreGetNewDocumentChanges(n.localStore, t).then((e => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e)));
}

/** Applies a mutation state to an existing batch.  */
// PORTING NOTE: Multi-Tab only.
async function __PRIVATE_syncEngineApplyBatchState(e, t, n, r) {
    const i = __PRIVATE_debugCast(e), s = await function __PRIVATE_localStoreLookupMutationDocuments(e, t) {
        const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.mutationQueue);
        return n.persistence.runTransaction("Lookup mutation documents", "readonly", (e => r.Wr(e, t).next((t => t ? n.localDocuments.getDocuments(e, t) : PersistencePromise.resolve(null)))));
    }
    // PORTING NOTE: Multi-Tab only.
    (i.localStore, t);
    null !== s ? ("pending" === n ? 
    // If we are the primary client, we need to send this write to the
    // backend. Secondary clients will ignore these writes since their remote
    // connection is disabled.
    await __PRIVATE_fillWritePipeline(i.remoteStore) : "acknowledged" === n || "rejected" === n ? (
    // NOTE: Both these methods are no-ops for batches that originated from
    // other clients.
    __PRIVATE_processUserCallback(i, t, r || null), __PRIVATE_triggerPendingWritesCallbacks(i, t), 
    function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e, t) {
        __PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).jr(t);
    }
    // PORTING NOTE: Multi-Tab only.
    (i.localStore, t)) : l(6720, "Unknown batchState", {
        bc: n
    }), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, s)) : 
    // A throttled tab may not have seen the mutation before it was completed
    // and removed from the mutation queue, in which case we won't have cached
    // the affected documents. In this case we can safely ignore the update
    // since that means we didn't apply the mutation locally at all (if we
    // had, we would have cached the affected documents), and so we will just
    // see any resulting document changes via normal remote document updates
    // as applicable.
    __PRIVATE_logDebug(dr, "Cannot apply mutation batch with id: " + t);
}

/** Applies a query target change from a different tab. */
// PORTING NOTE: Multi-Tab only.
async function __PRIVATE_syncEngineApplyPrimaryState(e, t) {
    const n = __PRIVATE_debugCast(e);
    if (__PRIVATE_ensureWatchCallbacks(n), __PRIVATE_syncEngineEnsureWriteCallbacks(n), 
    true === t && true !== n.mc) {
        // Secondary tabs only maintain Views for their local listeners and the
        // Views internal state may not be 100% populated (in particular
        // secondary tabs don't track syncedDocuments, the set of documents the
        // server considers to be in the target). So when a secondary becomes
        // primary, we need to need to make sure that all views for all targets
        // match the state on disk.
        const e = n.sharedClientState.getAllActiveQueryTargets(), t = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e.toArray());
        n.mc = true, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, true);
        for (const e of t) __PRIVATE_remoteStoreListen(n.remoteStore, e);
    } else if (false === t && false !== n.mc) {
        const e = [];
        let t = Promise.resolve();
        n.Tc.forEach(((r, i) => {
            n.sharedClientState.isLocalQueryTarget(i) ? e.push(i) : t = t.then((() => (__PRIVATE_removeAndCleanupTarget(n, i), 
            __PRIVATE_localStoreReleaseTarget(n.localStore, i, 
            /*keepPersistedTargetData=*/ true)))), __PRIVATE_remoteStoreUnlisten(n.remoteStore, i);
        })), await t, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e), 
        // PORTING NOTE: Multi-Tab only.
        function __PRIVATE_resetLimboDocuments(e) {
            const t = __PRIVATE_debugCast(e);
            t.Ic.forEach(((e, n) => {
                __PRIVATE_remoteStoreUnlisten(t.remoteStore, n);
            })), t.Ac.e_(), t.Ic = new Map, t.Rc = new SortedMap(DocumentKey.comparator);
        }
        /**
 * Reconcile the query views of the provided query targets with the state from
 * persistence. Raises snapshots for any changes that affect the local
 * client and returns the updated state of all target's query data.
 *
 * @param syncEngine - The sync engine implementation
 * @param targets - the list of targets with views that need to be recomputed
 * @param transitionToPrimary - `true` iff the tab transitions from a secondary
 * tab to a primary tab
 */
        // PORTING NOTE: Multi-Tab only.
        (n), n.mc = false, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, false);
    }
}

async function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e, t, n) {
    const r = __PRIVATE_debugCast(e), i = [], s = [];
    for (const e of t) {
        let t;
        const n = r.Tc.get(e);
        if (n && 0 !== n.length) {
            // For queries that have a local View, we fetch their current state
            // from LocalStore (as the resume token and the snapshot version
            // might have changed) and reconcile their views with the persisted
            // state (the list of syncedDocuments may have gotten out of sync).
            t = await __PRIVATE_localStoreAllocateTarget(r.localStore, __PRIVATE_isPipeline(n[0]) ? n[0] : __PRIVATE_queryToTarget(n[0]));
            for (const e of n) {
                const t = r.hc.get(e), n = await __PRIVATE_synchronizeViewAndComputeSnapshot(r, t);
                n.snapshot && s.push(n.snapshot);
            }
        } else {
            // For queries that never executed on this client, we need to
            // allocate the target in LocalStore and initialize a new View.
            const n = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e);
            t = await __PRIVATE_localStoreAllocateTarget(r.localStore, n), await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(n), e, 
            /*current=*/ false, t.resumeToken);
        }
        i.push(t);
    }
    return r.Ec.hn(s), i;
}

/**
 * Creates a `Query` object from the specified `Target`. There is no way to
 * obtain the original `Query`, so we synthesize a `Query` from the `Target`
 * object.
 *
 * The synthesized result might be different from the original `Query`, but
 * since the synthesized `Query` should return the same results as the
 * original one (only the presentation of results might differ), the potential
 * difference will not cause issues.
 */
// PORTING NOTE: Multi-Tab only.
function __PRIVATE_synthesizeTargetToQuery(e) {
    return __PRIVATE_targetIsPipelineTarget(e) ? e : __PRIVATE_newQuery(e.path, e.collectionGroup, e.orderBy, e.filters, e.limit, "F" /* LimitType.First */ , e.startAt, e.endAt);
}

/** Returns the IDs of the clients that are currently active. */
// PORTING NOTE: Multi-Tab only.
function __PRIVATE_syncEngineGetActiveClients(e) {
    return function __PRIVATE_localStoreGetActiveClients(e) {
        return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).Ro();
    }(__PRIVATE_debugCast(e).localStore);
}

/** Applies a query target change from a different tab. */
// PORTING NOTE: Multi-Tab only.
async function __PRIVATE_syncEngineApplyTargetState(e, t, n, r) {
    const i = __PRIVATE_debugCast(e);
    if (i.mc) 
    // If we receive a target state notification via WebStorage, we are
    // either already secondary or another tab has taken the primary lease.
    return void __PRIVATE_logDebug(dr, "Ignoring unexpected query state notification.");
    const s = i.Tc.get(t);
    if (s && s.length > 0) switch (n) {
      case "current":
      case "not-current":
        {
            let e;
            if (__PRIVATE_isPipeline(s[0])) switch (getPipelineSourceType(s[0])) {
              case "collection_group":
              case "collection":
                e = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, getPipelineCollectionId(s[0]));
                break;

              case "documents":
                e = await function __PRIVATE_localStoreGetDocuments(e, t) {
                    const n = __PRIVATE_debugCast(e), r = __PRIVATE_documentKeySet(...getPipelineDocuments(t).map((e => DocumentKey.fromPath(e))));
                    return n.persistence.runTransaction("Get documents for pipeline", "readonly", (e => n.Uo.getEntries(e, r))).then((e => e));
                }(i.localStore, s[0]);
                break;

              default:
                __PRIVATE_logWarn(""), e = documentMap();
            } else e = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, function __PRIVATE_queryCollectionGroup(e) {
                return e.collectionGroup || (e.path.length % 2 == 1 ? e.path.lastSegment() : e.path.get(e.path.length - 2));
            }(s[0]));
            const r = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t, "current" === n, ByteString.EMPTY_BYTE_STRING);
            await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, e, r);
            break;
        }

      case "rejected":
        await __PRIVATE_localStoreReleaseTarget(i.localStore, t, 
        /* keepPersistedTargetData */ true), __PRIVATE_removeAndCleanupTarget(i, t, r);
        break;

      default:
        l(64155, n);
    }
}

/** Adds or removes Watch targets for queries from different tabs. */ async function __PRIVATE_syncEngineApplyActiveTargetsChange(e, t, n) {
    const r = __PRIVATE_ensureWatchCallbacks(e);
    if (r.mc) {
        for (const e of t) {
            if (r.Tc.has(e) && r.sharedClientState.isActiveQueryTarget(e)) {
                __PRIVATE_logDebug(dr, "Adding an already active target " + e);
                continue;
            }
            const t = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e), n = await __PRIVATE_localStoreAllocateTarget(r.localStore, t);
            await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(t), n.targetId, 
            /*current=*/ false, n.resumeToken), __PRIVATE_remoteStoreListen(r.remoteStore, n);
        }
        for (const e of n) 
        // Check that the target is still active since the target might have been
        // removed if it has been rejected by the backend.
        r.Tc.has(e) && 
        // Release queries that are still active.
        await __PRIVATE_localStoreReleaseTarget(r.localStore, e, 
        /* keepPersistedTargetData */ false).then((() => {
            __PRIVATE_remoteStoreUnlisten(r.remoteStore, e), __PRIVATE_removeAndCleanupTarget(r, e);
        })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss);
    }
}

function __PRIVATE_ensureWatchCallbacks(e) {
    const t = __PRIVATE_debugCast(e);
    return t.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t), 
    t.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t), 
    t.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t), 
    t.Ec.hn = __PRIVATE_eventManagerOnWatchChange.bind(null, t.eventManager), t.Ec.yc = __PRIVATE_eventManagerOnWatchError.bind(null, t.eventManager), 
    t;
}

function __PRIVATE_syncEngineEnsureWriteCallbacks(e) {
    const t = __PRIVATE_debugCast(e);
    return t.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t), 
    t.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t), 
    t;
}

/**
 * Loads a Firestore bundle into the SDK. The returned promise resolves when
 * the bundle finished loading.
 *
 * @param syncEngine - SyncEngine to use.
 * @param bundleReader - Bundle to load into the SDK.
 * @param task - LoadBundleTask used to update the loading progress to public API.
 */ function __PRIVATE_syncEngineLoadBundle(e, t, n) {
    const r = __PRIVATE_debugCast(e);
    // eslint-disable-next-line @typescript-eslint/no-floating-promises
        (
    /** Loads a bundle and returns the list of affected collection groups. */
    async function __PRIVATE_loadBundleImpl(e, t, n) {
        try {
            const r = await t.getMetadata();
            if (await function __PRIVATE_localStoreHasNewerBundle(e, t) {
                const n = __PRIVATE_debugCast(e), r = __PRIVATE_fromVersion(t.createTime);
                return n.persistence.runTransaction("hasNewerBundle", "readonly", (e => n.d_.getBundleMetadata(e, t.id))).then((e => !!e && e.createTime.compareTo(r) >= 0));
            }
            /**
 * Saves the given `BundleMetadata` to local persistence.
 */ (e.localStore, r)) return await t.close(), n._completeWith(function __PRIVATE_bundleSuccessProgress(e) {
                return {
                    taskState: "Success",
                    documentsLoaded: e.totalDocuments,
                    bytesLoaded: e.totalBytes,
                    totalDocuments: e.totalDocuments,
                    totalBytes: e.totalBytes
                };
            }(r)), Promise.resolve(new Set);
            n._updateProgress(__PRIVATE_bundleInitialProgress(r));
            const i = new __PRIVATE_BundleLoader(r, t.serializer);
            let s = await t.ma();
            for (;s; ) {
                const e = await i.qu(s);
                e && n._updateProgress(e), s = await t.ma();
            }
            const _ = await i.Ku(e.localStore);
            return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, _.Qu, 
            /* remoteEvent */ void 0), 
            // Save metadata, so loading the same bundle will skip.
            await function __PRIVATE_localStoreSaveBundle(e, t) {
                const n = __PRIVATE_debugCast(e);
                return n.persistence.runTransaction("Save bundle", "readwrite", (e => n.d_.saveBundleMetadata(e, t)));
            }
            /**
 * Returns a promise of a `NamedQuery` associated with given query name. Promise
 * resolves to undefined if no persisted data can be found.
 */ (e.localStore, r), n._completeWith(_.progress), Promise.resolve(_.Wu);
        } catch (e) {
            return __PRIVATE_logWarn(dr, `Loading bundle failed with ${e}`), n._failWith(e), 
            Promise.resolve(new Set);
        }
    }
    /**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
    /**
 * Provides all components needed for Firestore with in-memory persistence.
 * Uses EagerGC garbage collection.
 */)(r, t, n).then((e => {
        r.sharedClientState.notifyBundleLoaded(e);
    }));
}

class __PRIVATE_MemoryOfflineComponentProvider {
    constructor() {
        this.kind = "memory", this.synchronizeTabs = false;
    }
    async initialize(e) {
        this.serializer = __PRIVATE_newSerializer(e.databaseInfo.databaseId), this.sharedClientState = this.vc(e), 
        this.persistence = this.Sc(e), await this.persistence.start(), this.localStore = this.Dc(e), 
        this.gcScheduler = this.xc(e, this.localStore), this.indexBackfillerScheduler = this.Cc(e, this.localStore);
    }
    xc(e, t) {
        return null;
    }
    Cc(e, t) {
        return null;
    }
    Dc(e) {
        return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer);
    }
    Sc(e) {
        return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.w_, this.serializer);
    }
    vc(e) {
        return new __PRIVATE_MemorySharedClientState;
    }
    async terminate() {
        this.gcScheduler?.stop(), this.indexBackfillerScheduler?.stop(), this.sharedClientState.shutdown(), 
        await this.persistence.shutdown();
    }
}

__PRIVATE_MemoryOfflineComponentProvider.provider = {
    build: () => new __PRIVATE_MemoryOfflineComponentProvider
};

class __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider {
    constructor(e) {
        super(), this.cacheSizeBytes = e;
    }
    xc(e, t) {
        __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate, 46915);
        const n = this.persistence.referenceDelegate.garbageCollector;
        return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);
    }
    Sc(e) {
        const t = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;
        return new __PRIVATE_MemoryPersistence((e => __PRIVATE_MemoryLruDelegate.w_(e, t)), this.serializer);
    }
}

/**
 * Provides all components needed for Firestore with IndexedDB persistence.
 */ class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider {
    constructor(e, t, n) {
        super(), this.Fc = e, this.cacheSizeBytes = t, this.forceOwnership = n, this.kind = "persistent", 
        this.synchronizeTabs = false;
    }
    async initialize(e) {
        await super.initialize(e), await this.Fc.initialize(this, e), 
        // Enqueue writes from a previous session
        await __PRIVATE_syncEngineEnsureWriteCallbacks(this.Fc.syncEngine), await __PRIVATE_fillWritePipeline(this.Fc.remoteStore), 
        // NOTE: This will immediately call the listener, so we make sure to
        // set it after localStore / remoteStore are started.
        await this.persistence.X_((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), 
        this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), 
        Promise.resolve())));
    }
    Dc(e) {
        return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer);
    }
    xc(e, t) {
        const n = this.persistence.referenceDelegate.garbageCollector;
        return new __PRIVATE_LruScheduler(n, e.asyncQueue, t);
    }
    Cc(e, t) {
        const n = new __PRIVATE_IndexBackfiller(t, this.persistence);
        return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue, n);
    }
    Sc(e) {
        const t = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT;
        return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t, e.clientId, n, e.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership);
    }
    vc(e) {
        return new __PRIVATE_MemorySharedClientState;
    }
}

/**
 * Provides all components needed for Firestore with multi-tab IndexedDB
 * persistence.
 *
 * In the legacy client, this provider is used to provide both multi-tab and
 * non-multi-tab persistence since we cannot tell at build time whether
 * `synchronizeTabs` will be enabled.
 */ class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider {
    constructor(e, t) {
        super(e, t, /* forceOwnership= */ false), this.Fc = e, this.cacheSizeBytes = t, this.synchronizeTabs = true;
    }
    async initialize(e) {
        await super.initialize(e);
        const t = this.Fc.syncEngine;
        this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = {
            Iu: __PRIVATE_syncEngineApplyBatchState.bind(null, t),
            Au: __PRIVATE_syncEngineApplyTargetState.bind(null, t),
            Vu: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t),
            Ro: __PRIVATE_syncEngineGetActiveClients.bind(null, t),
            Ru: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t)
        }, await this.sharedClientState.start()), 
        // NOTE: This will immediately call the listener, so we make sure to
        // set it after localStore / remoteStore are started.
        await this.persistence.X_((async e => {
            await __PRIVATE_syncEngineApplyPrimaryState(this.Fc.syncEngine, e), this.gcScheduler && (e && !this.gcScheduler.started ? this.gcScheduler.start() : e || this.gcScheduler.stop()), 
            this.indexBackfillerScheduler && (e && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e || this.indexBackfillerScheduler.stop());
        }));
    }
    vc(e) {
        const t = __PRIVATE_getWindow();
        if (!__PRIVATE_WebStorageSharedClientState.Je(t)) throw new s(aa.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
        const n = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey);
        return new __PRIVATE_WebStorageSharedClientState(t, e.asyncQueue, n, e.clientId, e.initialUser);
    }
}

/**
 * Initializes and wires the components that are needed to interface with the
 * network.
 */ class OnlineComponentProvider {
    async initialize(e, t) {
        this.localStore || (this.localStore = e.localStore, this.sharedClientState = e.sharedClientState, 
        this.datastore = this.createDatastore(t), this.remoteStore = this.createRemoteStore(t), 
        this.eventManager = this.createEventManager(t), this.syncEngine = this.createSyncEngine(t, 
        /* startAsPrimary=*/ !e.synchronizeTabs), this.sharedClientState.onlineStateHandler = e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 1 /* OnlineStateSource.SharedClientState */), 
        this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), 
        await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient));
    }
    createEventManager(e) {
        return function __PRIVATE_newEventManager() {
            return new __PRIVATE_EventManagerImpl;
        }();
    }
    createDatastore(e) {
        const t = __PRIVATE_newSerializer(e.databaseInfo.databaseId), n = __PRIVATE_newConnection(e.databaseInfo);
        return __PRIVATE_newDatastore(e.authCredentials, e.appCheckCredentials, n, t);
    }
    createRemoteStore(e) {
        return function __PRIVATE_newRemoteStore(e, t, n, r, i) {
            return new __PRIVATE_RemoteStoreImpl(e, t, n, r, i);
        }
        /** Re-enables the network. Idempotent. */ (this.localStore, this.datastore, e.asyncQueue, (e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 0 /* OnlineStateSource.RemoteStore */)), function __PRIVATE_newConnectivityMonitor() {
            return __PRIVATE_BrowserConnectivityMonitor.Je() ? new __PRIVATE_BrowserConnectivityMonitor : new __PRIVATE_NoopConnectivityMonitor;
        }
        /**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ ());
    }
    createSyncEngine(e, t) {
        return function __PRIVATE_newSyncEngine(e, t, n, 
        // PORTING NOTE: Manages state synchronization in multi-tab environments.
        r, i, s, _) {
            const o = new __PRIVATE_SyncEngineImpl(e, t, n, r, i, s);
            return _ && (o.mc = true), o;
        }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e.initialUser, e.maxConcurrentLimboResolutions, t);
    }
    async terminate() {
        await async function __PRIVATE_remoteStoreShutdown(e) {
            const t = __PRIVATE_debugCast(e);
            __PRIVATE_logDebug(hr, "RemoteStore shutting down."), t.ca.add(5 /* OfflineCause.Shutdown */), 
            await __PRIVATE_disableNetworkInternal(t), t.Ea.shutdown(), 
            // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
            // triggering spurious listener events with cached data, etc.
            t.ha.set("Unknown" /* OnlineState.Unknown */);
        }(this.remoteStore), this.datastore?.terminate(), this.eventManager?.terminate();
    }
}

OnlineComponentProvider.provider = {
    build: () => new OnlineComponentProvider
};

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Internal transaction object responsible for accumulating the mutations to
 * perform and the base versions for any documents read.
 */
class Transaction {
    constructor(e) {
        this.datastore = e, 
        // The version of each document that was read during this transaction.
        this.readVersions = new Map, this.mutations = [], this.committed = false, 
        /**
         * A deferred usage error that occurred previously in this transaction that
         * will cause the transaction to fail once it actually commits.
         */
        this.lastTransactionError = null, 
        /**
         * Set of documents that have been written in the transaction.
         *
         * When there's more than one write to the same key in a transaction, any
         * writes after the first are handled differently.
         */
        this.writtenDocs = new Set;
    }
    async lookup(e) {
        if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new s(aa.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes."), 
        this.lastTransactionError;
        const t = await async function __PRIVATE_invokeBatchGetDocumentsRpc(e, t) {
            const n = __PRIVATE_debugCast(e), r = {
                documents: t.map((e => __PRIVATE_toName(n.serializer, e)))
            }, i = await n.st("BatchGetDocuments", n.serializer.databaseId, ResourcePath.emptyPath(), r, t.length), s = new Map;
            i.forEach((e => {
                const t = __PRIVATE_fromBatchGetDocumentsResponse(n.serializer, e);
                s.set(t.key.toString(), t);
            }));
            const _ = [];
            return t.forEach((e => {
                const t = s.get(e.toString());
                __PRIVATE_hardAssert(!!t, 55234, {
                    key: e
                }), _.push(t);
            })), _;
        }(this.datastore, e);
        return t.forEach((e => this.recordVersion(e))), t;
    }
    set(e, t) {
        this.write(t.toMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());
    }
    update(e, t) {
        try {
            this.write(t.toMutation(e, this.preconditionForUpdate(e)));
        } catch (e) {
            this.lastTransactionError = e;
        }
        this.writtenDocs.add(e.toString());
    }
    delete(e) {
        this.write(new __PRIVATE_DeleteMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString());
    }
    async commit() {
        if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError;
        const e = this.readVersions;
        // For each mutation, note that the doc was written.
                this.mutations.forEach((t => {
            e.delete(t.key.toString());
        })), 
        // For each document that was read but not written to, we want to perform
        // a `verify` operation.
        e.forEach(((e, t) => {
            const n = DocumentKey.fromPath(t);
            this.mutations.push(new __PRIVATE_VerifyMutation(n, this.precondition(n)));
        })), await async function __PRIVATE_invokeCommitRpc(e, t) {
            const n = __PRIVATE_debugCast(e), r = {
                writes: t.map((e => toMutation(n.serializer, e)))
            };
            await n.tt("Commit", n.serializer.databaseId, ResourcePath.emptyPath(), r);
        }(this.datastore, this.mutations), this.committed = true;
    }
    recordVersion(e) {
        let t;
        if (e.isFoundDocument()) t = e.version; else {
            if (!e.isNoDocument()) throw l(50498, {
                Oc: e.constructor.name
            });
            // Represent a deleted doc using SnapshotVersion.min().
            t = SnapshotVersion.min();
        }
        const n = this.readVersions.get(e.key.toString());
        if (n) {
            if (!t.isEqual(n)) 
            // This transaction will fail no matter what.
            throw new s(aa.ABORTED, "Document version changed between two reads.");
        } else this.readVersions.set(e.key.toString(), t);
    }
    /**
     * Returns the version of this document when it was read in this transaction,
     * as a precondition, or no precondition if it was not read.
     */    precondition(e) {
        const t = this.readVersions.get(e.toString());
        return !this.writtenDocs.has(e.toString()) && t ? t.isEqual(SnapshotVersion.min()) ? Precondition.exists(false) : Precondition.updateTime(t) : Precondition.none();
    }
    /**
     * Returns the precondition for a document if the operation is an update.
     */    preconditionForUpdate(e) {
        const t = this.readVersions.get(e.toString());
        // The first time a document is written, we want to take into account the
        // read time and existence
                if (!this.writtenDocs.has(e.toString()) && t) {
            if (t.isEqual(SnapshotVersion.min())) 
            // The document doesn't exist, so fail the transaction.
            // This has to be validated locally because you can't send a
            // precondition that a document does not exist without changing the
            // semantics of the backend write to be an insert. This is the reverse
            // of what we want, since we want to assert that the document doesn't
            // exist but then send the update and have it fail. Since we can't
            // express that to the backend, we have to validate locally.
            // Note: this can change once we can send separate verify writes in the
            // transaction.
            throw new s(aa.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
            // Document exists, base precondition on document update time.
                        return Precondition.updateTime(t);
        }
        // Document was not read, so we just use the preconditions for a blind
        // update.
        return Precondition.exists(true);
    }
    write(e) {
        this.ensureCommitNotCalled(), this.mutations.push(e);
    }
    ensureCommitNotCalled() {}
}

/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * TransactionRunner encapsulates the logic needed to run and retry transactions
 * with backoff.
 */ class __PRIVATE_TransactionRunner {
    constructor(e, t, n, r, i) {
        this.asyncQueue = e, this.datastore = t, this.options = n, this.updateFunction = r, 
        this.deferred = i, this.Mc = n.maxAttempts, this.jt = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */);
    }
    /** Runs the transaction and sets the result on deferred. */    Nc() {
        this.Mc -= 1, this.Lc();
    }
    Lc() {
        this.jt.Ut((async () => {
            const e = new Transaction(this.datastore), t = this.Bc(e);
            t && t.then((t => {
                this.asyncQueue.enqueueAndForget((() => e.commit().then((() => {
                    this.deferred.resolve(t);
                })).catch((e => {
                    this.Uc(e);
                }))));
            })).catch((e => {
                this.Uc(e);
            }));
        }));
    }
    Bc(e) {
        try {
            const t = this.updateFunction(e);
            return !__PRIVATE_isNullOrUndefined(t) && t.catch && t.then ? t : (this.deferred.reject(Error("Transaction callback must return a Promise")), 
            null);
        } catch (e) {
            // Do not retry errors thrown by user provided updateFunction.
            return this.deferred.reject(e), null;
        }
    }
    Uc(e) {
        this.Mc > 0 && this.kc(e) ? (this.Mc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Lc(), 
        Promise.resolve())))) : this.deferred.reject(e);
    }
    kc(e) {
        if ("FirebaseError" === e?.name) {
            // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and
            // non-matching document versions with ABORTED. These errors should be retried.
            const t = e.code;
            return "aborted" === t || "failed-precondition" === t || "already-exists" === t || !__PRIVATE_isPermanentError(t);
        }
        return false;
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const fr = "FirestoreClient";

/**
 * FirestoreClient is a top-level class that constructs and owns all of the //
 * pieces of the client SDK architecture. It is responsible for creating the //
 * async queue that is shared by all of the other components in the system. //
 */
class FirestoreClient {
    constructor(e, t, 
    /**
     * Asynchronous queue responsible for all of our internal processing. When
     * we get incoming work from the user (via public API) or the network
     * (incoming GRPC messages), we should always schedule onto this queue.
     * This ensures all of our work is properly serialized (e.g. we don't
     * start processing a new operation while the previous one is waiting for
     * an async I/O to complete).
     */
    n, 
    /**
     * Exposed for testing
     */
    r, i) {
        this.authCredentials = e, this.appCheckCredentials = t, this.asyncQueue = n, this._databaseInfo = r, 
        this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.newId(), this.authCredentialListener = () => Promise.resolve(), 
        this.appCheckCredentialListener = () => Promise.resolve(), this._uninitializedComponentsProvider = i, 
        this.authCredentials.start(n, (async e => {
            __PRIVATE_logDebug(fr, "Received user=", e.uid), await this.authCredentialListener(e), 
            this.user = e;
        })), this.appCheckCredentials.start(n, (e => (__PRIVATE_logDebug(fr, "Received new app check token=", e), 
        this.appCheckCredentialListener(e, this.user))));
    }
    get configuration() {
        return {
            asyncQueue: this.asyncQueue,
            databaseInfo: this._databaseInfo,
            clientId: this.clientId,
            authCredentials: this.authCredentials,
            appCheckCredentials: this.appCheckCredentials,
            initialUser: this.user,
            maxConcurrentLimboResolutions: 100
        };
    }
    setCredentialChangeListener(e) {
        this.authCredentialListener = e;
    }
    setAppCheckTokenChangeListener(e) {
        this.appCheckCredentialListener = e;
    }
    terminate() {
        this.asyncQueue.enterRestrictedMode();
        const e = new __PRIVATE_Deferred;
        return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {
            try {
                this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), 
                // The credentials provider must be terminated after shutting down the
                // RemoteStore as it will prevent the RemoteStore from retrieving auth
                // tokens.
                this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e.resolve();
            } catch (t) {
                const n = __PRIVATE_wrapInUserErrorIfRecoverable(t, "Failed to shutdown persistence");
                e.reject(n);
            }
        })), e.promise;
    }
}

async function __PRIVATE_setOfflineComponentProvider(e, t) {
    e.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(fr, "Initializing OfflineComponentProvider");
    const n = e.configuration;
    await t.initialize(n);
    let r = n.initialUser;
    e.setCredentialChangeListener((async e => {
        r.isEqual(e) || (await __PRIVATE_localStoreHandleUserChange(t.localStore, e), r = e);
    })), 
    // When a user calls clearPersistence() in one client, all other clients
    // need to be terminated to allow the delete to succeed.
    t.persistence.setDatabaseDeletedListener((() => e.terminate())), e._offlineComponents = t;
}

async function __PRIVATE_setOnlineComponentProvider(e, t) {
    e.asyncQueue.verifyOperationInProgress();
    const n = await __PRIVATE_ensureOfflineComponents(e);
    __PRIVATE_logDebug(fr, "Initializing OnlineComponentProvider"), await t.initialize(n, e.configuration), 
    // The CredentialChangeListener of the online component provider takes
    // precedence over the offline component provider.
    e.setCredentialChangeListener((e => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, e))), 
    e.setAppCheckTokenChangeListener(((e, n) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, n))), 
    e._onlineComponents = t;
}

/**
 * Decides whether the provided error allows us to gracefully disable
 * persistence (as opposed to crashing the client).
 */ async function __PRIVATE_ensureOfflineComponents(e) {
    if (!e._offlineComponents) if (e._uninitializedComponentsProvider) {
        __PRIVATE_logDebug(fr, "Using user provided OfflineComponentProvider");
        try {
            await __PRIVATE_setOfflineComponentProvider(e, e._uninitializedComponentsProvider._offline);
        } catch (t) {
            const n = t;
            if (!function __PRIVATE_canFallbackFromIndexedDbError(e) {
                return "FirebaseError" === e.name ? e.code === aa.FAILED_PRECONDITION || e.code === aa.UNIMPLEMENTED : !("undefined" != typeof DOMException && e instanceof DOMException) || 
                // When the browser is out of quota we could get either quota exceeded
                // or an aborted error depending on whether the error happened during
                // schema migration.
                22 === e.code || 20 === e.code || 
                // Firefox Private Browsing mode disables IndexedDb and returns
                // INVALID_STATE for any usage.
                11 === e.code;
            }(n)) throw n;
            __PRIVATE_logWarn("Error using user provided cache. Falling back to memory cache: " + n), 
            await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_MemoryOfflineComponentProvider);
        }
    } else __PRIVATE_logDebug(fr, "Using default OfflineComponentProvider"), await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0));
    return e._offlineComponents;
}

async function __PRIVATE_ensureOnlineComponents(e) {
    return e._onlineComponents || (e._uninitializedComponentsProvider ? (__PRIVATE_logDebug(fr, "Using user provided OnlineComponentProvider"), 
    await __PRIVATE_setOnlineComponentProvider(e, e._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(fr, "Using default OnlineComponentProvider"), 
    await __PRIVATE_setOnlineComponentProvider(e, new OnlineComponentProvider))), e._onlineComponents;
}

function __PRIVATE_getPersistence(e) {
    return __PRIVATE_ensureOfflineComponents(e).then((e => e.persistence));
}

function __PRIVATE_getLocalStore(e) {
    return __PRIVATE_ensureOfflineComponents(e).then((e => e.localStore));
}

function __PRIVATE_getRemoteStore(e) {
    return __PRIVATE_ensureOnlineComponents(e).then((e => e.remoteStore));
}

function __PRIVATE_getSyncEngine(e) {
    return __PRIVATE_ensureOnlineComponents(e).then((e => e.syncEngine));
}

function __PRIVATE_getDatastore(e) {
    return __PRIVATE_ensureOnlineComponents(e).then((e => e.datastore));
}

async function __PRIVATE_getEventManager(e) {
    const t = await __PRIVATE_ensureOnlineComponents(e), n = t.eventManager;
    return n.onListen = __PRIVATE_syncEngineListen.bind(null, t.syncEngine), n.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t.syncEngine), 
    n.onFirstRemoteStoreListen = __PRIVATE_triggerRemoteStoreListen.bind(null, t.syncEngine), 
    n.onLastRemoteStoreUnlisten = __PRIVATE_triggerRemoteStoreUnlisten.bind(null, t.syncEngine), 
    n;
}

/** Enables the network connection and re-enqueues all pending operations. */ function __PRIVATE_firestoreClientEnableNetwork(e) {
    return e.asyncQueue.enqueue((async () => {
        const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);
        return t.setNetworkEnabled(true), function __PRIVATE_remoteStoreEnableNetwork(e) {
            const t = __PRIVATE_debugCast(e);
            return t.ca.delete(0 /* OfflineCause.UserDisabled */), __PRIVATE_enableNetworkInternal(t);
        }(n);
    }));
}

/** Disables the network connection. Pending operations will not complete. */ function __PRIVATE_firestoreClientDisableNetwork(e) {
    return e.asyncQueue.enqueue((async () => {
        const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e);
        return t.setNetworkEnabled(false), async function __PRIVATE_remoteStoreDisableNetwork(e) {
            const t = __PRIVATE_debugCast(e);
            t.ca.add(0 /* OfflineCause.UserDisabled */), await __PRIVATE_disableNetworkInternal(t), 
            // Set the OnlineState to Offline so get()s return from cache, etc.
            t.ha.set("Offline" /* OnlineState.Offline */);
        }(n);
    }));
}

/**
 * Returns a Promise that resolves when all writes that were pending at the time
 * this method was called received server acknowledgement. An acknowledgement
 * can be either acceptance or rejection.
 */ function __PRIVATE_firestoreClientListen(e, t, n, r) {
    const i = new __PRIVATE_AsyncObserver(r), s = new __PRIVATE_QueryListener(t, i, n);
    return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e), s))), 
    () => {
        i.Aa(), e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e), s)));
    };
}

function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e, t) {
    const n = new __PRIVATE_Deferred;
    return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_readDocumentFromCache(e, t, n) {
        try {
            const r = await function __PRIVATE_localStoreReadDocument(e, t) {
                const n = __PRIVATE_debugCast(e);
                return n.persistence.runTransaction("read document", "readonly", (e => n.localDocuments.getDocument(e, t)));
            }(e, t);
            r.isFoundDocument() ? n.resolve(r) : r.isNoDocument() ? n.resolve(null) : n.reject(new s(aa.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.)"));
        } catch (e) {
            const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to get document '${t} from cache`);
            n.reject(r);
        }
    }
    /**
 * Retrieves a latency-compensated document from the backend via a
 * SnapshotListener.
 */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise;
}

function __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e, t, n = {}) {
    const r = new __PRIVATE_Deferred;
    return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_readDocumentViaSnapshotListener(e, t, n, r, i) {
        const _ = new __PRIVATE_AsyncObserver({
            next: a => {
                // Mute and remove query first before passing event to user to avoid
                // user actions affecting the now stale query.
                _.Aa(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o)));
                const u = a.docs.has(n);
                !u && a.fromCache ? 
                // TODO(dimond): If we're online and the document doesn't
                // exist then we resolve with a doc.exists set to false. If
                // we're offline however, we reject the Promise in this
                // case. Two options: 1) Cache the negative response from
                // the server so we can deliver that even when you're
                // offline 2) Actually reject the Promise in the online case
                // if the document doesn't exist.
                i.reject(new s(aa.UNAVAILABLE, "Failed to get document because the client is offline.")) : u && a.fromCache && r && "server" === r.source ? i.reject(new s(aa.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(a);
            },
            error: e => i.reject(e)
        }), o = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n.path), _, {
            includeMetadataChanges: true,
            waitForSyncWhenOnline: true
        });
        return __PRIVATE_eventManagerListen(e, o);
    }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise;
}

function __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e, t) {
    const n = new __PRIVATE_Deferred;
    return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_executeQueryFromCache(e, t, n) {
        try {
            const r = await __PRIVATE_localStoreExecuteQuery(e, t, 
            /* usePreviousResults= */ !0), i = new __PRIVATE_View(t, r.Wo), s = i.Zu(r.documents), _ = i.applyChanges(s, 
            /* limboResolutionEnabled= */ !1);
            n.resolve(_.snapshot);
        } catch (e) {
            const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to execute query '${t} against cache`);
            n.reject(r);
        }
    }
    /**
 * Retrieves a latency-compensated query snapshot from the backend via a
 * SnapshotListener.
 */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise;
}

function __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e, t, n = {}) {
    const r = new __PRIVATE_Deferred;
    return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_executeQueryViaSnapshotListener(e, t, n, r, i) {
        const _ = new __PRIVATE_AsyncObserver({
            next: n => {
                // Mute and remove query first before passing event to user to avoid
                // user actions affecting the now stale query.
                _.Aa(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))), n.fromCache && "server" === r.source ? i.reject(new s(aa.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);
            },
            error: e => i.reject(e)
        }), o = new __PRIVATE_QueryListener(n instanceof __PRIVATE_RealtimePipeline ? __PRIVATE_toCorePipeline(n) : n, _, {
            includeMetadataChanges: true,
            waitForSyncWhenOnline: true
        });
        return __PRIVATE_eventManagerListen(e, o);
    }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise;
}

function __PRIVATE_firestoreClientRunAggregateQuery(e, t, n) {
    const r = new __PRIVATE_Deferred;
    return e.asyncQueue.enqueueAndForget((async () => {
        // Implement and call executeAggregateQueryViaSnapshotListener, similar
        // to the implementation in firestoreClientGetDocumentsViaSnapshotListener
        // above
        try {
            // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab.
            const i = await __PRIVATE_getDatastore(e);
            r.resolve(async function __PRIVATE_invokeRunAggregationQueryRpc(e, t, n) {
                const r = __PRIVATE_debugCast(e), {request: i, ve: s, parent: _} = __PRIVATE_toRunAggregationQueryRequest(r.serializer, __PRIVATE_queryToAggregateTarget(t), n);
                r.connection.Ye || delete i.parent;
                const o = (await r.st("RunAggregationQuery", r.serializer.databaseId, _, i, 
                /*expectedResponseCount=*/ 1)).filter((e => !!e.result));
                // Omit RunAggregationQueryResponse that only contain readTimes.
                                __PRIVATE_hardAssert(1 === o.length, 64727);
                // Remap the short-form aliases that were sent to the server
                // to the client-side aliases. Users will access the results
                // using the client-side alias.
                const a = o[0].result?.aggregateFields;
                return Object.keys(a).reduce(((e, t) => (e[s[t]] = a[t], e)), {});
            }(i, t, n));
        } catch (e) {
            r.reject(e);
        }
    })), r.promise;
}

function ha(e, t) {
    const n = new __PRIVATE_Deferred;
    return e.asyncQueue.enqueueAndForget((async () => {
        try {
            const r = await __PRIVATE_getDatastore(e);
            n.resolve(async function __PRIVATE_invokeExecutePipeline(e, t) {
                const n = __PRIVATE_debugCast(e), r = {
                    database: __PRIVATE_getEncodedDatabaseId(n.serializer),
                    structuredPipeline: t._toProto(n.serializer)
                }, i = await n.st("ExecutePipeline", n.serializer.databaseId, ResourcePath.emptyPath(), r), s = [];
                return i.forEach((e => {
                    if (e.results && 0 !== e.results.length) return e.results.forEach((t => s.push(__PRIVATE_fromPipelineResponse(n.serializer, e, t))));
                    s.push(__PRIVATE_fromPipelineResponse(n.serializer, e));
                })), s;
            }(r, t));
        } catch (e) {
            n.reject(e);
        }
    })), n.promise;
}

function __PRIVATE_firestoreClientWrite(e, t) {
    const n = new __PRIVATE_Deferred;
    return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e), t, n))), 
    n.promise;
}

function __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e, t) {
    const n = new __PRIVATE_AsyncObserver(t);
    return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_addSnapshotsInSyncListener(e, t) {
        __PRIVATE_debugCast(e).Su.add(t), 
        // Immediately fire an initial event, indicating all existing listeners
        // are in-sync.
        t.next();
    }(await __PRIVATE_getEventManager(e), n))), () => {
        n.Aa(), e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_removeSnapshotsInSyncListener(e, t) {
            __PRIVATE_debugCast(e).Su.delete(t);
        }(await __PRIVATE_getEventManager(e), n)));
    };
}

/**
 * Takes an updateFunction in which a set of reads and writes can be performed
 * atomically. In the updateFunction, the client can read and write values
 * using the supplied transaction object. After the updateFunction, all
 * changes will be committed. If a retryable error occurs (ex: some other
 * client has changed any of the data referenced), then the updateFunction
 * will be called again after a backoff. If the updateFunction still fails
 * after all retries, then the transaction will be rejected.
 *
 * The transaction object passed to the updateFunction contains methods for
 * accessing documents and collections. Unlike other datastore access, data
 * accessed with the transaction will not reflect local changes that have not
 * been committed. For this reason, it is required that all reads are
 * performed before any writes. Transactions must be performed while online.
 */ function __PRIVATE_firestoreClientTransaction(e, t, n) {
    const r = new __PRIVATE_Deferred;
    return e.asyncQueue.enqueueAndForget((async () => {
        const i = await __PRIVATE_getDatastore(e);
        new __PRIVATE_TransactionRunner(e.asyncQueue, i, n, t, r).Nc();
    })), r.promise;
}

function __PRIVATE_firestoreClientLoadBundle(e, t, n, r) {
    const i = function __PRIVATE_createBundleReader(e, t) {
        let n;
        n = "string" == typeof e ? __PRIVATE_newTextEncoder().encode(e) : e;
        return function __PRIVATE_newBundleReader(e, t) {
            return new __PRIVATE_BundleReaderImpl(e, t);
        }(function __PRIVATE_toByteStreamReader(e, t) {
            if (e instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e, t);
            if (e instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e), t);
            if (e instanceof ReadableStream) return e.getReader();
            throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream");
        }
        /**
 * @license
 * Copyright 2018 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ (n), t);
    }(n, __PRIVATE_newSerializer(t));
    e.asyncQueue.enqueueAndForget((async () => {
        __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e), i, r);
    }));
}

function __PRIVATE_firestoreClientGetNamedQuery(e, t) {
    return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreGetNamedQuery(e, t) {
        const n = __PRIVATE_debugCast(e);
        return n.persistence.runTransaction("Get named query", "readonly", (e => n.d_.getNamedQuery(e, t)));
    }(await __PRIVATE_getLocalStore(e), t)));
}

function __PRIVATE_createBundleReaderSync(e, t) {
    return function __PRIVATE_newBundleReaderSync(e, t) {
        return new __PRIVATE_BundleReaderSyncImpl(e, t);
    }(e, t);
}

function __PRIVATE_firestoreClientSetIndexConfiguration(e, t) {
    return e.asyncQueue.enqueue((async () => async function __PRIVATE_localStoreConfigureFieldIndexes(e, t) {
        const n = __PRIVATE_debugCast(e), r = n.indexManager, i = [];
        return n.persistence.runTransaction("Configure indexes", "readwrite", (e => r.getFieldIndexes(e).next((n => function __PRIVATE_diffArrays(e, t, n, r, i) {
            e = [ ...e ], t = [ ...t ], e.sort(n), t.sort(n);
            const s = e.length, _ = t.length;
            let o = 0, a = 0;
            for (;o < _ && a < s; ) {
                const s = n(e[a], t[o]);
                s < 0 ? 
                // The element was removed if the next element in our ordered
                // walkthrough is only in `before`.
                i(e[a++]) : s > 0 ? 
                // The element was added if the next element in our ordered walkthrough
                // is only in `after`.
                r(t[o++]) : (o++, a++);
            }
            for (;o < _; ) r(t[o++]);
            for (;a < s; ) i(e[a++]);
        }(n, t, __PRIVATE_fieldIndexSemanticComparator, (t => {
            i.push(r.addFieldIndex(e, t));
        }), (t => {
            i.push(r.deleteFieldIndex(e, t));
        })))).next((() => PersistencePromise.waitFor(i)))));
    }(await __PRIVATE_getLocalStore(e), t)));
}

function __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e, t) {
    return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e, t) {
        __PRIVATE_debugCast(e).Mo.po = t;
    }(await __PRIVATE_getLocalStore(e), t)));
}

function __PRIVATE_firestoreClientDeleteAllFieldIndexes(e) {
    return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreDeleteAllFieldIndexes(e) {
        const t = __PRIVATE_debugCast(e), n = t.indexManager;
        return t.persistence.runTransaction("Delete All Indexes", "readwrite", (e => n.deleteAllFieldIndexes(e)));
    }(await __PRIVATE_getLocalStore(e))));
}

/**
 * @license
 * Copyright 2025 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class pa {
    constructor(e = {}, t = {}) {
        this.qc = e, this.$c = t, this.Kc = new OptionsUtil({
            indexMode: {
                serverName: "index_mode"
            }
        });
    }
    _readUserData(e) {
        this.proto = this.Kc.getOptionsProto(e, this.qc, this.$c);
    }
}

class ma {
    constructor(e, t) {
        this.pipeline = e, this.options = t;
    }
    _toProto(e) {
        return {
            pipeline: this.pipeline._toProto(e),
            options: this.options.proto
        };
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ const mr = "AsyncQueue";

class __PRIVATE_AsyncQueueImpl {
    constructor(e = Promise.resolve()) {
        // A list of retryable operations. Retryable operations are run in order and
        // retried with backoff.
        this.Wc = [], 
        // Is this AsyncQueue being shut down? Once it is set to true, it will not
        // be changed again.
        this.Qc = false, 
        // Operations scheduled to be queued in the future. Operations are
        // automatically removed after they are run or canceled.
        this.Gc = [], 
        // visible for testing
        this.zc = null, 
        // Flag set while there's an outstanding AsyncQueue operation, used for
        // assertion sanity-checks.
        this.jc = false, 
        // Enabled during shutdown on Safari to prevent future access to IndexedDB.
        this.Hc = false, 
        // List of TimerIds to fast-forward delays for.
        this.Jc = [], 
        // Backoff timer used to schedule retries for retryable operations
        this.jt = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), 
        // Visibility handler that triggers an immediate retry of all retryable
        // operations. Meant to speed up recovery when we regain file system access
        // after page comes into foreground.
        this.Yc = () => {
            const e = getDocument();
            e && __PRIVATE_logDebug(mr, "Visibility state changed to " + e.visibilityState), 
            this.jt.qt();
        }, this.Zc = e;
        const t = getDocument();
        t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.Yc);
    }
    get isShuttingDown() {
        return this.Qc;
    }
    /**
     * Adds a new operation to the queue without waiting for it to complete (i.e.
     * we ignore the Promise result).
     */    enqueueAndForget(e) {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this.enqueue(e);
    }
    enqueueAndForgetEvenWhileRestricted(e) {
        this.Xc(), 
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this.el(e);
    }
    enterRestrictedMode(e) {
        if (!this.Qc) {
            this.Qc = true, this.Hc = e || false;
            const t = getDocument();
            t && "function" == typeof t.removeEventListener && t.removeEventListener("visibilitychange", this.Yc);
        }
    }
    enqueue(e) {
        if (this.Xc(), this.Qc) 
        // Return a Promise which never resolves.
        return new Promise((() => {}));
        // Create a deferred Promise that we can return to the callee. This
        // allows us to return a "hanging Promise" only to the callee and still
        // advance the queue even when the operation is not run.
                const t = new __PRIVATE_Deferred;
        return this.el((() => this.Qc && this.Hc ? Promise.resolve() : (e().then(t.resolve, t.reject), 
        t.promise))).then((() => t.promise));
    }
    enqueueRetryable(e) {
        this.enqueueAndForget((() => (this.Wc.push(e), this.tl())));
    }
    /**
     * Runs the next operation from the retryable queue. If the operation fails,
     * reschedules with backoff.
     */    async tl() {
        if (0 !== this.Wc.length) {
            try {
                await this.Wc[0](), this.Wc.shift(), this.jt.reset();
            } catch (e) {
                if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e;
 // Failure will be handled by AsyncQueue
                                __PRIVATE_logDebug(mr, "Operation failed with retryable error: " + e);
            }
            this.Wc.length > 0 && 
            // If there are additional operations, we re-schedule `retryNextOp()`.
            // This is necessary to run retryable operations that failed during
            // their initial attempt since we don't know whether they are already
            // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`
            // needs to  be re-run, we will run `op1`, `op1`, `op2` using the
            // already enqueued calls to `retryNextOp()`. `op3()` will then run in the
            // call scheduled here.
            // Since `backoffAndRun()` cancels an existing backoff and schedules a
            // new backoff on every call, there is only ever a single additional
            // operation in the queue.
            this.jt.Ut((() => this.tl()));
        }
    }
    el(e) {
        const t = this.Zc.then((() => (this.jc = true, e().catch((e => {
            this.zc = e, this.jc = false;
            // Re-throw the error so that this.tail becomes a rejected Promise and
            // all further attempts to chain (via .then) will just short-circuit
            // and return the rejected Promise.
            throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(e)), 
            e;
        })).then((e => (this.jc = false, e))))));
        return this.Zc = t, t;
    }
    enqueueAfterDelay(e, t, n) {
        this.Xc(), 
        // Fast-forward delays for timerIds that have been overridden.
        this.Jc.indexOf(e) > -1 && (t = 0);
        const r = DelayedOperation.createAndSchedule(this, e, t, n, (e => this.nl(e)));
        return this.Gc.push(r), r;
    }
    Xc() {
        this.zc && l(47125, {
            rl: __PRIVATE_getMessageOrStack(this.zc)
        });
    }
    verifyOperationInProgress() {}
    /**
     * Waits until all currently queued tasks are finished executing. Delayed
     * operations are not run.
     */    async il() {
        // Operations in the queue prior to draining may have enqueued additional
        // operations. Keep draining the queue until the tail is no longer advanced,
        // which indicates that no more new operations were enqueued and that all
        // operations were executed.
        let e;
        do {
            e = this.Zc, await e;
        } while (e !== this.Zc);
    }
    /**
     * For Tests: Determine if a delayed operation with a particular TimerId
     * exists.
     */    sl(e) {
        for (const t of this.Gc) if (t.timerId === e) return true;
        return false;
    }
    /**
     * For Tests: Runs some or all delayed operations early.
     *
     * @param lastTimerId - Delayed operations up to and including this TimerId
     * will be drained. Pass TimerId.All to run all delayed operations.
     * @returns a Promise that resolves once all operations have been run.
     */    _l(e) {
        // Note that draining may generate more delayed ops, so we do that first.
        return this.il().then((() => {
            // Run ops in the same order they'd run if they ran naturally.
            /* eslint-disable-next-line @typescript-eslint/no-floating-promises */
            this.Gc.sort(((e, t) => e.targetTimeMs - t.targetTimeMs));
            for (const t of this.Gc) if (t.skipDelay(), "all" /* TimerId.All */ !== e && t.timerId === e) break;
            return this.il();
        }));
    }
    /**
     * For Tests: Skip all subsequent delays for a timer id.
     */    ol(e) {
        this.Jc.push(e);
    }
    /** Called once a DelayedOperation is run or canceled. */    nl(e) {
        // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
        const t = this.Gc.indexOf(e);
        /* eslint-disable-next-line @typescript-eslint/no-floating-promises */        this.Gc.splice(t, 1);
    }
}

/**
 * Chrome includes Error.message in Error.stack. Other browsers do not.
 * This returns expected output of message + stack when available.
 * @param error - Error or FirestoreError
 */ function __PRIVATE_getMessageOrStack(e) {
    let t = e.message || "";
    return e.stack && (t = e.stack.includes(e.message) ? e.stack : e.message + "\n" + e.stack), 
    t;
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Represents the task of loading a Firestore bundle. It provides progress of bundle
 * loading, as well as task completion and error events.
 *
 * The API is compatible with `Promise<LoadBundleTaskProgress>`.
 */ class LoadBundleTask {
    constructor() {
        this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred, 
        this._lastProgress = {
            taskState: "Running",
            totalBytes: 0,
            totalDocuments: 0,
            bytesLoaded: 0,
            documentsLoaded: 0
        };
    }
    /**
     * Registers functions to listen to bundle loading progress events.
     * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur
     *   each time a Firestore document is loaded from the bundle.
     * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the
     *   error, and there should be no more updates after this.
     * @param complete - Called when the loading task is complete.
     */    onProgress(e, t, n) {
        this._progressObserver = {
            next: e,
            error: t,
            complete: n
        };
    }
    /**
     * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.
     *
     * @param onRejected - Called when an error occurs during bundle loading.
     */    catch(e) {
        return this._taskCompletionResolver.promise.catch(e);
    }
    /**
     * Implements the `Promise<LoadBundleTaskProgress>.then` interface.
     *
     * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.
     *   The update will always have its `taskState` set to `"Success"`.
     * @param onRejected - Called when an error occurs during bundle loading.
     */    then(e, t) {
        return this._taskCompletionResolver.promise.then(e, t);
    }
    /**
     * Notifies all observers that bundle loading has completed, with a provided
     * `LoadBundleTaskProgress` object.
     *
     * @private
     */    _completeWith(e) {
        this._updateProgress(e), this._progressObserver.complete && this._progressObserver.complete(), 
        this._taskCompletionResolver.resolve(e);
    }
    /**
     * Notifies all observers that bundle loading has failed, with a provided
     * `Error` as the reason.
     *
     * @private
     */    _failWith(e) {
        this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress), 
        this._progressObserver.error && this._progressObserver.error(e), this._taskCompletionResolver.reject(e);
    }
    /**
     * Notifies a progress update of loading a bundle.
     * @param progress - The new progress.
     *
     * @private
     */    _updateProgress(e) {
        this._lastProgress = e, this._progressObserver.next && this._progressObserver.next(e);
    }
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Constant used to indicate the LRU garbage collection should be disabled.
 * Set this value as the `cacheSizeBytes` on the settings passed to the
 * {@link Firestore} instance.
 */ const pr = -1;

/**
 * The Cloud Firestore service interface.
 *
 * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.
 */ class da extends Dt {
    /** @hideconstructor */
    constructor(e, t, n, r) {
        super(e, t, n, r), 
        /**
         * Whether it's a {@link Firestore} or Firestore Lite instance.
         */
        this.type = "firestore", this._queue = new __PRIVATE_AsyncQueueImpl, this._persistenceKey = r?.name || "[DEFAULT]";
    }
    async _terminate() {
        if (this._firestoreClient) {
            const e = this._firestoreClient.terminate();
            this._queue = new __PRIVATE_AsyncQueueImpl(e), this._firestoreClient = void 0, await e;
        }
    }
}

/**
 * Initializes a new instance of {@link Firestore} with the provided settings.
 * Can only be called before any other function, including
 * {@link (getFirestore:1)}. If the custom settings are empty, this function is
 * equivalent to calling {@link (getFirestore:1)}.
 *
 * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will
 * be associated.
 * @param settings - A settings object to configure the {@link Firestore} instance.
 * @param databaseId - The name of the database.
 * @returns A newly initialized {@link Firestore} instance.
 */ function initializeFirestore(e, t, n) {
    n || (n = $e);
    const r = app._getProvider(e, "firestore");
    if (r.isInitialized(n)) {
        const e = r.getImmediate({
            identifier: n
        }), i = r.getOptions(n);
        if (util.deepEqual(i, t)) return e;
        throw new s(aa.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.");
    }
    if (void 0 !== t.cacheSizeBytes && void 0 !== t.localCache) throw new s(aa.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");
    if (void 0 !== t.cacheSizeBytes && -1 !== t.cacheSizeBytes && t.cacheSizeBytes < bt) throw new s(aa.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576");
    // Workaround to get cookies in Firebase Studio
        return t.host && util.isCloudWorkstation(t.host) && util.pingServer(t.host), r.initialize({
        options: t,
        instanceIdentifier: n
    });
}

function getFirestore(e, t) {
    const n = "object" == typeof e ? e : app.getApp(), r = "string" == typeof e ? e : t || $e, i = app._getProvider(n, "firestore").getImmediate({
        identifier: r
    });
    if (!i._initialized) {
        const e = util.getDefaultEmulatorHostnameAndPort("firestore");
        e && connectFirestoreEmulator(i, ...e);
    }
    return i;
}

/**
 * @internal
 */ function oa(e) {
    if (e._terminated) throw new s(aa.FAILED_PRECONDITION, "The client has already been terminated.");
    return e._firestoreClient || __PRIVATE_configureFirestore(e), e._firestoreClient;
}

function __PRIVATE_configureFirestore(e) {
    const t = e._freezeSettings(), n = __PRIVATE_makeDatabaseInfo(e._databaseId, e._app?.options.appId || "", e._persistenceKey, e._app?.options.apiKey, t);
    e._componentsProvider || t.localCache?._offlineComponentProvider && t.localCache?._onlineComponentProvider && (e._componentsProvider = {
        _offline: t.localCache._offlineComponentProvider,
        _online: t.localCache._onlineComponentProvider
    }), e._firestoreClient = new FirestoreClient(e._authCredentials, e._appCheckCredentials, e._queue, n, e._componentsProvider && function __PRIVATE_buildComponentProvider(e) {
        const t = e?._online.build();
        return {
            _offline: e?._offline.build(t),
            _online: t
        };
    }
    /**
 * Attempts to enable persistent storage, if possible.
 *
 * On failure, `enableIndexedDbPersistence()` will reject the promise or
 * throw an exception. There are several reasons why this can fail, which can be
 * identified by the `code` on the error.
 *
 *   * failed-precondition: The app is already open in another browser tab.
 *   * unimplemented: The browser is incompatible with the offline persistence
 *     implementation.
 *
 * Note that even after a failure, the {@link Firestore} instance will remain
 * usable, however offline persistence will be disabled.
 *
 * Note: `enableIndexedDbPersistence()` must be called before any other functions
 * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or
 * {@link clearIndexedDbPersistence}.
 *
 * Persistence cannot be used in a Node.js environment.
 *
 * @param firestore - The {@link Firestore} instance to enable persistence for.
 * @param persistenceSettings - Optional settings object to configure
 * persistence.
 * @returns A `Promise` that represents successfully enabling persistent storage.
 * @deprecated This function will be removed in a future major release. Instead, set
 * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to
 * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache`
 * is already specified will throw an exception.
 */ (e._componentsProvider));
}

function enableIndexedDbPersistence(e, t) {
    __PRIVATE_logWarn("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
    const n = e._freezeSettings();
    return __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, {
        build: e => new __PRIVATE_IndexedDbOfflineComponentProvider(e, n.cacheSizeBytes, t?.forceOwnership)
    }), Promise.resolve();
}

/**
 * Attempts to enable multi-tab persistent storage, if possible. If enabled
 * across all tabs, all operations share access to local persistence, including
 * shared execution of queries and latency-compensated local document updates
 * across all connected instances.
 *
 * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or
 * throw an exception. There are several reasons why this can fail, which can be
 * identified by the `code` on the error.
 *
 *   * failed-precondition: The app is already open in another browser tab and
 *     multi-tab is not enabled.
 *   * unimplemented: The browser is incompatible with the offline persistence
 *     implementation.
 *
 * Note that even after a failure, the {@link Firestore} instance will remain
 * usable, however offline persistence will be disabled.
 *
 * @param firestore - The {@link Firestore} instance to enable persistence for.
 * @returns A `Promise` that represents successfully enabling persistent
 * storage.
 * @deprecated This function will be removed in a future major release. Instead, set
 * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to
 * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache`
 * is already specified will throw an exception.
 */ async function enableMultiTabIndexedDbPersistence(e) {
    __PRIVATE_logWarn("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.");
    const t = e._freezeSettings();
    __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, {
        build: e => new __PRIVATE_MultiTabOfflineComponentProvider(e, t.cacheSizeBytes)
    });
}

/**
 * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.
 * If the operation fails with a recoverable error (see
 * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected
 * but the client remains usable.
 */ function __PRIVATE_setPersistenceProviders(e, t, n) {
    if ((e = ra(e, da))._firestoreClient || e._terminated) throw new s(aa.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.");
    if (e._componentsProvider || e._getSettings().localCache) throw new s(aa.FAILED_PRECONDITION, "SDK cache is already specified.");
    e._componentsProvider = {
        _online: t,
        _offline: n
    }, __PRIVATE_configureFirestore(e);
}

/**
 * Clears the persistent storage. This includes pending writes and cached
 * documents.
 *
 * Must be called while the {@link Firestore} instance is not started (after the app is
 * terminated or when the app is first initialized). On startup, this function
 * must be called before other functions (other than {@link
 * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}
 * instance is still running, the promise will be rejected with the error code
 * of `failed-precondition`.
 *
 * Note: `clearIndexedDbPersistence()` is primarily intended to help write
 * reliable tests that use Cloud Firestore. It uses an efficient mechanism for
 * dropping existing data but does not attempt to securely overwrite or
 * otherwise make cached data unrecoverable. For applications that are sensitive
 * to the disclosure of cached data in between user sessions, we strongly
 * recommend not enabling persistence at all.
 *
 * @param firestore - The {@link Firestore} instance to clear persistence for.
 * @returns A `Promise` that is resolved when the persistent storage is
 * cleared. Otherwise, the promise is rejected with an error.
 */ function clearIndexedDbPersistence(e) {
    if (e._initialized && !e._terminated) throw new s(aa.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.");
    const t = new __PRIVATE_Deferred;
    return e._queue.enqueueAndForgetEvenWhileRestricted((async () => {
        try {
            await async function __PRIVATE_indexedDbClearPersistence(e) {
                if (!__PRIVATE_SimpleDb.Je()) return Promise.resolve();
                const t = e + cr;
                await __PRIVATE_SimpleDb.delete(t);
            }(__PRIVATE_indexedDbStoragePrefix(e._databaseId, e._persistenceKey)), t.resolve();
        } catch (e) {
            t.reject(e);
        }
    })), t.promise;
}

/**
 * Waits until all currently pending writes for the active user have been
 * acknowledged by the backend.
 *
 * The returned promise resolves immediately if there are no outstanding writes.
 * Otherwise, the promise waits for all previously issued writes (including
 * those written in a previous app session), but it does not wait for writes
 * that were added after the function is called. If you want to wait for
 * additional writes, call `waitForPendingWrites()` again.
 *
 * Any outstanding `waitForPendingWrites()` promises are rejected during user
 * changes.
 *
 * @returns A `Promise` which resolves when all currently pending writes have been
 * acknowledged by the backend.
 */ function waitForPendingWrites(e) {
    return function __PRIVATE_firestoreClientWaitForPendingWrites(e) {
        const t = new __PRIVATE_Deferred;
        return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e), t))), 
        t.promise;
    }(oa(e = ra(e, da)));
}

/**
 * Re-enables use of the network for this {@link Firestore} instance after a prior
 * call to {@link disableNetwork}.
 *
 * @returns A `Promise` that is resolved once the network has been enabled.
 */ function enableNetwork(e) {
    return __PRIVATE_firestoreClientEnableNetwork(oa(e = ra(e, da)));
}

/**
 * Disables network usage for this instance. It can be re-enabled via {@link
 * enableNetwork}. While the network is disabled, any snapshot listeners,
 * `getDoc()` or `getDocs()` calls will return results from cache, and any write
 * operations will be queued until the network is restored.
 *
 * @returns A `Promise` that is resolved once the network has been disabled.
 */ function disableNetwork(e) {
    return __PRIVATE_firestoreClientDisableNetwork(oa(e = ra(e, da)));
}

/**
 * Terminates the provided {@link Firestore} instance.
 *
 * After calling `terminate()` only the `clearIndexedDbPersistence()` function
 * may be used. Any other function will throw a `FirestoreError`.
 *
 * To restart after termination, create a new instance of FirebaseFirestore with
 * {@link (getFirestore:1)}.
 *
 * Termination does not cancel any pending writes, and any promises that are
 * awaiting a response from the server will not be resolved. If you have
 * persistence enabled, the next time you start this instance, it will resume
 * sending these writes to the server.
 *
 * Note: Under normal circumstances, calling `terminate()` is not required. This
 * function is useful only when you want to force this instance to release all
 * of its resources or in combination with `clearIndexedDbPersistence()` to
 * ensure that all local state is destroyed between test runs.
 *
 * @returns A `Promise` that is resolved when the instance has been successfully
 * terminated.
 */ function terminate(e) {
    return app._removeServiceInstance(e.app, "firestore", e._databaseId.database), e._delete();
}

/**
 * Loads a Firestore bundle into the local cache.
 *
 * @param firestore - The {@link Firestore} instance to load bundles for.
 * @param bundleData - An object representing the bundle to be loaded. Valid
 * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.
 *
 * @returns A `LoadBundleTask` object, which notifies callers with progress
 * updates, and completion or error events. It can be used as a
 * `Promise<LoadBundleTaskProgress>`.
 */ function loadBundle(e, t) {
    const n = oa(e = ra(e, da)), r = new LoadBundleTask;
    return __PRIVATE_firestoreClientLoadBundle(n, e._databaseId, t, r), r;
}

/**
 * Reads a Firestore {@link Query} from local cache, identified by the given
 * name.
 *
 * The named queries are packaged  into bundles on the server side (along
 * with resulting documents), and loaded to local cache using `loadBundle`. Once
 * in local cache, use this method to extract a {@link Query} by name.
 *
 * @param firestore - The {@link Firestore} instance to read the query from.
 * @param name - The name of the query.
 * @returns A `Promise` that is resolved with the Query or `null`.
 */ function namedQuery(e, t) {
    return __PRIVATE_firestoreClientGetNamedQuery(oa(e = ra(e, da)), t).then((t => t ? new Query(e, null, t.query) : null));
}

/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Converts Firestore's internal types to the JavaScript types that we expose
 * to the user.
 *
 * @internal
 */ class AbstractUserDataWriter {
    convertValue(e, t = "none") {
        switch (__PRIVATE_typeOrder(e)) {
          case 0 /* TypeOrder.NullValue */ :
            return null;

          case 1 /* TypeOrder.BooleanValue */ :
            return e.booleanValue;

          case 2 /* TypeOrder.NumberValue */ :
            return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue);

          case 3 /* TypeOrder.TimestampValue */ :
            return this.convertTimestamp(e.timestampValue);

          case 4 /* TypeOrder.ServerTimestampValue */ :
            return this.convertServerTimestamp(e, t);

          case 5 /* TypeOrder.StringValue */ :
            return e.stringValue;

          case 6 /* TypeOrder.BlobValue */ :
            return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));

          case 7 /* TypeOrder.RefValue */ :
            return this.convertReference(e.referenceValue);

          case 8 /* TypeOrder.GeoPointValue */ :
            return this.convertGeoPoint(e.geoPointValue);

          case 9 /* TypeOrder.ArrayValue */ :
            return this.convertArray(e.arrayValue, t);

          case 11 /* TypeOrder.ObjectValue */ :
            return this.convertObject(e.mapValue, t);

          case 10 /* TypeOrder.VectorValue */ :
            return this.convertVectorValue(e.mapValue);

          default:
            throw l(62114, {
                value: e
            });
        }
    }
    convertObject(e, t) {
        return this.convertObjectMap(e.fields, t);
    }
    /**
     * @internal
     */    convertObjectMap(e, t = "none") {
        const n = {};
        return forEach(e, ((e, r) => {
            n[e] = this.convertValue(r, t);
        })), n;
    }
    /**
     * @internal
     */    convertVectorValue(e) {
        const t = e.fields?.[je].arrayValue?.values?.map((e => __PRIVATE_normalizeNumber(e.doubleValue)));
        return new n(t);
    }
    convertGeoPoint(e) {
        return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(e.longitude));
    }
    convertArray(e, t) {
        return (e.values || []).map((e => this.convertValue(e, t)));
    }
    convertServerTimestamp(e, t) {
        switch (t) {
          case "previous":
            const n = __PRIVATE_getPreviousValue(e);
            return null == n ? null : this.convertValue(n, t);

          case "estimate":
            return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));

          default:
            return null;
        }
    }
    convertTimestamp(e) {
        const t = __PRIVATE_normalizeTimestamp(e);
        return new Timestamp(t.seconds, t.nanos);
    }
    convertDocumentKey(e, t) {
        const n = ResourcePath.fromString(e);
        __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n), 9688, {
            name: e
        });
        const r = new DatabaseId(n.get(1), n.get(3)), i = new DocumentKey(n.popFirst(5));
        return r.isEqual(t) || 
        // TODO(b/64130202): Somehow support foreign references.
        __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.`), 
        i;
    }
}

/**
 * @license
 * Copyright 2024 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */ class ua extends AbstractUserDataWriter {
    constructor(e) {
        super(), this.firestore = e;
    }
    convertBytes(e) {
        return new Bytes(e);
    }
    convertReference(e) {
        const t = this.convertDocumentKey(e, this.firestore._databaseId);
        return new X(this.firestore, /* converter= */ null, t);
    }
}

/**
 * @license
 * Copyright 2017 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * @internal
 * @private
 *
 * This function is for internal use only.
 *
 * Returns the `QueryTarget` representation of the given query. Returns `null`
 * if the Firestore client associated with the given query has not been
 * initialized or has been terminated.
 *
 * @param query - The Query to convert to proto representation.
 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function _internalQueryToProtoQueryTarget(e) {
    const t = oa(ra(e.firestore, da)), n = t._onlineComponents?.datastore.serializer;
    return void 0 === n ? null : __PRIVATE_toQueryTarget(n, __PRIVATE_queryToTarget(e._query)).be;
}

/**
 * @internal
 * @private
 *
 * This function is for internal use only.
 *
 * Returns `RunAggregationQueryRequest` which contains the proto representation
 * of the given aggregation query request. Returns null if the Firestore client
 * associated with the given query has not been initialized or has been
 * terminated.
 *
 * @param query - The Query to convert to proto representation.
 * @param aggregateSpec - The set of aggregations and their aliases.
 */ function _internalAggregationQueryToProtoRunAggregationQueryRequest(e, t) {
    const n = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath))), r = oa(ra(e.firestore, da)), i = r._onlineComponents?.datastore.serializer;
    return void 0 === i ? null : __PRIVATE_toRunAggregationQueryRequest(i, __PRIVATE_queryToAggregateTarget(e._query), n, 
    /* skipAliasing= */ true).request;
}

/**
 * @internal
 * @private
 *
 * This function is for internal use only.
 *
 * Returns the `ExecutePipelineRequest` representation of the given query.
 * Returns `null` if the Firestore client associated with the given query has
 * not been initialized or has been terminated.
 *
 * @param pipeline - The Pipeline to convert to proto representation.
 */ function _internalPipelineToExecutePipelineRequestProto(e) {
    if (!e._db) throw new s(aa.FAILED_PRECONDITION, "This pipeline was created without a database and cannot be serialized for execution.");
    const t = ra(e._db, da), n = la(t).createContext(3 /* UserDataSource.Argument */ , "_internalPipelineToExecutePipelineRequestProto");
    e._readUserData(n);
    const r = 
    /**
 * Returns an initialized and started Datastore for the given Firestore
 * instance. Callers must invoke removeComponents() when the Firestore
 * instance is terminated.
 */
    function __PRIVATE_getDatastore$1(e) {
        if (e._terminated) throw new s(aa.FAILED_PRECONDITION, "The client has already been terminated.");
        if (!dt.has(e)) {
            __PRIVATE_logDebug(Vt, "Initializing Datastore");
            const t = __PRIVATE_newConnection(__PRIVATE_makeDatabaseInfo(e._databaseId, e.app.options.appId || "", e._persistenceKey, e.app.options.apiKey, e._freezeSettings())), n = __PRIVATE_newSerializer(e._databaseId), r = __PRIVATE_newDatastore(e._authCredentials, e._appCheckCredentials, t, n);
            dt.set(e, r);
        }
        return dt.get(e);
    }(t), i = r.serializer;
    if (void 0 === i) return null;
    const _ = new ma(e, new pa);
    return {
        database: __PRIVATE_getEncodedDatabaseId(i),
        structuredPipeline: _._toProto(i)
    };
}

exports.$ = $;
exports.A = A;
exports.AbstractUserDataWriter = AbstractUserDataWriter;
exports.AliasedAggregate = AliasedAggregate;
exports.B = B;
exports.BooleanExpression = BooleanExpression;
exports.Bound = Bound;
exports.ByteString = ByteString;
exports.Bytes = Bytes;
exports.C = C;
exports.CompositeFilter = CompositeFilter;
exports.D = D;
exports.DatabaseId = DatabaseId;
exports.DocumentKey = DocumentKey;
exports.DocumentSet = DocumentSet;
exports.E = E;
exports.F = F;
exports.FieldFilter = FieldFilter;
exports.FieldIndex = FieldIndex;
exports.FieldPath = FieldPath;
exports.FieldValue = FieldValue;
exports.G = G;
exports.GeoPoint = GeoPoint;
exports.H = H;
exports.I = I;
exports.IndexSegment = IndexSegment;
exports.IndexState = IndexState;
exports.J = J;
exports.K = K;
exports.L = L;
exports.LoadBundleTask = LoadBundleTask;
exports.M = M;
exports.N = N;
exports.O = O;
exports.ObjectValue = ObjectValue;
exports.Oe = Oe;
exports.OnlineComponentProvider = OnlineComponentProvider;
exports.OrderBy = OrderBy;
exports.Ordering = Ordering;
exports.P = P;
exports.Precondition = Precondition;
exports.Q = Q;
exports.Query = Query;
exports.ResourcePath = ResourcePath;
exports.S = S;
exports.T = T;
exports.Timestamp = Timestamp;
exports.U = U;
exports.V = V;
exports.ViewSnapshot = ViewSnapshot;
exports.W = W;
exports.X = X;
exports.Y = Y;
exports.Z = Z;
exports._ = _;
exports.__PRIVATE_AggregateImpl = __PRIVATE_AggregateImpl;
exports.__PRIVATE_AutoId = __PRIVATE_AutoId;
exports.__PRIVATE_BundleLoader = __PRIVATE_BundleLoader;
exports.__PRIVATE_DeleteMutation = __PRIVATE_DeleteMutation;
exports.__PRIVATE_EmptyAppCheckTokenProvider = __PRIVATE_EmptyAppCheckTokenProvider;
exports.__PRIVATE_EmptyAuthCredentialsProvider = __PRIVATE_EmptyAuthCredentialsProvider;
exports.__PRIVATE_FirebaseAppCheckTokenProvider = __PRIVATE_FirebaseAppCheckTokenProvider;
exports.__PRIVATE_FirebaseAuthCredentialsProvider = __PRIVATE_FirebaseAuthCredentialsProvider;
exports.__PRIVATE_IndexedDbOfflineComponentProvider = __PRIVATE_IndexedDbOfflineComponentProvider;
exports.__PRIVATE_LruGcMemoryOfflineComponentProvider = __PRIVATE_LruGcMemoryOfflineComponentProvider;
exports.__PRIVATE_MemoryOfflineComponentProvider = __PRIVATE_MemoryOfflineComponentProvider;
exports.__PRIVATE_MultiTabOfflineComponentProvider = __PRIVATE_MultiTabOfflineComponentProvider;
exports.__PRIVATE_createBundleReaderSync = __PRIVATE_createBundleReaderSync;
exports.__PRIVATE_databaseIdFromApp = __PRIVATE_databaseIdFromApp;
exports.__PRIVATE_debugAssert = __PRIVATE_debugAssert;
exports.__PRIVATE_documentKeySet = __PRIVATE_documentKeySet;
exports.__PRIVATE_fieldPathFromDotSeparatedString = __PRIVATE_fieldPathFromDotSeparatedString;
exports.__PRIVATE_firestoreClientAddSnapshotsInSyncListener = __PRIVATE_firestoreClientAddSnapshotsInSyncListener;
exports.__PRIVATE_firestoreClientDeleteAllFieldIndexes = __PRIVATE_firestoreClientDeleteAllFieldIndexes;
exports.__PRIVATE_firestoreClientGetDocumentFromLocalCache = __PRIVATE_firestoreClientGetDocumentFromLocalCache;
exports.__PRIVATE_firestoreClientGetDocumentViaSnapshotListener = __PRIVATE_firestoreClientGetDocumentViaSnapshotListener;
exports.__PRIVATE_firestoreClientGetDocumentsFromLocalCache = __PRIVATE_firestoreClientGetDocumentsFromLocalCache;
exports.__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener = __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener;
exports.__PRIVATE_firestoreClientListen = __PRIVATE_firestoreClientListen;
exports.__PRIVATE_firestoreClientRunAggregateQuery = __PRIVATE_firestoreClientRunAggregateQuery;
exports.__PRIVATE_firestoreClientSetIndexConfiguration = __PRIVATE_firestoreClientSetIndexConfiguration;
exports.__PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled = __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled;
exports.__PRIVATE_firestoreClientTransaction = __PRIVATE_firestoreClientTransaction;
exports.__PRIVATE_firestoreClientWrite = __PRIVATE_firestoreClientWrite;
exports.__PRIVATE_fromBundledQuery = __PRIVATE_fromBundledQuery;
exports.__PRIVATE_isBase64Available = __PRIVATE_isBase64Available;
exports.__PRIVATE_isCollectionGroupQuery = __PRIVATE_isCollectionGroupQuery;
exports.__PRIVATE_isNumber$1 = __PRIVATE_isNumber$1;
exports.__PRIVATE_isPipeline = __PRIVATE_isPipeline;
exports.__PRIVATE_isServerTimestamp = __PRIVATE_isServerTimestamp;
exports.__PRIVATE_isString$1 = __PRIVATE_isString$1;
exports.__PRIVATE_logDebug = __PRIVATE_logDebug;
exports.__PRIVATE_logWarn = __PRIVATE_logWarn;
exports.__PRIVATE_mapToArray = __PRIVATE_mapToArray;
exports.__PRIVATE_newPipelineComparator = __PRIVATE_newPipelineComparator;
exports.__PRIVATE_newQueryComparator = __PRIVATE_newQueryComparator;
exports.__PRIVATE_newQueryForPath = __PRIVATE_newQueryForPath;
exports.__PRIVATE_newSerializer = __PRIVATE_newSerializer;
exports.__PRIVATE_parseQueryValue = __PRIVATE_parseQueryValue;
exports.__PRIVATE_parseSetData = __PRIVATE_parseSetData;
exports.__PRIVATE_parseUpdateData = __PRIVATE_parseUpdateData;
exports.__PRIVATE_parseUpdateVarargs = __PRIVATE_parseUpdateVarargs;
exports.__PRIVATE_queryNormalizedOrderBy = __PRIVATE_queryNormalizedOrderBy;
exports.__PRIVATE_queryWithAddedFilter = __PRIVATE_queryWithAddedFilter;
exports.__PRIVATE_queryWithAddedOrderBy = __PRIVATE_queryWithAddedOrderBy;
exports.__PRIVATE_queryWithEndAt = __PRIVATE_queryWithEndAt;
exports.__PRIVATE_queryWithLimit = __PRIVATE_queryWithLimit;
exports.__PRIVATE_queryWithStartAt = __PRIVATE_queryWithStartAt;
exports.__PRIVATE_refValue = __PRIVATE_refValue;
exports.__PRIVATE_setSDKVersion = __PRIVATE_setSDKVersion;
exports.__PRIVATE_setTestingHooksSpi = __PRIVATE_setTestingHooksSpi;
exports.__PRIVATE_validateIsNotUsedTogether = __PRIVATE_validateIsNotUsedTogether;
exports.__PRIVATE_validateJSON = __PRIVATE_validateJSON;
exports.__PRIVATE_validatePositiveNumber = __PRIVATE_validatePositiveNumber;
exports.__PRIVATE_valueDescription = __PRIVATE_valueDescription;
exports._internalAggregationQueryToProtoRunAggregationQueryRequest = _internalAggregationQueryToProtoRunAggregationQueryRequest;
exports._internalPipelineToExecutePipelineRequestProto = _internalPipelineToExecutePipelineRequestProto;
exports._internalQueryToProtoQueryTarget = _internalQueryToProtoQueryTarget;
exports.aa = aa;
exports.abs = abs;
exports.add = add;
exports.and = and;
exports.arrayAgg = arrayAgg;
exports.arrayAggDistinct = arrayAggDistinct;
exports.arrayConcat = arrayConcat;
exports.arrayContains = arrayContains;
exports.arrayContainsAll = arrayContainsAll;
exports.arrayContainsAny = arrayContainsAny;
exports.arrayFilter = arrayFilter;
exports.arrayFirst = arrayFirst;
exports.arrayFirstN = arrayFirstN;
exports.arrayGet = arrayGet;
exports.arrayIndexOf = arrayIndexOf;
exports.arrayIndexOfAll = arrayIndexOfAll;
exports.arrayLast = arrayLast;
exports.arrayLastIndexOf = arrayLastIndexOf;
exports.arrayLastN = arrayLastN;
exports.arrayLength = arrayLength;
exports.arrayMaximum = arrayMaximum;
exports.arrayMaximumN = arrayMaximumN;
exports.arrayMinimum = arrayMinimum;
exports.arrayMinimumN = arrayMinimumN;
exports.arrayRemove = arrayRemove;
exports.arraySlice = arraySlice;
exports.arraySum = arraySum;
exports.arrayTransform = arrayTransform;
exports.arrayTransformWithIndex = arrayTransformWithIndex;
exports.arrayUnion = arrayUnion;
exports.ascending = ascending;
exports.average = average;
exports.b = b;
exports.byteLength = byteLength;
exports.c = c;
exports.ceil = ceil;
exports.charLength = charLength;
exports.clearIndexedDbPersistence = clearIndexedDbPersistence;
exports.coalesce = coalesce;
exports.collection = collection;
exports.collectionGroup = collectionGroup;
exports.collectionId = collectionId;
exports.concat = concat;
exports.conditional = conditional;
exports.connectFirestoreEmulator = connectFirestoreEmulator;
exports.cosineDistance = cosineDistance;
exports.count = count;
exports.countAll = countAll;
exports.countDistinct = countDistinct;
exports.countIf = countIf;
exports.currentDocument = currentDocument;
exports.currentTimestamp = currentTimestamp;
exports.d = d;
exports.da = da;
exports.deleteField = deleteField;
exports.descending = descending;
exports.disableNetwork = disableNetwork;
exports.divide = divide;
exports.doc = doc;
exports.documentId = documentId;
exports.documentId$1 = documentId$1;
exports.dotProduct = dotProduct;
exports.e = e;
exports.ea = ea;
exports.enableIndexedDbPersistence = enableIndexedDbPersistence;
exports.enableMultiTabIndexedDbPersistence = enableMultiTabIndexedDbPersistence;
exports.enableNetwork = enableNetwork;
exports.endsWith = endsWith;
exports.equal = equal;
exports.equalAny = equalAny;
exports.euclideanDistance = euclideanDistance;
exports.exists = exists;
exports.exp = exp;
exports.f = f;
exports.first = first;
exports.floor = floor;
exports.fromDocument = fromDocument;
exports.g = g;
exports.geoDistance = geoDistance;
exports.getFirestore = getFirestore;
exports.greaterThan = greaterThan;
exports.greaterThanOrEqual = greaterThanOrEqual;
exports.h = h;
exports.ha = ha;
exports.i = i;
exports.ia = ia;
exports.ifAbsent = ifAbsent;
exports.ifError = ifError;
exports.ifNull = ifNull;
exports.increment = increment;
exports.initializeFirestore = initializeFirestore;
exports.isAbsent = isAbsent;
exports.isError = isError;
exports.isType = isType;
exports.j = j;
exports.join = join;
exports.k = k;
exports.l = l;
exports.la = la;
exports.last = last;
exports.length = length;
exports.lessThan = lessThan;
exports.lessThanOrEqual = lessThanOrEqual;
exports.like = like;
exports.ln = ln;
exports.loadBundle = loadBundle;
exports.log = log;
exports.log10 = log10;
exports.logicalMaximum = logicalMaximum;
exports.logicalMinimum = logicalMinimum;
exports.ltrim = ltrim;
exports.m = m;
exports.ma = ma;
exports.mapEntries = mapEntries;
exports.mapGet = mapGet;
exports.mapKeys = mapKeys;
exports.mapMerge = mapMerge;
exports.mapRemove = mapRemove;
exports.mapSet = mapSet;
exports.mapValues = mapValues;
exports.maximum = maximum;
exports.maximum$1 = maximum$1;
exports.minimum = minimum;
exports.minimum$1 = minimum$1;
exports.mod = mod;
exports.multiply = multiply;
exports.n = n;
exports.na = na;
exports.namedQuery = namedQuery;
exports.nor = nor;
exports.not = not;
exports.notEqual = notEqual;
exports.notEqualAny = notEqualAny;
exports.o = o;
exports.oa = oa;
exports.or = or;
exports.p = p;
exports.pa = pa;
exports.parent = parent;
exports.pow = pow;
exports.pr = pr;
exports.property = property;
exports.q = q;
exports.queryEqual = queryEqual;
exports.r = r;
exports.ra = ra;
exports.rand = rand;
exports.regexContains = regexContains;
exports.regexFind = regexFind;
exports.regexFindAll = regexFindAll;
exports.regexMatch = regexMatch;
exports.reverse = reverse;
exports.round = round;
exports.rtrim = rtrim;
exports.s = s;
exports.sa = sa;
exports.score = score;
exports.serverTimestamp = serverTimestamp;
exports.setLogLevel = setLogLevel;
exports.split = split;
exports.sqrt = sqrt;
exports.startsWith = startsWith;
exports.stringConcat = stringConcat;
exports.stringContains = stringContains;
exports.stringIndexOf = stringIndexOf;
exports.stringRepeat = stringRepeat;
exports.stringReplaceAll = stringReplaceAll;
exports.stringReplaceOne = stringReplaceOne;
exports.stringReverse = stringReverse;
exports.substring = substring;
exports.subtract = subtract;
exports.sum = sum;
exports.switchOn = switchOn;
exports.t = t;
exports.ta = ta;
exports.terminate = terminate;
exports.timestampAdd = timestampAdd;
exports.timestampDiff = timestampDiff;
exports.timestampExtract = timestampExtract;
exports.timestampSubtract = timestampSubtract;
exports.timestampToUnixMicros = timestampToUnixMicros;
exports.timestampToUnixMillis = timestampToUnixMillis;
exports.timestampToUnixSeconds = timestampToUnixSeconds;
exports.timestampTruncate = timestampTruncate;
exports.toLower = toLower;
exports.toUpper = toUpper;
exports.trim = trim;
exports.trunc = trunc;
exports.type = type;
exports.u = u;
exports.ua = ua;
exports.unixMicrosToTimestamp = unixMicrosToTimestamp;
exports.unixMillisToTimestamp = unixMillisToTimestamp;
exports.unixSecondsToTimestamp = unixSecondsToTimestamp;
exports.v = v;
exports.variable = variable;
exports.vectorLength = vectorLength;
exports.w = w;
exports.waitForPendingWrites = waitForPendingWrites;
exports.x = x;
exports.xor = xor;
exports.y = y;
exports.z = z;
//# sourceMappingURL=common-D8YuAUTW.cjs.js.map
