import t from "@firebase/app";

import { Logger as e, LogLevel as s } from "@firebase/logger";

import { getUA as i, isMobileCordova as n, isReactNative as r, isElectron as h, isIE as o, isUWP as a, isBrowserExtension as u } from "@firebase/util";

import { Component as c } from "@firebase/component";

import { XhrIo as _, EventType as l, ErrorCode as d, createWebChannelTransport as f, WebChannel as T } from "@firebase/webchannel-wrapper";

/**
 * @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. */ const E = t.SDK_VERSION;

/**
 * @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 I {
    constructor(t) {
        this.uid = t;
    }
    t() {
        return null != this.uid;
    }
    /**
     * Returns a key representing this user, suitable for inclusion in a
     * dictionary.
     */    s() {
        return this.t() ? "uid:" + this.uid : "anonymous-user";
    }
    isEqual(t) {
        return t.uid === this.uid;
    }
}

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

/**
 * @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 w = {
    // 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 can not 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 class used for Firestore-generated errors. Ideally we should be
 * using FirebaseError, but integrating with it is overly arduous at the moment,
 * so we define our own compatible error class (with a `name` of 'FirebaseError'
 * and compatible `code` and `message` fields.)
 */ class R extends Error {
    constructor(t, e) {
        super(e), this.code = t, this.message = e, this.name = "FirebaseError", 
        // 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.
 */ class A {
    constructor(t, e) {
        this.user = e, this.type = "OAuth", this.o = {}, 
        // Set the headers using Object Literal notation to avoid minification
        this.o.Authorization = `Bearer ${t}`;
    }
}

/** A CredentialsProvider that always yields an empty token. */ class m {
    constructor() {
        /**
         * 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.u = null;
    }
    getToken() {
        return Promise.resolve(null);
    }
    _() {}
    l(t) {
        this.u = t, 
        // Fire with initial user.
        t(I.UNAUTHENTICATED);
    }
    T() {
        this.u = null;
    }
}

class P {
    constructor(t) {
        /**
         * The auth token listener registered with FirebaseApp, retained here so we
         * can unregister it.
         */
        this.I = null, 
        /** Tracks the current User. */
        this.currentUser = I.UNAUTHENTICATED, this.R = !1, 
        /**
         * Counter used to detect if the token changed while a getToken request was
         * outstanding.
         */
        this.A = 0, 
        /** The listener registered with setChangeListener(). */
        this.u = null, this.forceRefresh = !1, this.I = () => {
            this.A++, this.currentUser = this.m(), this.R = !0, this.u && this.u(this.currentUser);
        }, this.A = 0, this.auth = t.getImmediate({
            optional: !0
        }), this.auth ? this.auth.addAuthTokenListener(this.I) : (
        // if auth is not available, invoke tokenListener once with null token
        this.I(null), t.get().then(t => {
            this.auth = t, this.I && 
            // tokenListener can be removed by removeChangeListener()
            this.auth.addAuthTokenListener(this.I);
        }, () => {}));
    }
    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 t = this.A, e = this.forceRefresh;
        return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then(e => {
            // 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).
            if (this.A !== t) throw new R(w.ABORTED, "getToken aborted due to token change.");
            return e ? (ve("string" == typeof e.accessToken), new A(e.accessToken, this.currentUser)) : null;
        }) : Promise.resolve(null);
    }
    _() {
        this.forceRefresh = !0;
    }
    l(t) {
        this.u = t, 
        // Fire the initial event
        this.R && t(this.currentUser);
    }
    T() {
        this.auth && this.auth.removeAuthTokenListener(this.I), this.I = null, this.u = null;
    }
    // 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.
    m() {
        const t = this.auth && this.auth.getUid();
        return ve(null === t || "string" == typeof t), new I(t);
    }
}

/*
 * 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 V {
    constructor(t, e) {
        this.P = t, this.V = e, this.type = "FirstParty", this.user = I.h;
    }
    get o() {
        const t = {
            "X-Goog-AuthUser": this.V
        }, e = this.P.auth.g([]);
        return e && (t.Authorization = e), t;
    }
}

/*
 * 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 g {
    constructor(t, e) {
        this.P = t, this.V = e;
    }
    getToken() {
        return Promise.resolve(new V(this.P, this.V));
    }
    l(t) {
        // Fire with initial uid.
        t(I.h);
    }
    T() {}
    _() {}
}

/**
 * Builds a CredentialsProvider depending on the type of
 * the credentials passed in.
 */ class p {
    constructor(t, e) {
        if (this.seconds = t, this.nanoseconds = e, e < 0) throw new R(w.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
        if (e >= 1e9) throw new R(w.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + e);
        if (t < -62135596800) throw new R(w.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
        // This will break in the year 10,000.
                if (t >= 253402300800) throw new R(w.INVALID_ARGUMENT, "Timestamp seconds out of range: " + t);
    }
    static now() {
        return p.fromMillis(Date.now());
    }
    static fromDate(t) {
        return p.fromMillis(t.getTime());
    }
    static fromMillis(t) {
        const e = Math.floor(t / 1e3);
        return new p(e, 1e6 * (t - 1e3 * e));
    }
    toDate() {
        return new Date(this.toMillis());
    }
    toMillis() {
        return 1e3 * this.seconds + this.nanoseconds / 1e6;
    }
    p(t) {
        return this.seconds === t.seconds ? Ce(this.nanoseconds, t.nanoseconds) : Ce(this.seconds, t.seconds);
    }
    isEqual(t) {
        return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
    }
    toString() {
        return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
    }
    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 lexiographical
        // 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 lexiographical ordering.
        const t = this.seconds - -62135596800;
        // Note: Up to 12 decimal digits are required to represent all valid 'seconds' values.
                return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "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.
 */
/**
 * A version of a document in Firestore. This corresponds to the version
 * timestamp, such as update_time or read_time.
 */ class y {
    constructor(t) {
        this.timestamp = t;
    }
    static v(t) {
        return new y(t);
    }
    static min() {
        return new y(new p(0, 0));
    }
    S(t) {
        return this.timestamp.p(t.timestamp);
    }
    isEqual(t) {
        return this.timestamp.isEqual(t.timestamp);
    }
    /** Returns a number representation of the version for use in spec tests. */    D() {
        // Convert to microseconds.
        return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
    }
    toString() {
        return "SnapshotVersion(" + this.timestamp.toString() + ")";
    }
    C() {
        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.
 */
/**
 * Path represents an ordered sequence of string segments.
 */
class b {
    constructor(t, e, s) {
        void 0 === e ? e = 0 : e > t.length && be(), void 0 === s ? s = t.length - e : s > t.length - e && be(), 
        this.segments = t, this.offset = e, this.F = s;
    }
    get length() {
        return this.F;
    }
    isEqual(t) {
        return 0 === b.N(this, t);
    }
    child(t) {
        const e = this.segments.slice(this.offset, this.limit());
        return t instanceof b ? t.forEach(t => {
            e.push(t);
        }) : e.push(t), this.$(e);
    }
    /** The index of one past the last segment of the path. */    limit() {
        return this.offset + this.length;
    }
    k(t) {
        return t = void 0 === t ? 1 : t, this.$(this.segments, this.offset + t, this.length - t);
    }
    L() {
        return this.$(this.segments, this.offset, this.length - 1);
    }
    M() {
        return this.segments[this.offset];
    }
    O() {
        return this.get(this.length - 1);
    }
    get(t) {
        return this.segments[this.offset + t];
    }
    B() {
        return 0 === this.length;
    }
    q(t) {
        if (t.length < this.length) return !1;
        for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
        return !0;
    }
    U(t) {
        if (this.length + 1 !== t.length) return !1;
        for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
        return !0;
    }
    forEach(t) {
        for (let e = this.offset, s = this.limit(); e < s; e++) t(this.segments[e]);
    }
    W() {
        return this.segments.slice(this.offset, this.limit());
    }
    static N(t, e) {
        const s = Math.min(t.length, e.length);
        for (let i = 0; i < s; i++) {
            const s = t.get(i), n = e.get(i);
            if (s < n) return -1;
            if (s > n) return 1;
        }
        return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
    }
}

/**
 * A slash-separated path for navigating resources (documents and collections)
 * within Firestore.
 */ class v extends b {
    $(t, e, s) {
        return new v(t, e, s);
    }
    j() {
        // 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.W().join("/");
    }
    toString() {
        return this.j();
    }
    /**
     * Creates a resource path from the given slash-delimited string.
     */    static K(t) {
        // 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).
        if (t.indexOf("//") >= 0) throw new R(w.INVALID_ARGUMENT, `Invalid path (${t}). Paths must not contain // in them.`);
        // We may still have an empty segment at the beginning or end if they had a
        // leading or trailing slash (which we allow).
                const e = t.split("/").filter(t => t.length > 0);
        return new v(e);
    }
}

v.G = new v([]);

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

/** A dot-separated path for navigating sub-objects within a document. */ class D extends b {
    $(t, e, s) {
        return new D(t, e, s);
    }
    /**
     * Returns true if the string could be used as a segment in a field path
     * without escaping.
     */    static H(t) {
        return S.test(t);
    }
    j() {
        return this.W().map(t => (t = t.replace("\\", "\\\\").replace("`", "\\`"), D.H(t) || (t = "`" + t + "`"), 
        t)).join(".");
    }
    toString() {
        return this.j();
    }
    /**
     * Returns true if this field references the key of a document.
     */    Y() {
        return 1 === this.length && "__name__" === this.get(0);
    }
    /**
     * The field designating the key of a document.
     */    static J() {
        return new D([ "__name__" ]);
    }
    /**
     * 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 X(t) {
        const e = [];
        let s = "", i = 0;
        const n = () => {
            if (0 === s.length) throw new R(w.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin ` + "with '.', end with '.', or contain '..'");
            e.push(s), s = "";
        };
        let r = !1;
        for (;i < t.length; ) {
            const e = t[i];
            if ("\\" === e) {
                if (i + 1 === t.length) throw new R(w.INVALID_ARGUMENT, "Path has trailing escape character: " + t);
                const e = t[i + 1];
                if ("\\" !== e && "." !== e && "`" !== e) throw new R(w.INVALID_ARGUMENT, "Path has invalid escape sequence: " + t);
                s += e, i += 2;
            } else "`" === e ? (r = !r, i++) : "." !== e || r ? (s += e, i++) : (n(), i++);
        }
        if (n(), r) throw new R(w.INVALID_ARGUMENT, "Unterminated ` in path: " + t);
        return new D(e);
    }
}

D.G = new D([]);

/**
 * @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 C {
    constructor(t) {
        this.path = t;
    }
    static Z(t) {
        return new C(v.K(t).k(5));
    }
    /** Returns true if the document is in the specified collectionId. */    tt(t) {
        return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
    }
    isEqual(t) {
        return null !== t && 0 === v.N(this.path, t.path);
    }
    toString() {
        return this.path.toString();
    }
    static N(t, e) {
        return v.N(t.path, e.path);
    }
    static et(t) {
        return t.length % 2 == 0;
    }
    /**
     * Creates and returns a new document key with the given segments.
     *
     * @param segments The segments of the path to the document
     * @return A new instance of DocumentKey
     */    static st(t) {
        return new C(new v(t.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 F(t) {
    let e = 0;
    for (const s in t) Object.prototype.hasOwnProperty.call(t, s) && e++;
    return e;
}

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

function $(t) {
    for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;
    return !0;
}

/**
 * @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.
 */ C.EMPTY = new C(new v([]));

class k {
    constructor(t) {
        this.it = t;
    }
    static fromBase64String(t) {
        const e = Ae.nt().atob(t);
        return new k(e);
    }
    static fromUint8Array(t) {
        const e = 
        /**
 * Helper function to convert an Uint8array to a binary string.
 */
        function(t) {
            let e = "";
            for (let s = 0; s < t.length; ++s) e += String.fromCharCode(t[s]);
            return e;
        }
        /**
 * Helper function to convert a binary string to an Uint8Array.
 */ (t);
        return new k(e);
    }
    toBase64() {
        return Ae.nt().btoa(this.it);
    }
    toUint8Array() {
        return function(t) {
            const e = new Uint8Array(t.length);
            for (let s = 0; s < t.length; s++) e[s] = t.charCodeAt(s);
            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.
 */
        /**
 * Returns whether a variable is either undefined or null.
 */ (this.it);
    }
    rt() {
        return 2 * this.it.length;
    }
    S(t) {
        return Ce(this.it, t.it);
    }
    isEqual(t) {
        return this.it === t.it;
    }
}

function L(t) {
    return null == t;
}

/** Returns whether the value represents -0. */ function M(t) {
    // 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 === t && 1 / t == -1 / 0;
}

/**
 * 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 O(t) {
    return "number" == typeof t && Number.isInteger(t) && !M(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;
}

/**
 * @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
 *   TransformMutation (see TransformMutation.applyTo()). 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.
 */ k.ht = new k("");

function x(t) {
    var e, s;
    return "server_timestamp" === (null === (s = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === s ? void 0 : s.stringValue);
}

/**
 * Creates a new ServerTimestamp proto value (using the internal format).
 */
/**
 * Returns the local time at which this timestamp was first set.
 */
function B(t) {
    const e = H(t.mapValue.fields.__local_write_time__.timestampValue);
    return new p(e.seconds, e.nanos);
}

/**
 * @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.
const q = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);

/** Extracts the backend's type order for the provided value. */ function U(t) {
    return "nullValue" in t ? 0 /* NullValue */ : "booleanValue" in t ? 1 /* BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* NumberValue */ : "timestampValue" in t ? 3 /* TimestampValue */ : "stringValue" in t ? 5 /* StringValue */ : "bytesValue" in t ? 6 /* BlobValue */ : "referenceValue" in t ? 7 /* RefValue */ : "geoPointValue" in t ? 8 /* GeoPointValue */ : "arrayValue" in t ? 9 /* ArrayValue */ : "mapValue" in t ? x(t) ? 4 /* ServerTimestampValue */ : 10 /* ObjectValue */ : be();
}

/** Tests `left` and `right` for equality based on the backend semantics. */ function Q(t, e) {
    const s = U(t);
    if (s !== U(e)) return !1;
    switch (s) {
      case 0 /* NullValue */ :
        return !0;

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

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

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

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

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

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

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

      case 2 /* NumberValue */ :
        return function(t, e) {
            if ("integerValue" in t && "integerValue" in e) return Y(t.integerValue) === Y(e.integerValue);
            if ("doubleValue" in t && "doubleValue" in e) {
                const s = Y(t.doubleValue), i = Y(e.doubleValue);
                return s === i ? M(s) === M(i) : isNaN(s) && isNaN(i);
            }
            return !1;
        }(t, e);

      case 9 /* ArrayValue */ :
        return Fe(t.arrayValue.values || [], e.arrayValue.values || [], Q);

      case 10 /* ObjectValue */ :
        return function(t, e) {
            const s = t.mapValue.fields || {}, i = e.mapValue.fields || {};
            if (F(s) !== F(i)) return !1;
            for (const t in s) if (s.hasOwnProperty(t) && (void 0 === i[t] || !Q(s[t], i[t]))) return !1;
            return !0;
        }
        /** Returns true if the ArrayValue contains the specified element. */ (t, e);

      default:
        return be();
    }
}

function W(t, e) {
    return void 0 !== (t.values || []).find(t => Q(t, e));
}

function j(t, e) {
    const s = U(t), i = U(e);
    if (s !== i) return Ce(s, i);
    switch (s) {
      case 0 /* NullValue */ :
        return 0;

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

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

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

      case 4 /* ServerTimestampValue */ :
        return K(B(t), B(e));

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

      case 6 /* BlobValue */ :
        return function(t, e) {
            const s = J(t), i = J(e);
            return s.S(i);
        }(t.bytesValue, e.bytesValue);

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

      case 8 /* GeoPointValue */ :
        return function(t, e) {
            const s = Ce(Y(t.latitude), Y(e.latitude));
            if (0 !== s) return s;
            return Ce(Y(t.longitude), Y(e.longitude));
        }(t.geoPointValue, e.geoPointValue);

      case 9 /* ArrayValue */ :
        return function(t, e) {
            const s = t.values || [], i = e.values || [];
            for (let t = 0; t < s.length && t < i.length; ++t) {
                const e = j(s[t], i[t]);
                if (e) return e;
            }
            return Ce(s.length, i.length);
        }(t.arrayValue, e.arrayValue);

      case 10 /* ObjectValue */ :
        return function(t, e) {
            const s = t.fields || {}, i = Object.keys(s), n = e.fields || {}, r = Object.keys(n);
            // 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.
            i.sort(), r.sort();
            for (let t = 0; t < i.length && t < r.length; ++t) {
                const e = Ce(i[t], r[t]);
                if (0 !== e) return e;
                const h = j(s[i[t]], n[r[t]]);
                if (0 !== h) return h;
            }
            return Ce(i.length, r.length);
        }
        /**
 * Generates the canonical ID for the provided field value (as used in Target
 * serialization).
 */ (t.mapValue, e.mapValue);

      default:
        throw be();
    }
}

function K(t, e) {
    if ("string" == typeof t && "string" == typeof e && t.length === e.length) return Ce(t, e);
    const s = H(t), i = H(e), n = Ce(s.seconds, i.seconds);
    return 0 !== n ? n : Ce(s.nanos, i.nanos);
}

function G(t) {
    return z(t);
}

function z(t) {
    return "nullValue" in t ? "null" : "booleanValue" in t ? "" + t.booleanValue : "integerValue" in t ? "" + t.integerValue : "doubleValue" in t ? "" + t.doubleValue : "timestampValue" in t ? function(t) {
        const e = H(t);
        return `time(${e.seconds},${e.nanos})`;
    }(t.timestampValue) : "stringValue" in t ? t.stringValue : "bytesValue" in t ? J(t.bytesValue).toBase64() : "referenceValue" in t ? (s = t.referenceValue, 
    C.Z(s).toString()) : "geoPointValue" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : "arrayValue" in t ? function(t) {
        let e = "[", s = !0;
        for (const i of t.values || []) s ? s = !1 : e += ",", e += z(i);
        return e + "]";
    }
    /**
 * Converts the possible Proto values for a timestamp value into a "seconds and
 * nanos" representation.
 */ (t.arrayValue) : "mapValue" in t ? function(t) {
        // 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 e = Object.keys(t.fields || {}).sort();
        let s = "{", i = !0;
        for (const n of e) i ? i = !1 : s += ",", s += `${n}:${z(t.fields[n])}`;
        return s + "}";
    }(t.mapValue) : be();
    var e, s;
}

function H(t) {
    // 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 (ve(!!t), "string" == typeof t) {
        // 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 e = 0;
        const s = q.exec(t);
        if (ve(!!s), s[1]) {
            // Pad the fraction out to 9 digits (nanos).
            let t = s[1];
            t = (t + "000000000").substr(0, 9), e = Number(t);
        }
        // Parse the date to get the seconds.
                const i = new Date(t);
        return {
            seconds: Math.floor(i.getTime() / 1e3),
            nanos: e
        };
    }
    return {
        seconds: Y(t.seconds),
        nanos: Y(t.nanos)
    };
}

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

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

/** Returns a reference value for the provided database and key. */ function X(t, e) {
    return {
        referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.j()}`
    };
}

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

/** Returns true if `value` is a DoubleValue. */
/** Returns true if `value` is an ArrayValue. */
function tt(t) {
    return !!t && "arrayValue" in t;
}

/** Returns true if `value` is a NullValue. */ function et(t) {
    return !!t && "nullValue" in t;
}

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

/** Returns true if `value` is a MapValue. */ function it(t) {
    return !!t && "mapValue" in 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.
 */
/** Transforms a value into a server-generated timestamp. */ class nt {
    constructor() {}
    ot(t, e) {
        return function(t, e) {
            const s = {
                fields: {
                    __type__: {
                        stringValue: "server_timestamp"
                    },
                    __local_write_time__: {
                        timestampValue: {
                            seconds: t.seconds,
                            nanos: t.nanoseconds
                        }
                    }
                }
            };
            return e && (s.fields.__previous_value__ = e), {
                mapValue: s
            };
        }
        /**
 * 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.
 */ (e, t);
    }
    at(t, e) {
        return e;
    }
    ut(t) {
        return null;
 // Server timestamps are idempotent and don't require a base value.
        }
    isEqual(t) {
        return t instanceof nt;
    }
}

nt.instance = new nt;

/** Transforms an array value via a union operation. */
class rt {
    constructor(t) {
        this.elements = t;
    }
    ot(t, e) {
        return this.apply(t);
    }
    at(t, e) {
        // 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 this.apply(t);
    }
    apply(t) {
        const e = at(t);
        for (const t of this.elements) e.some(e => Q(e, t)) || e.push(t);
        return {
            arrayValue: {
                values: e
            }
        };
    }
    ut(t) {
        return null;
 // Array transforms are idempotent and don't require a base value.
        }
    isEqual(t) {
        return t instanceof rt && Fe(this.elements, t.elements, Q);
    }
}

/** Transforms an array value via a remove operation. */ class ht {
    constructor(t) {
        this.elements = t;
    }
    ot(t, e) {
        return this.apply(t);
    }
    at(t, e) {
        // 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 this.apply(t);
    }
    apply(t) {
        let e = at(t);
        for (const t of this.elements) e = e.filter(e => !Q(e, t));
        return {
            arrayValue: {
                values: e
            }
        };
    }
    ut(t) {
        return null;
 // Array transforms are idempotent and don't require a base value.
        }
    isEqual(t) {
        return t instanceof ht && Fe(this.elements, t.elements, Q);
    }
}

/**
 * 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 ot {
    constructor(t, e) {
        this.serializer = t, this.ct = e;
    }
    ot(t, e) {
        // 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 s = this.ut(t), i = this.asNumber(s) + this.asNumber(this.ct);
        return Z(s) && Z(this.ct) ? this.serializer._t(i) : this.serializer.lt(i);
    }
    at(t, e) {
        return e;
    }
    /**
     * Inspects the provided value, returning the provided value if it is already
     * a NumberValue, otherwise returning a coerced value of 0.
     */    ut(t) {
        return Z(e = t) || function(t) {
            return !!t && "doubleValue" in t;
        }
        /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (e) ? t : {
            integerValue: 0
        };
        var e;
    }
    isEqual(t) {
        return t instanceof ot && Q(this.ct, t.ct);
    }
    asNumber(t) {
        return Y(t.integerValue || t.doubleValue);
    }
}

function at(t) {
    return tt(t) && t.arrayValue.values ? t.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.
 */
/**
 * 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 ut {
    constructor(t) {
        this.fields = t, 
        // TODO(dimond): validation of FieldMask
        // Sort the field mask to support `FieldMask.isEqual()` and assert below.
        t.sort(D.N);
    }
    /**
     * 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.
     */    dt(t) {
        for (const e of this.fields) if (e.q(t)) return !0;
        return !1;
    }
    isEqual(t) {
        return Fe(this.fields, t.fields, (t, e) => t.isEqual(e));
    }
}

/** A field path and the TransformOperation to perform upon it. */ class ct {
    constructor(t, e) {
        this.field = t, this.transform = e;
    }
    isEqual(t) {
        return this.field.isEqual(t.field) && this.transform.isEqual(t.transform);
    }
}

/** The result of successfully applying a mutation to the backend. */ class _t {
    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.
     */
    t, 
    /**
     * The resulting fields returned from the backend after a
     * TransformMutation has been committed. Contains one FieldValue for each
     * FieldTransform that was in the mutation.
     *
     * Will be null if the mutation was not a TransformMutation.
     */
    e) {
        this.version = t, this.transformResults = e;
    }
}

/**
 * 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 lt {
    constructor(t, e) {
        this.updateTime = t, this.exists = e;
    }
    /** Creates a new empty Precondition. */    static ft() {
        return new lt;
    }
    /** Creates a new Precondition with an exists flag. */    static exists(t) {
        return new lt(void 0, t);
    }
    /** Creates a new Precondition based on a version a document exists at. */    static updateTime(t) {
        return new lt(t);
    }
    /** Returns whether this Precondition is empty. */    get Tt() {
        return void 0 === this.updateTime && void 0 === this.exists;
    }
    /**
     * Returns true if the preconditions is valid for the given document
     * (or null if no document is available).
     */    Et(t) {
        return void 0 !== this.updateTime ? t instanceof Vt && t.version.isEqual(this.updateTime) : void 0 === this.exists || this.exists === t instanceof Vt;
    }
    isEqual(t) {
        return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);
    }
}

/**
 * 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, Patch, and Transform 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        null                  Document(v0)
 * PatchMutation      Document(v3)          Document(v3)
 * PatchMutation      NoDocument(v3)        NoDocument(v3)
 * PatchMutation      null                  null
 * TransformMutation  Document(v3)          Document(v3)
 * TransformMutation  NoDocument(v3)        NoDocument(v3)
 * TransformMutation  null                  null
 * DeleteMutation     Document(v3)          NoDocument(v0)
 * DeleteMutation     NoDocument(v3)        NoDocument(v0)
 * DeleteMutation     null                  NoDocument(v0)
 *
 * For acknowledged mutations, we use the updateTime of the WriteResponse as
 * the resulting version for Set, Patch, and Transform 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 return an `UnknownDocument` and rely on Watch to send us the
 * updated version.
 *
 * Note that TransformMutations don't create Documents (in the case of being
 * applied to a NoDocument), even though they would on the backend. This is
 * because the client always combines the TransformMutation with a SetMutation
 * or PatchMutation and we only want to apply the transform if the prior
 * mutation resulted in a Document (always true for a SetMutation, but not
 * necessarily for a PatchMutation).
 *
 * ## Subclassing Notes
 *
 * Subclasses of Mutation need to implement applyToRemoteDocument() and
 * applyToLocalView() to implement the actual behavior of applying the mutation
 * to some source document.
 */ class dt {
    It(t) {}
    /**
     * Returns the version from the given document for use as the result of a
     * mutation. Mutations are defined to return the version of the base document
     * only if it is an existing document. Deleted and unknown documents have a
     * post-mutation version of SnapshotVersion.min().
     */    static wt(t) {
        return t instanceof Vt ? t.version : y.min();
    }
}

/**
 * A mutation that creates or replaces the document at the given key with the
 * object value contents.
 */ class ft extends dt {
    constructor(t, e, s) {
        super(), this.key = t, this.value = e, this.Rt = s, this.type = 0 /* Set */;
    }
    at(t, e) {
        this.It(t);
        // Unlike applyToLocalView, if we're applying a mutation to a remote
        // document the server has accepted the mutation so the precondition must
        // have held.
        const s = e.version;
        return new Vt(this.key, s, this.value, {
            hasCommittedMutations: !0
        });
    }
    ot(t, e, s) {
        if (this.It(t), !this.Rt.Et(t)) return t;
        const i = dt.wt(t);
        return new Vt(this.key, i, this.value, {
            At: !0
        });
    }
    Pt(t) {
        return null;
    }
    isEqual(t) {
        return t instanceof ft && this.key.isEqual(t.key) && this.value.isEqual(t.value) && this.Rt.isEqual(t.Rt);
    }
}

/**
 * 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.
 */ class Tt extends dt {
    constructor(t, e, s, i) {
        super(), this.key = t, this.data = e, this.Vt = s, this.Rt = i, this.type = 1 /* Patch */;
    }
    at(t, e) {
        if (this.It(t), !this.Rt.Et(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 return an UnknownDocument with the
        // known updateTime.
        return new pt(this.key, e.version);
        const s = this.gt(t);
        return new Vt(this.key, e.version, s, {
            hasCommittedMutations: !0
        });
    }
    ot(t, e, s) {
        if (this.It(t), !this.Rt.Et(t)) return t;
        const i = dt.wt(t), n = this.gt(t);
        return new Vt(this.key, i, n, {
            At: !0
        });
    }
    Pt(t) {
        return null;
    }
    isEqual(t) {
        return t instanceof Tt && this.key.isEqual(t.key) && this.Vt.isEqual(t.Vt) && this.Rt.isEqual(t.Rt);
    }
    /**
     * Patches the data of document if available or creates a new document. Note
     * that this does not check whether or not the precondition of this patch
     * holds.
     */    gt(t) {
        let e;
        return e = t instanceof Vt ? t.data() : Rt.empty(), this.pt(e);
    }
    pt(t) {
        const e = new At(t);
        return this.Vt.fields.forEach(t => {
            if (!t.B()) {
                const s = this.data.field(t);
                null !== s ? e.set(t, s) : e.delete(t);
            }
        }), e.yt();
    }
}

/**
 * A mutation that modifies specific fields of the document with transform
 * operations. Currently the only supported transform is a server timestamp, but
 * IP Address, increment(n), etc. could be supported in the future.
 *
 * It is somewhat similar to a PatchMutation in that it patches specific fields
 * and has no effect when applied to a null or NoDocument (see comment on
 * Mutation for rationale).
 */ class Et extends dt {
    constructor(t, e) {
        super(), this.key = t, this.fieldTransforms = e, this.type = 2 /* Transform */ , 
        // NOTE: We set a precondition of exists: true as a safety-check, since we
        // always combine TransformMutations with a SetMutation or PatchMutation which
        // (if successful) should end up with an existing document.
        this.Rt = lt.exists(!0);
    }
    at(t, e) {
        if (this.It(t), ve(null != e.transformResults), !this.Rt.Et(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 return an UnknownDocument with the
        // known updateTime.
        return new pt(this.key, e.version);
        const s = this.bt(t), i = this.vt(t, e.transformResults), n = e.version, r = this.St(s.data(), i);
        return new Vt(this.key, n, r, {
            hasCommittedMutations: !0
        });
    }
    ot(t, e, s) {
        if (this.It(t), !this.Rt.Et(t)) return t;
        const i = this.bt(t), n = this.Dt(s, t, e), r = this.St(i.data(), n);
        return new Vt(this.key, i.version, r, {
            At: !0
        });
    }
    Pt(t) {
        let e = null;
        for (const s of this.fieldTransforms) {
            const i = t instanceof Vt ? t.field(s.field) : void 0, n = s.transform.ut(i || null);
            null != n && (e = null == e ? (new At).set(s.field, n) : e.set(s.field, n));
        }
        return e ? e.yt() : null;
    }
    isEqual(t) {
        return t instanceof Et && this.key.isEqual(t.key) && Fe(this.fieldTransforms, t.fieldTransforms, (t, e) => t.isEqual(e)) && this.Rt.isEqual(t.Rt);
    }
    /**
     * Asserts that the given MaybeDocument is actually a Document and verifies
     * that it matches the key for this mutation. Since we only support
     * transformations with precondition exists this method is guaranteed to be
     * safe.
     */    bt(t) {
        return 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
     * TransformMutation has been acknowledged by the server.
     *
     * @param baseDoc The document prior to applying this mutation batch.
     * @param serverTransformResults The transform results received by the server.
     * @return The transform results list.
     */    vt(t, e) {
        const s = [];
        ve(this.fieldTransforms.length === e.length);
        for (let i = 0; i < e.length; i++) {
            const n = this.fieldTransforms[i], r = n.transform;
            let h = null;
            t instanceof Vt && (h = t.field(n.field)), s.push(r.at(h, e[i]));
        }
        return s;
    }
    /**
     * 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
     * TransformMutation locally.
     *
     * @param localWriteTime The local time of the transform mutation (used to
     *     generate ServerTimestampValues).
     * @param maybeDoc The current state of the document after applying all
     *     previous mutations.
     * @param baseDoc The document prior to applying this mutation batch.
     * @return The transform results list.
     */    Dt(t, e, s) {
        const i = [];
        for (const n of this.fieldTransforms) {
            const r = n.transform;
            let h = null;
            e instanceof Vt && (h = e.field(n.field)), null === h && s instanceof Vt && (
            // If the current document does not contain a value for the mutated
            // field, use the value that existed before applying this mutation
            // batch. This solves an edge case where a PatchMutation clears the
            // values in a nested map before the TransformMutation is applied.
            h = s.field(n.field)), i.push(r.ot(h, t));
        }
        return i;
    }
    St(t, e) {
        const s = new At(t);
        for (let t = 0; t < this.fieldTransforms.length; t++) {
            const i = this.fieldTransforms[t].field;
            s.set(i, e[t]);
        }
        return s.yt();
    }
}

/** A mutation that deletes the document at the given key. */ class It extends dt {
    constructor(t, e) {
        super(), this.key = t, this.Rt = e, this.type = 3 /* Delete */;
    }
    at(t, e) {
        // Unlike applyToLocalView, if we're applying a mutation to a remote
        // document the server has accepted the mutation so the precondition must
        // have held.
        return this.It(t), new gt(this.key, e.version, {
            hasCommittedMutations: !0
        });
    }
    ot(t, e, s) {
        return this.It(t), this.Rt.Et(t) ? new gt(this.key, y.min()) : t;
    }
    Pt(t) {
        return null;
    }
    isEqual(t) {
        return t instanceof It && this.key.isEqual(t.key) && this.Rt.isEqual(t.Rt);
    }
}

/**
 * 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.
 */ class wt extends dt {
    constructor(t, e) {
        super(), this.key = t, this.Rt = e, this.type = 4 /* Verify */;
    }
    at(t, e) {
        be();
    }
    ot(t, e, s) {
        be();
    }
    Pt(t) {
        be();
    }
    isEqual(t) {
        return t instanceof wt && this.key.isEqual(t.key) && this.Rt.isEqual(t.Rt);
    }
}

/**
 * @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 Rt {
    constructor(t) {
        this.proto = t;
    }
    static empty() {
        return new Rt({
            mapValue: {}
        });
    }
    /**
     * Returns the value at the given path or null.
     *
     * @param path the path to search
     * @return The value at the path or if there it doesn't exist.
     */    field(t) {
        if (t.B()) return this.proto;
        {
            let e = this.proto;
            for (let s = 0; s < t.length - 1; ++s) {
                if (!e.mapValue.fields) return null;
                if (e = e.mapValue.fields[t.get(s)], !it(e)) return null;
            }
            return e = (e.mapValue.fields || {})[t.O()], e || null;
        }
    }
    isEqual(t) {
        return Q(this.proto, t.proto);
    }
}

/**
 * An ObjectValueBuilder provides APIs to set and delete fields from an
 * ObjectValue.
 */ class At {
    /**
     * @param baseObject The object to mutate.
     */
    constructor(t = Rt.empty()) {
        this.Ct = t, 
        /** A map that contains the accumulated changes in this builder. */
        this.Ft = new Map;
    }
    /**
     * Sets the field to the provided value.
     *
     * @param path The field path to set.
     * @param value The value to set.
     * @return The current Builder instance.
     */    set(t, e) {
        return this.Nt(t, e), this;
    }
    /**
     * 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.
     * @return The current Builder instance.
     */    delete(t) {
        return this.Nt(t, null), this;
    }
    /**
     * Adds `value` to the overlay map at `path`. Creates nested map entries if
     * needed.
     */    Nt(t, e) {
        let s = this.Ft;
        for (let e = 0; e < t.length - 1; ++e) {
            const i = t.get(e);
            let n = s.get(i);
            n instanceof Map ? 
            // Re-use a previously created map
            s = n : n && 10 /* ObjectValue */ === U(n) ? (
            // Convert the existing Protobuf MapValue into a map
            n = new Map(Object.entries(n.mapValue.fields || {})), s.set(i, n), s = n) : (
            // Create an empty map to represent the current nesting level
            n = new Map, s.set(i, n), s = n);
        }
        s.set(t.O(), e);
    }
    /** Returns an ObjectValue with all mutations applied. */    yt() {
        const t = this.$t(D.G, this.Ft);
        return null != t ? new Rt(t) : this.Ct;
    }
    /**
     * Applies any overlays from `currentOverlays` that exist at `currentPath`
     * and returns the merged data at `currentPath` (or null if there were no
     * changes).
     *
     * @param currentPath The path at the current nesting level. Can be set to
     * FieldValue.EMPTY_PATH to represent the root.
     * @param currentOverlays The overlays at the current nesting level in the
     * same format as `overlayMap`.
     * @return The merged data at `currentPath` or null if no modifications
     * were applied.
     */    $t(t, e) {
        let s = !1;
        const i = this.Ct.field(t), n = it(i) ? // If there is already data at the current path, base our
        Object.assign({}, i.mapValue.fields) : {};
        return e.forEach((e, i) => {
            if (e instanceof Map) {
                const r = this.$t(t.child(i), e);
                null != r && (n[i] = r, s = !0);
            } else null !== e ? (n[i] = e, s = !0) : n.hasOwnProperty(i) && (delete n[i], s = !0);
        }), s ? {
            mapValue: {
                fields: n
            }
        } : null;
    }
}

/**
 * Returns a FieldMask built from all fields in a MapValue.
 */ function mt(t) {
    const e = [];
    return N(t.fields || {}, (t, s) => {
        const i = new D([ t ]);
        if (it(s)) {
            const t = mt(s.mapValue).fields;
            if (0 === t.length) 
            // Preserve the empty map by adding it to the FieldMask.
            e.push(i); else 
            // For nested and non-empty ObjectValues, add the FieldPath of the
            // leaf nodes.
            for (const s of t) e.push(i.child(s));
        } else 
        // For nested and non-empty ObjectValues, add the FieldPath of the leaf
        // nodes.
        e.push(i);
    }), new ut(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.
 */
/**
 * The result of a lookup for a given path may be an existing document or a
 * marker that this document does not exist at a given version.
 */ class Pt {
    constructor(t, e) {
        this.key = t, this.version = e;
    }
}

/**
 * Represents a document in Firestore with a key, version, data and whether the
 * data has local mutations applied to it.
 */ class Vt extends Pt {
    constructor(t, e, s, i) {
        super(t, e), this.kt = s, this.At = !!i.At, this.hasCommittedMutations = !!i.hasCommittedMutations;
    }
    field(t) {
        return this.kt.field(t);
    }
    data() {
        return this.kt;
    }
    Lt() {
        return this.kt.proto;
    }
    isEqual(t) {
        return t instanceof Vt && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.At === t.At && this.hasCommittedMutations === t.hasCommittedMutations && this.kt.isEqual(t.kt);
    }
    toString() {
        return `Document(${this.key}, ${this.version}, ${this.kt.toString()}, ` + `{hasLocalMutations: ${this.At}}), ` + `{hasCommittedMutations: ${this.hasCommittedMutations}})`;
    }
    get hasPendingWrites() {
        return this.At || this.hasCommittedMutations;
    }
}

/**
 * Compares the value for field `field` in the provided documents. Throws if
 * the field does not exist in both documents.
 */
/**
 * A class representing a deleted document.
 * Version is set to 0 if we don't point to any specific time, otherwise it
 * denotes time we know it didn't exist at.
 */
class gt extends Pt {
    constructor(t, e, s) {
        super(t, e), this.hasCommittedMutations = !(!s || !s.hasCommittedMutations);
    }
    toString() {
        return `NoDocument(${this.key}, ${this.version})`;
    }
    get hasPendingWrites() {
        return this.hasCommittedMutations;
    }
    isEqual(t) {
        return t instanceof gt && t.hasCommittedMutations === this.hasCommittedMutations && t.version.isEqual(this.version) && t.key.isEqual(this.key);
    }
}

/**
 * A class representing an existing document whose data is unknown (e.g. a
 * document that was updated without a known base document).
 */ class pt extends Pt {
    toString() {
        return `UnknownDocument(${this.key}, ${this.version})`;
    }
    get hasPendingWrites() {
        return !0;
    }
    isEqual(t) {
        return t instanceof pt && t.version.isEqual(this.version) && t.key.isEqual(this.key);
    }
}

/**
 * @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.
 */
/**
 * A Target represents the WatchTarget representation of a Query, which is used
 * by the LocalStore and the RemoteStore to keep track of and to execute
 * backend queries. While a Query can represent multiple Targets, each Targets
 * maps to a single WatchTarget in RemoteStore and a single TargetData entry
 * in persistence.
 */ class yt {
    /**
     * 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 constructor, because `Query` provides an implicit `orderBy`
     * property.
     */
    constructor(t, e = null, s = [], i = [], n = null, r = null, h = null) {
        this.path = t, this.collectionGroup = e, this.orderBy = s, this.filters = i, this.limit = n, 
        this.startAt = r, this.endAt = h, this.Mt = null;
    }
    canonicalId() {
        if (null === this.Mt) {
            let t = this.path.j();
            null !== this.collectionGroup && (t += "|cg:" + this.collectionGroup), t += "|f:", 
            t += this.filters.map(t => t.canonicalId()).join(","), t += "|ob:", t += this.orderBy.map(t => t.canonicalId()).join(","), 
            L(this.limit) || (t += "|l:", t += this.limit), this.startAt && (t += "|lb:", t += this.startAt.canonicalId()), 
            this.endAt && (t += "|ub:", t += this.endAt.canonicalId()), this.Mt = t;
        }
        return this.Mt;
    }
    toString() {
        let t = this.path.j();
        return null !== this.collectionGroup && (t += " collectionGroup=" + this.collectionGroup), 
        this.filters.length > 0 && (t += `, filters: [${this.filters.join(", ")}]`), L(this.limit) || (t += ", limit: " + this.limit), 
        this.orderBy.length > 0 && (t += `, orderBy: [${this.orderBy.join(", ")}]`), this.startAt && (t += ", startAt: " + this.startAt.canonicalId()), 
        this.endAt && (t += ", endAt: " + this.endAt.canonicalId()), `Target(${t})`;
    }
    isEqual(t) {
        if (this.limit !== t.limit) return !1;
        if (this.orderBy.length !== t.orderBy.length) return !1;
        for (let e = 0; e < this.orderBy.length; e++) if (!this.orderBy[e].isEqual(t.orderBy[e])) return !1;
        if (this.filters.length !== t.filters.length) return !1;
        for (let e = 0; e < this.filters.length; e++) if (!this.filters[e].isEqual(t.filters[e])) return !1;
        return this.collectionGroup === t.collectionGroup && (!!this.path.isEqual(t.path) && (!!(null !== this.startAt ? this.startAt.isEqual(t.startAt) : null === t.startAt) && (null !== this.endAt ? this.endAt.isEqual(t.endAt) : null === t.endAt)));
    }
    Ot() {
        return C.et(this.path) && null === this.collectionGroup && 0 === this.filters.length;
    }
}

/**
 * @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.
 */ class bt {
    /**
     * Initializes a Query with a path and optional additional query constraints.
     * Path must currently be empty if this is a collection group query.
     */
    constructor(t, e = null, s = [], i = [], n = null, r = "F" /* First */ , h = null, o = null) {
        this.path = t, this.collectionGroup = e, this.xt = s, this.filters = i, this.limit = n, 
        this.Bt = r, this.startAt = h, this.endAt = o, this.qt = null, 
        // The corresponding `Target` of this `Query` instance.
        this.Ut = null, this.startAt && this.Qt(this.startAt), this.endAt && this.Qt(this.endAt);
    }
    static Wt(t) {
        return new bt(t);
    }
    get orderBy() {
        if (null === this.qt) {
            this.qt = [];
            const t = this.jt(), e = this.Kt();
            if (null !== t && null === e) 
            // In order to implicitly add key ordering, we must also add the
            // inequality filter field for it to be a valid query.
            // Note that the default inequality field and key ordering is ascending.
            t.Y() || this.qt.push(new kt(t)), this.qt.push(new kt(D.J(), "asc" /* ASCENDING */)); else {
                let t = !1;
                for (const e of this.xt) this.qt.push(e), e.field.Y() && (t = !0);
                if (!t) {
                    // The order of the implicit key ordering always matches the last
                    // explicit order by
                    const t = this.xt.length > 0 ? this.xt[this.xt.length - 1].dir : "asc" /* ASCENDING */;
                    this.qt.push(new kt(D.J(), t));
                }
            }
        }
        return this.qt;
    }
    Gt(t) {
        const e = this.filters.concat([ t ]);
        return new bt(this.path, this.collectionGroup, this.xt.slice(), e, this.limit, this.Bt, this.startAt, this.endAt);
    }
    zt(t) {
        // TODO(dimond): validate that orderBy does not list the same key twice.
        const e = this.xt.concat([ t ]);
        return new bt(this.path, this.collectionGroup, e, this.filters.slice(), this.limit, this.Bt, this.startAt, this.endAt);
    }
    Ht(t) {
        return new bt(this.path, this.collectionGroup, this.xt.slice(), this.filters.slice(), t, "F" /* First */ , this.startAt, this.endAt);
    }
    Yt(t) {
        return new bt(this.path, this.collectionGroup, this.xt.slice(), this.filters.slice(), t, "L" /* Last */ , this.startAt, this.endAt);
    }
    Jt(t) {
        return new bt(this.path, this.collectionGroup, this.xt.slice(), this.filters.slice(), this.limit, this.Bt, t, this.endAt);
    }
    Xt(t) {
        return new bt(this.path, this.collectionGroup, this.xt.slice(), this.filters.slice(), this.limit, this.Bt, this.startAt, t);
    }
    /**
     * 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.
     */    Zt(t) {
        return new bt(t, 
        /*collectionGroup=*/ null, this.xt.slice(), this.filters.slice(), this.limit, this.Bt, this.startAt, this.endAt);
    }
    /**
     * Returns true if this query does not specify any query constraints that
     * could remove results.
     */    te() {
        return 0 === this.filters.length && null === this.limit && null == this.startAt && null == this.endAt && (0 === this.xt.length || 1 === this.xt.length && this.xt[0].field.Y());
    }
    // 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.
    canonicalId() {
        return `${this.ee().canonicalId()}|lt:${this.Bt}`;
    }
    toString() {
        return `Query(target=${this.ee().toString()}; limitType=${this.Bt})`;
    }
    isEqual(t) {
        return this.ee().isEqual(t.ee()) && this.Bt === t.Bt;
    }
    se(t, e) {
        let s = !1;
        for (const i of this.orderBy) {
            const n = i.compare(t, e);
            if (0 !== n) return n;
            s = s || i.field.Y();
        }
        return 0;
    }
    matches(t) {
        return this.ie(t) && this.ne(t) && this.re(t) && this.he(t);
    }
    oe() {
        return !L(this.limit) && "F" /* First */ === this.Bt;
    }
    ae() {
        return !L(this.limit) && "L" /* Last */ === this.Bt;
    }
    Kt() {
        return this.xt.length > 0 ? this.xt[0].field : null;
    }
    jt() {
        for (const t of this.filters) if (t instanceof vt && t.ue()) return t.field;
        return null;
    }
    // Checks if any of the provided Operators are included in the query and
    // returns the first one that is, or null if none are.
    ce(t) {
        for (const e of this.filters) if (e instanceof vt && t.indexOf(e.op) >= 0) return e.op;
        return null;
    }
    Ot() {
        return this.ee().Ot();
    }
    _e() {
        return null !== this.collectionGroup;
    }
    /**
     * Converts this `Query` instance to it's corresponding `Target`
     * representation.
     */    ee() {
        if (!this.Ut) if ("F" /* First */ === this.Bt) this.Ut = new yt(this.path, this.collectionGroup, this.orderBy, this.filters, this.limit, this.startAt, this.endAt); else {
            // Flip the orderBy directions since we want the last results
            const t = [];
            for (const e of this.orderBy) {
                const s = "desc" /* DESCENDING */ === e.dir ? "asc" /* ASCENDING */ : "desc" /* DESCENDING */;
                t.push(new kt(e.field, s));
            }
            // We need to swap the cursors to match the now-flipped query ordering.
                        const e = this.endAt ? new $t(this.endAt.position, !this.endAt.before) : null, s = this.startAt ? new $t(this.startAt.position, !this.startAt.before) : null;
            // Now return as a LimitType.First query.
            this.Ut = new yt(this.path, this.collectionGroup, t, this.filters, this.limit, e, s);
        }
        return this.Ut;
    }
    ie(t) {
        const e = t.key.path;
        return null !== this.collectionGroup ? t.key.tt(this.collectionGroup) && this.path.q(e) : C.et(this.path) ? this.path.isEqual(e) : this.path.U(e);
    }
    /**
     * A document must have a value for every ordering clause in order to show up
     * in the results.
     */    ne(t) {
        for (const e of this.xt) 
        // order by key always matches
        if (!e.field.Y() && null === t.field(e.field)) return !1;
        return !0;
    }
    re(t) {
        for (const e of this.filters) if (!e.matches(t)) return !1;
        return !0;
    }
    /**
     * Makes sure a document is within the bounds, if provided.
     */    he(t) {
        return !(this.startAt && !this.startAt.le(this.orderBy, t)) && (!this.endAt || !this.endAt.le(this.orderBy, t));
    }
    Qt(t) {}
}

class vt extends class {} {
    constructor(t, e, s) {
        super(), this.field = t, this.op = e, this.value = s;
    }
    /**
     * Creates a filter based on the provided arguments.
     */    static create(t, e, s) {
        if (t.Y()) return "in" /* IN */ === e ? new Dt(t, s) : new St(t, e, s);
        if (et(s)) {
            if ("==" /* EQUAL */ !== e) throw new R(w.INVALID_ARGUMENT, "Invalid query. Null supports only equality comparisons.");
            return new vt(t, e, s);
        }
        if (st(s)) {
            if ("==" /* EQUAL */ !== e) throw new R(w.INVALID_ARGUMENT, "Invalid query. NaN supports only equality comparisons.");
            return new vt(t, e, s);
        }
        return "array-contains" /* ARRAY_CONTAINS */ === e ? new Ct(t, s) : "in" /* IN */ === e ? new Ft(t, s) : "array-contains-any" /* ARRAY_CONTAINS_ANY */ === e ? new Nt(t, s) : new vt(t, e, s);
    }
    matches(t) {
        const e = t.field(this.field);
        // Only compare types with matching backend order (such as double and int).
                return null !== e && U(this.value) === U(e) && this.de(j(e, this.value));
    }
    de(t) {
        switch (this.op) {
          case "<" /* LESS_THAN */ :
            return t < 0;

          case "<=" /* LESS_THAN_OR_EQUAL */ :
            return t <= 0;

          case "==" /* EQUAL */ :
            return 0 === t;

          case ">" /* GREATER_THAN */ :
            return t > 0;

          case ">=" /* GREATER_THAN_OR_EQUAL */ :
            return t >= 0;

          default:
            return be();
        }
    }
    ue() {
        return [ "<" /* LESS_THAN */ , "<=" /* LESS_THAN_OR_EQUAL */ , ">" /* GREATER_THAN */ , ">=" /* GREATER_THAN_OR_EQUAL */ ].indexOf(this.op) >= 0;
    }
    canonicalId() {
        // 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 this.field.j() + this.op.toString() + G(this.value);
    }
    isEqual(t) {
        return t instanceof vt && (this.op === t.op && this.field.isEqual(t.field) && Q(this.value, t.value));
    }
    toString() {
        return `${this.field.j()} ${this.op} ${G(this.value)}`;
    }
}

/** Filter that matches on key fields (i.e. '__name__'). */ class St extends vt {
    constructor(t, e, s) {
        super(t, e, s), this.key = C.Z(s.referenceValue);
    }
    matches(t) {
        const e = C.N(t.key, this.key);
        return this.de(e);
    }
}

/** Filter that matches on key fields within an array. */ class Dt extends vt {
    constructor(t, e) {
        super(t, "in" /* IN */ , e), this.keys = (e.arrayValue.values || []).map(t => C.Z(t.referenceValue));
    }
    matches(t) {
        return this.keys.some(e => e.isEqual(t.key));
    }
}

/** A Filter that implements the array-contains operator. */ class Ct extends vt {
    constructor(t, e) {
        super(t, "array-contains" /* ARRAY_CONTAINS */ , e);
    }
    matches(t) {
        const e = t.field(this.field);
        return tt(e) && W(e.arrayValue, this.value);
    }
}

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

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

/**
 * 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 $t {
    constructor(t, e) {
        this.position = t, this.before = e;
    }
    canonicalId() {
        // TODO(b/29183165): Make this collision robust.
        return `${this.before ? "b" : "a"}:${this.position.map(t => G(t)).join(",")}`;
    }
    /**
     * Returns true if a document sorts before a bound using the provided sort
     * order.
     */    le(t, e) {
        let s = 0;
        for (let i = 0; i < this.position.length; i++) {
            const n = t[i], r = this.position[i];
            if (n.field.Y()) s = C.N(C.Z(r.referenceValue), e.key); else {
                s = j(r, e.field(n.field));
            }
            if ("desc" /* DESCENDING */ === n.dir && (s *= -1), 0 !== s) break;
        }
        return this.before ? s <= 0 : s < 0;
    }
    isEqual(t) {
        if (null === t) return !1;
        if (this.before !== t.before || this.position.length !== t.position.length) return !1;
        for (let e = 0; e < this.position.length; e++) {
            if (!Q(this.position[e], t.position[e])) return !1;
        }
        return !0;
    }
}

/**
 * An ordering on a field, in some Direction. Direction defaults to ASCENDING.
 */ class kt {
    constructor(t, e) {
        this.field = t, void 0 === e && (e = "asc" /* ASCENDING */), this.dir = e, this.fe = t.Y();
    }
    compare(t, e) {
        const s = this.fe ? C.N(t.key, e.key) : function(t, e, s) {
            const i = e.field(t), n = s.field(t);
            return null !== i && null !== n ? j(i, n) : be();
        }(this.field, t, e);
        switch (this.dir) {
          case "asc" /* ASCENDING */ :
            return s;

          case "desc" /* DESCENDING */ :
            return -1 * s;

          default:
            return be();
        }
    }
    canonicalId() {
        // TODO(b/29183165): Make this collision robust.
        return this.field.j() + this.dir.toString();
    }
    toString() {
        return `${this.field.j()} (${this.dir})`;
    }
    isEqual(t) {
        return this.dir === t.dir && this.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.
 */
/**
 * An immutable set of metadata that the local store tracks for each target.
 */ class Lt {
    constructor(
    /** The target being listened to. */
    t, 
    /**
     * The target ID to which the target corresponds; Assigned by the
     * LocalStore for user listens and by the SyncEngine for limbo watches.
     */
    e, 
    /** The purpose of the target. */
    s, 
    /**
     * The sequence number of the last transaction during which this target data
     * was modified.
     */
    i, 
    /** The latest snapshot version seen for this target. */
    n = y.min()
    /**
     * The maximum snapshot version at which the associated view
     * contained no limbo documents.
     */ , r = y.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.
     */ , h = k.ht) {
        this.target = t, this.targetId = e, this.Te = s, this.sequenceNumber = i, this.Ee = n, 
        this.lastLimboFreeSnapshotVersion = r, this.resumeToken = h;
    }
    /** Creates a new target data instance with an updated sequence number. */    Ie(t) {
        return new Lt(this.target, this.targetId, this.Te, t, this.Ee, this.lastLimboFreeSnapshotVersion, this.resumeToken);
    }
    /**
     * Creates a new target data instance with an updated resume token and
     * snapshot version.
     */    we(t, e) {
        return new Lt(this.target, this.targetId, this.Te, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);
    }
    /**
     * Creates a new target data instance with an updated last limbo free
     * snapshot version number.
     */    Re(t) {
        return new Lt(this.target, this.targetId, this.Te, this.sequenceNumber, this.Ee, t, this.resumeToken);
    }
}

/**
 * @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 Mt {
    // TODO(b/33078163): just use simplest form of existence filter for now
    constructor(t) {
        this.count = 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 Ot, xt;

/**
 * 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 Bt(t) {
    switch (t) {
      case w.OK:
        return be();

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

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

      default:
        return be();
    }
}

/**
 * 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 qt(t) {
    if (void 0 === t) 
    // 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 pe("GRPC error has no .code"), w.UNKNOWN;
    switch (t) {
      case Ot.OK:
        return w.OK;

      case Ot.CANCELLED:
        return w.CANCELLED;

      case Ot.UNKNOWN:
        return w.UNKNOWN;

      case Ot.DEADLINE_EXCEEDED:
        return w.DEADLINE_EXCEEDED;

      case Ot.RESOURCE_EXHAUSTED:
        return w.RESOURCE_EXHAUSTED;

      case Ot.INTERNAL:
        return w.INTERNAL;

      case Ot.UNAVAILABLE:
        return w.UNAVAILABLE;

      case Ot.UNAUTHENTICATED:
        return w.UNAUTHENTICATED;

      case Ot.INVALID_ARGUMENT:
        return w.INVALID_ARGUMENT;

      case Ot.NOT_FOUND:
        return w.NOT_FOUND;

      case Ot.ALREADY_EXISTS:
        return w.ALREADY_EXISTS;

      case Ot.PERMISSION_DENIED:
        return w.PERMISSION_DENIED;

      case Ot.FAILED_PRECONDITION:
        return w.FAILED_PRECONDITION;

      case Ot.ABORTED:
        return w.ABORTED;

      case Ot.OUT_OF_RANGE:
        return w.OUT_OF_RANGE;

      case Ot.UNIMPLEMENTED:
        return w.UNIMPLEMENTED;

      case Ot.DATA_LOSS:
        return w.DATA_LOSS;

      default:
        return be();
    }
}

/**
 * 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.
 */ (xt = Ot || (Ot = {}))[xt.OK = 0] = "OK", xt[xt.CANCELLED = 1] = "CANCELLED", 
xt[xt.UNKNOWN = 2] = "UNKNOWN", xt[xt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", 
xt[xt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", xt[xt.NOT_FOUND = 5] = "NOT_FOUND", 
xt[xt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", xt[xt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", 
xt[xt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", xt[xt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", 
xt[xt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", xt[xt.ABORTED = 10] = "ABORTED", 
xt[xt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", xt[xt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", 
xt[xt.INTERNAL = 13] = "INTERNAL", xt[xt.UNAVAILABLE = 14] = "UNAVAILABLE", xt[xt.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.
 */
// An immutable sorted map implementation, based on a Left-leaning Red-Black
// tree.
class Ut {
    constructor(t, e) {
        this.N = t, this.root = e || Wt.EMPTY;
    }
    // Returns a copy of the map, with the specified key/value added or replaced.
    Ae(t, e) {
        return new Ut(this.N, this.root.Ae(t, e, this.N).me(null, null, Wt.Pe, null, null));
    }
    // Returns a copy of the map, with the specified key removed.
    remove(t) {
        return new Ut(this.N, this.root.remove(t, this.N).me(null, null, Wt.Pe, null, null));
    }
    // Returns the value of the node with the given key, or null.
    get(t) {
        let e = this.root;
        for (;!e.B(); ) {
            const s = this.N(t, e.key);
            if (0 === s) return e.value;
            s < 0 ? e = e.left : s > 0 && (e = e.right);
        }
        return null;
    }
    // Returns the index of the element in this sorted map, or -1 if it doesn't
    // exist.
    indexOf(t) {
        // Number of nodes that were pruned when descending right
        let e = 0, s = this.root;
        for (;!s.B(); ) {
            const i = this.N(t, s.key);
            if (0 === i) return e + s.left.size;
            i < 0 ? s = s.left : (
            // Count all nodes left of the node plus the node itself
            e += s.left.size + 1, s = s.right);
        }
        // Node not found
                return -1;
    }
    B() {
        return this.root.B();
    }
    // Returns the total number of nodes in the map.
    get size() {
        return this.root.size;
    }
    // Returns the minimum key in the map.
    Ve() {
        return this.root.Ve();
    }
    // Returns the maximum key in the map.
    ge() {
        return this.root.ge();
    }
    // 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.
    pe(t) {
        return this.root.pe(t);
    }
    forEach(t) {
        this.pe((e, s) => (t(e, s), !1));
    }
    toString() {
        const t = [];
        return this.pe((e, s) => (t.push(`${e}:${s}`), !1)), `{${t.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.
    ye(t) {
        return this.root.ye(t);
    }
    // Returns an iterator over the SortedMap.
    be() {
        return new Qt(this.root, null, this.N, !1);
    }
    ve(t) {
        return new Qt(this.root, t, this.N, !1);
    }
    Se() {
        return new Qt(this.root, null, this.N, !0);
    }
    De(t) {
        return new Qt(this.root, t, this.N, !0);
    }
}

 // end SortedMap
// An iterator over an LLRBNode.
class Qt {
    constructor(t, e, s, i) {
        this.Ce = i, this.Fe = [];
        let n = 1;
        for (;!t.B(); ) if (n = e ? s(t.key, e) : 1, 
        // flip the comparison if we're going in reverse
        i && (n *= -1), n < 0) 
        // This node is less than our start key. ignore it
        t = this.Ce ? t.left : t.right; else {
            if (0 === n) {
                // This node is exactly equal to our start key. Push it on the stack,
                // but stop iterating;
                this.Fe.push(t);
                break;
            }
            // This node is greater than our start key, add it to the stack and move
            // to the next one
            this.Fe.push(t), t = this.Ce ? t.right : t.left;
        }
    }
    Ne() {
        let t = this.Fe.pop();
        const e = {
            key: t.key,
            value: t.value
        };
        if (this.Ce) for (t = t.left; !t.B(); ) this.Fe.push(t), t = t.right; else for (t = t.right; !t.B(); ) this.Fe.push(t), 
        t = t.left;
        return e;
    }
    $e() {
        return this.Fe.length > 0;
    }
    ke() {
        if (0 === this.Fe.length) return null;
        const t = this.Fe[this.Fe.length - 1];
        return {
            key: t.key,
            value: t.value
        };
    }
}

 // end SortedMapIterator
// Represents a node in a Left-leaning Red-Black tree.
class Wt {
    constructor(t, e, s, i, n) {
        this.key = t, this.value = e, this.color = null != s ? s : Wt.RED, this.left = null != i ? i : Wt.EMPTY, 
        this.right = null != n ? n : Wt.EMPTY, this.size = this.left.size + 1 + this.right.size;
    }
    // Returns a copy of the current node, optionally replacing pieces of it.
    me(t, e, s, i, n) {
        return new Wt(null != t ? t : this.key, null != e ? e : this.value, null != s ? s : this.color, null != i ? i : this.left, null != n ? n : this.right);
    }
    B() {
        return !1;
    }
    // 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.
    pe(t) {
        return this.left.pe(t) || t(this.key, this.value) || this.right.pe(t);
    }
    // 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.
    ye(t) {
        return this.right.ye(t) || t(this.key, this.value) || this.left.ye(t);
    }
    // Returns the minimum node in the tree.
    min() {
        return this.left.B() ? this : this.left.min();
    }
    // Returns the maximum key in the tree.
    Ve() {
        return this.min().key;
    }
    // Returns the maximum key in the tree.
    ge() {
        return this.right.B() ? this.key : this.right.ge();
    }
    // Returns new tree, with the key/value added.
    Ae(t, e, s) {
        let i = this;
        const n = s(t, i.key);
        return i = n < 0 ? i.me(null, null, null, i.left.Ae(t, e, s), null) : 0 === n ? i.me(null, e, null, null, null) : i.me(null, null, null, null, i.right.Ae(t, e, s)), 
        i.Le();
    }
    Me() {
        if (this.left.B()) return Wt.EMPTY;
        let t = this;
        return t.left.Oe() || t.left.left.Oe() || (t = t.xe()), t = t.me(null, null, null, t.left.Me(), null), 
        t.Le();
    }
    // Returns new tree, with the specified item removed.
    remove(t, e) {
        let s, i = this;
        if (e(t, i.key) < 0) i.left.B() || i.left.Oe() || i.left.left.Oe() || (i = i.xe()), 
        i = i.me(null, null, null, i.left.remove(t, e), null); else {
            if (i.left.Oe() && (i = i.Be()), i.right.B() || i.right.Oe() || i.right.left.Oe() || (i = i.qe()), 
            0 === e(t, i.key)) {
                if (i.right.B()) return Wt.EMPTY;
                s = i.right.min(), i = i.me(s.key, s.value, null, null, i.right.Me());
            }
            i = i.me(null, null, null, null, i.right.remove(t, e));
        }
        return i.Le();
    }
    Oe() {
        return this.color;
    }
    // Returns new tree after performing any needed rotations.
    Le() {
        let t = this;
        return t.right.Oe() && !t.left.Oe() && (t = t.Ue()), t.left.Oe() && t.left.left.Oe() && (t = t.Be()), 
        t.left.Oe() && t.right.Oe() && (t = t.Qe()), t;
    }
    xe() {
        let t = this.Qe();
        return t.right.left.Oe() && (t = t.me(null, null, null, null, t.right.Be()), t = t.Ue(), 
        t = t.Qe()), t;
    }
    qe() {
        let t = this.Qe();
        return t.left.left.Oe() && (t = t.Be(), t = t.Qe()), t;
    }
    Ue() {
        const t = this.me(null, null, Wt.RED, null, this.right.left);
        return this.right.me(null, null, this.color, t, null);
    }
    Be() {
        const t = this.me(null, null, Wt.RED, this.left.right, null);
        return this.left.me(null, null, this.color, null, t);
    }
    Qe() {
        const t = this.left.me(null, null, !this.left.color, null, null), e = this.right.me(null, null, !this.right.color, null, null);
        return this.me(null, null, !this.color, t, e);
    }
    // For testing.
    We() {
        const t = this.je();
        return Math.pow(2, t) <= 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.
    je() {
        if (this.Oe() && this.left.Oe()) throw be();
        if (this.right.Oe()) throw be();
        const t = this.left.je();
        if (t !== this.right.je()) throw be();
        return t + (this.Oe() ? 0 : 1);
    }
}

 // end LLRBNode
// Empty node is shared between all LLRB trees.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Wt.EMPTY = null, Wt.RED = !0, Wt.Pe = !1;

// end LLRBEmptyNode
Wt.EMPTY = new 
// Represents an empty node (a leaf node in the Red-Black Tree).
class {
    constructor() {
        this.size = 0;
    }
    get key() {
        throw be();
    }
    get value() {
        throw be();
    }
    get color() {
        throw be();
    }
    get left() {
        throw be();
    }
    get right() {
        throw be();
    }
    // Returns a copy of the current node.
    me(t, e, s, i, n) {
        return this;
    }
    // Returns a copy of the tree, with the specified key/value added.
    Ae(t, e, s) {
        return new Wt(t, e);
    }
    // Returns a copy of the tree, with the specified key removed.
    remove(t, e) {
        return this;
    }
    B() {
        return !0;
    }
    pe(t) {
        return !1;
    }
    ye(t) {
        return !1;
    }
    Ve() {
        return null;
    }
    ge() {
        return null;
    }
    Oe() {
        return !1;
    }
    // For testing.
    We() {
        return !0;
    }
    je() {
        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 jt {
    constructor(t) {
        this.N = t, this.data = new Ut(this.N);
    }
    has(t) {
        return null !== this.data.get(t);
    }
    first() {
        return this.data.Ve();
    }
    last() {
        return this.data.ge();
    }
    get size() {
        return this.data.size;
    }
    indexOf(t) {
        return this.data.indexOf(t);
    }
    /** Iterates elements in order defined by "comparator" */    forEach(t) {
        this.data.pe((e, s) => (t(e), !1));
    }
    /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */    Ke(t, e) {
        const s = this.data.ve(t[0]);
        for (;s.$e(); ) {
            const i = s.Ne();
            if (this.N(i.key, t[1]) >= 0) return;
            e(i.key);
        }
    }
    /**
     * Iterates over `elem`s such that: start <= elem until false is returned.
     */    Ge(t, e) {
        let s;
        for (s = void 0 !== e ? this.data.ve(e) : this.data.be(); s.$e(); ) {
            if (!t(s.Ne().key)) return;
        }
    }
    /** Finds the least element greater than or equal to `elem`. */    ze(t) {
        const e = this.data.ve(t);
        return e.$e() ? e.Ne().key : null;
    }
    be() {
        return new Kt(this.data.be());
    }
    ve(t) {
        return new Kt(this.data.ve(t));
    }
    /** Inserts or updates an element */    add(t) {
        return this.me(this.data.remove(t).Ae(t, !0));
    }
    /** Deletes an element */    delete(t) {
        return this.has(t) ? this.me(this.data.remove(t)) : this;
    }
    B() {
        return this.data.B();
    }
    He(t) {
        let e = this;
        // Make sure `result` always refers to the larger one of the two sets.
                return e.size < t.size && (e = t, t = this), t.forEach(t => {
            e = e.add(t);
        }), e;
    }
    isEqual(t) {
        if (!(t instanceof jt)) return !1;
        if (this.size !== t.size) return !1;
        const e = this.data.be(), s = t.data.be();
        for (;e.$e(); ) {
            const t = e.Ne().key, i = s.Ne().key;
            if (0 !== this.N(t, i)) return !1;
        }
        return !0;
    }
    W() {
        const t = [];
        return this.forEach(e => {
            t.push(e);
        }), t;
    }
    toString() {
        const t = [];
        return this.forEach(e => t.push(e)), "SortedSet(" + t.toString() + ")";
    }
    me(t) {
        const e = new jt(this.N);
        return e.data = t, e;
    }
}

class Kt {
    constructor(t) {
        this.Ye = t;
    }
    Ne() {
        return this.Ye.Ne().key;
    }
    $e() {
        return this.Ye.$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 Gt = new Ut(C.N);

function zt() {
    return Gt;
}

function Ht() {
    return zt();
}

const Yt = new Ut(C.N);

function Jt() {
    return Yt;
}

const Xt = new Ut(C.N);

function Zt() {
    return Xt;
}

const te = new jt(C.N);

function ee(...t) {
    let e = te;
    for (const s of t) e = e.add(s);
    return e;
}

const se = new jt(Ce);

function ie() {
    return se;
}

/**
 * @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 ne {
    /** The default ordering is by key if the comparator is omitted */
    constructor(t) {
        // We are adding document key comparator to the end as it's the only
        // guaranteed unique property of a document.
        this.N = t ? (e, s) => t(e, s) || C.N(e.key, s.key) : (t, e) => C.N(t.key, e.key), 
        this.Je = Jt(), this.Xe = new Ut(this.N);
    }
    /**
     * Returns an empty copy of the existing DocumentSet, using the same
     * comparator.
     */    static Ze(t) {
        return new ne(t.N);
    }
    has(t) {
        return null != this.Je.get(t);
    }
    get(t) {
        return this.Je.get(t);
    }
    first() {
        return this.Xe.Ve();
    }
    last() {
        return this.Xe.ge();
    }
    B() {
        return this.Xe.B();
    }
    /**
     * Returns the index of the provided key in the document set, or -1 if the
     * document key is not present in the set;
     */    indexOf(t) {
        const e = this.Je.get(t);
        return e ? this.Xe.indexOf(e) : -1;
    }
    get size() {
        return this.Xe.size;
    }
    /** Iterates documents in order defined by "comparator" */    forEach(t) {
        this.Xe.pe((e, s) => (t(e), !1));
    }
    /** Inserts or updates a document with the same key */    add(t) {
        // First remove the element if we have it.
        const e = this.delete(t.key);
        return e.me(e.Je.Ae(t.key, t), e.Xe.Ae(t, null));
    }
    /** Deletes a document with a given key */    delete(t) {
        const e = this.get(t);
        return e ? this.me(this.Je.remove(t), this.Xe.remove(e)) : this;
    }
    isEqual(t) {
        if (!(t instanceof ne)) return !1;
        if (this.size !== t.size) return !1;
        const e = this.Xe.be(), s = t.Xe.be();
        for (;e.$e(); ) {
            const t = e.Ne().key, i = s.Ne().key;
            if (!t.isEqual(i)) return !1;
        }
        return !0;
    }
    toString() {
        const t = [];
        return this.forEach(e => {
            t.push(e.toString());
        }), 0 === t.length ? "DocumentSet ()" : "DocumentSet (\n  " + t.join("  \n") + "\n)";
    }
    me(t, e) {
        const s = new ne;
        return s.N = this.N, s.Je = t, s.Xe = e, 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.
 */
/**
 * DocumentChangeSet keeps track of a set of changes to docs in a query, merging
 * duplicate events for the same doc.
 */ class re {
    constructor() {
        this.ts = new Ut(C.N);
    }
    track(t) {
        const e = t.doc.key, s = this.ts.get(e);
        s ? 
        // Merge the new change with the existing change.
        0 /* Added */ !== t.type && 3 /* Metadata */ === s.type ? this.ts = this.ts.Ae(e, t) : 3 /* Metadata */ === t.type && 1 /* Removed */ !== s.type ? this.ts = this.ts.Ae(e, {
            type: s.type,
            doc: t.doc
        }) : 2 /* Modified */ === t.type && 2 /* Modified */ === s.type ? this.ts = this.ts.Ae(e, {
            type: 2 /* Modified */ ,
            doc: t.doc
        }) : 2 /* Modified */ === t.type && 0 /* Added */ === s.type ? this.ts = this.ts.Ae(e, {
            type: 0 /* Added */ ,
            doc: t.doc
        }) : 1 /* Removed */ === t.type && 0 /* Added */ === s.type ? this.ts = this.ts.remove(e) : 1 /* Removed */ === t.type && 2 /* Modified */ === s.type ? this.ts = this.ts.Ae(e, {
            type: 1 /* Removed */ ,
            doc: s.doc
        }) : 0 /* Added */ === t.type && 1 /* Removed */ === s.type ? this.ts = this.ts.Ae(e, {
            type: 2 /* Modified */ ,
            doc: t.doc
        }) : 
        // This includes these cases, which don't make sense:
        // Added->Added
        // Removed->Removed
        // Modified->Added
        // Removed->Modified
        // Metadata->Added
        // Removed->Metadata
        be() : this.ts = this.ts.Ae(e, t);
    }
    es() {
        const t = [];
        return this.ts.pe((e, s) => {
            t.push(s);
        }), t;
    }
}

class he {
    constructor(t, e, s, i, n, r, h, o) {
        this.query = t, this.docs = e, this.ss = s, this.docChanges = i, this.ns = n, this.fromCache = r, 
        this.rs = h, this.hs = o;
    }
    /** Returns a view snapshot as if all documents in the snapshot were added. */    static os(t, e, s, i) {
        const n = [];
        return e.forEach(t => {
            n.push({
                type: 0 /* Added */ ,
                doc: t
            });
        }), new he(t, e, ne.Ze(e), n, s, i, 
        /* syncStateChanged= */ !0, 
        /* excludesMetadataChanges= */ !1);
    }
    get hasPendingWrites() {
        return !this.ns.B();
    }
    isEqual(t) {
        if (!(this.fromCache === t.fromCache && this.rs === t.rs && this.ns.isEqual(t.ns) && this.query.isEqual(t.query) && this.docs.isEqual(t.docs) && this.ss.isEqual(t.ss))) return !1;
        const e = this.docChanges, s = t.docChanges;
        if (e.length !== s.length) return !1;
        for (let t = 0; t < e.length; t++) if (e[t].type !== s[t].type || !e[t].doc.isEqual(s[t].doc)) return !1;
        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.
 */
/**
 * 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 oe {
    constructor(
    /**
     * The snapshot version this event brings us up to, or MIN if not set.
     */
    t, 
    /**
     * A map from target to changes to the target. See TargetChange.
     */
    e, 
    /**
     * A set of targets that is known to be inconsistent. Listens for these
     * targets should be re-established without resume tokens.
     */
    s, 
    /**
     * A set of which documents 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.
     */
    n) {
        this.Ee = t, this.as = e, this.us = s, this.cs = i, this._s = n;
    }
    /**
     * 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 ls(t, e) {
        const s = new Map;
        return s.set(t, ae.ds(t, e)), new oe(y.min(), s, ie(), zt(), ee());
    }
}

/**
 * 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 ae {
    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.
     */
    t, 
    /**
     * 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.
     */
    e, 
    /**
     * The set of documents that were newly assigned to this target as part of
     * this remote event.
     */
    s, 
    /**
     * The set of documents that were already assigned to this target but received
     * an update during this remote event.
     */
    i, 
    /**
     * The set of documents that were removed from this target as part of this
     * remote event.
     */
    n) {
        this.resumeToken = t, this.fs = e, this.Ts = s, this.Es = i, this.Is = n;
    }
    /**
     * 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 ds(t, e) {
        return new ae(k.ht, e, ee(), ee(), ee());
    }
}

/**
 * @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 ue {
    constructor(
    /** The new document applies to all of these targets. */
    t, 
    /** The new document is removed from all of these targets. */
    e, 
    /** The key of the document for this change. */
    s, 
    /**
     * 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.
     */
    i) {
        this.ws = t, this.removedTargetIds = e, this.key = s, this.Rs = i;
    }
}

class ce {
    constructor(t, e) {
        this.targetId = t, this.As = e;
    }
}

class _e {
    constructor(
    /** What kind of change occurred to the watch target. */
    t, 
    /** The target IDs that were added/removed/set. */
    e, 
    /**
     * 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.
     */
    s = k.ht
    /** An RPC error indicating why the watch failed. */ , i = null) {
        this.state = t, this.targetIds = e, this.resumeToken = s, this.cause = i;
    }
}

/** Tracks the internal state of a Watch target. */ class le {
    constructor() {
        /**
         * The number of pending responses (adds or removes) that we are waiting on.
         * We only consider targets active that have no pending responses.
         */
        this.ms = 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.Ps = Te(), 
        /** See public getters for explanations of these fields. */
        this.Vs = k.ht, this.gs = !1, 
        /**
         * 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.ps = !0;
    }
    /**
     * 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 fs() {
        return this.gs;
    }
    /** The last resume token sent to us for this target. */    get resumeToken() {
        return this.Vs;
    }
    /** Whether this target has pending target adds or target removes. */    get ys() {
        return 0 !== this.ms;
    }
    /** Whether we have modified any state that should trigger a snapshot. */    get bs() {
        return this.ps;
    }
    /**
     * Applies the resume token to the TargetChange, but only when it has a new
     * value. Empty resumeTokens are discarded.
     */    vs(t) {
        t.rt() > 0 && (this.ps = !0, this.Vs = t);
    }
    /**
     * Creates a target change from the current set of changes.
     *
     * To reset the document changes after raising this snapshot, call
     * `clearPendingChanges()`.
     */    Ss() {
        let t = ee(), e = ee(), s = ee();
        return this.Ps.forEach((i, n) => {
            switch (n) {
              case 0 /* Added */ :
                t = t.add(i);
                break;

              case 2 /* Modified */ :
                e = e.add(i);
                break;

              case 1 /* Removed */ :
                s = s.add(i);
                break;

              default:
                be();
            }
        }), new ae(this.Vs, this.gs, t, e, s);
    }
    /**
     * Resets the document changes and sets `hasPendingChanges` to false.
     */    Ds() {
        this.ps = !1, this.Ps = Te();
    }
    Cs(t, e) {
        this.ps = !0, this.Ps = this.Ps.Ae(t, e);
    }
    Fs(t) {
        this.ps = !0, this.Ps = this.Ps.remove(t);
    }
    Ns() {
        this.ms += 1;
    }
    $s() {
        this.ms -= 1;
    }
    ks() {
        this.ps = !0, this.gs = !0;
    }
}

/**
 * A helper class to accumulate watch changes into a RemoteEvent.
 */
class de {
    constructor(t) {
        this.Ls = t, 
        /** The internal state of all tracked targets. */
        this.Ms = new Map, 
        /** Keeps track of the documents to update since the last raised snapshot. */
        this.Os = zt(), 
        /** A mapping of document keys to their set of target IDs. */
        this.xs = fe(), 
        /**
         * A list of targets with existence filter mismatches. These targets are
         * known to be inconsistent and their listens needs to be re-established by
         * RemoteStore.
         */
        this.Bs = new jt(Ce);
    }
    /**
     * Processes and adds the DocumentWatchChange to the current set of changes.
     */    qs(t) {
        for (const e of t.ws) t.Rs instanceof Vt ? this.Us(e, t.Rs) : t.Rs instanceof gt && this.Qs(e, t.key, t.Rs);
        for (const e of t.removedTargetIds) this.Qs(e, t.key, t.Rs);
    }
    /** Processes and adds the WatchTargetChange to the current set of changes. */    Ws(t) {
        this.js(t, e => {
            const s = this.Ks(e);
            switch (t.state) {
              case 0 /* NoChange */ :
                this.Gs(e) && s.vs(t.resumeToken);
                break;

              case 1 /* Added */ :
                // We need to decrement the number of pending acks needed from watch
                // for this targetId.
                s.$s(), s.ys || 
                // 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.
                s.Ds(), s.vs(t.resumeToken);
                break;

              case 2 /* 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.
                s.$s(), s.ys || this.removeTarget(e);
                break;

              case 3 /* Current */ :
                this.Gs(e) && (s.ks(), s.vs(t.resumeToken));
                break;

              case 4 /* Reset */ :
                this.Gs(e) && (
                // 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.zs(e), s.vs(t.resumeToken));
                break;

              default:
                be();
            }
        });
    }
    /**
     * 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.
     */    js(t, e) {
        t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Ms.forEach((t, s) => {
            this.Gs(s) && e(s);
        });
    }
    /**
     * Handles existence filters and synthesizes deletes for filter mismatches.
     * Targets that are invalidated by filter mismatches are added to
     * `pendingTargetResets`.
     */    Hs(t) {
        const e = t.targetId, s = t.As.count, i = this.Ys(e);
        if (i) {
            const t = i.target;
            if (t.Ot()) if (0 === s) {
                // 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 s = new C(t.path);
                this.Qs(e, s, new gt(s, y.min()));
            } else ve(1 === s); else {
                this.Js(e) !== s && (
                // Existence filter mismatch: We reset the mapping and raise a new
                // snapshot with `isFromCache:true`.
                this.zs(e), this.Bs = this.Bs.add(e));
            }
        }
    }
    /**
     * Converts the currently accumulated state into a remote event at the
     * provided snapshot version. Resets the accumulated changes before returning.
     */    Xs(t) {
        const e = new Map;
        this.Ms.forEach((s, i) => {
            const n = this.Ys(i);
            if (n) {
                if (s.fs && n.target.Ot()) {
                    // 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. 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 e = new C(n.target.path);
                    null !== this.Os.get(e) || this.Zs(i, e) || this.Qs(i, e, new gt(e, t));
                }
                s.bs && (e.set(i, s.Ss()), s.Ds());
            }
        });
        let s = ee();
        // 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.xs.forEach((t, e) => {
            let i = !0;
            e.Ge(t => {
                const e = this.Ys(t);
                return !e || 2 /* LimboResolution */ === e.Te || (i = !1, !1);
            }), i && (s = s.add(t));
        });
        const i = new oe(t, e, this.Bs, this.Os, s);
        return this.Os = zt(), this.xs = fe(), this.Bs = new jt(Ce), i;
    }
    /**
     * Adds the provided document to the internal list of document updates and
     * its document key to the given target's mapping.
     */
    // Visible for testing.
    Us(t, e) {
        if (!this.Gs(t)) return;
        const s = this.Zs(t, e.key) ? 2 /* Modified */ : 0 /* Added */;
        this.Ks(t).Cs(e.key, s), this.Os = this.Os.Ae(e.key, e), this.xs = this.xs.Ae(e.key, this.ti(e.key).add(t));
    }
    /**
     * 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.
    Qs(t, e, s) {
        if (!this.Gs(t)) return;
        const i = this.Ks(t);
        this.Zs(t, e) ? i.Cs(e, 1 /* Removed */) : 
        // The document may have entered and left the target before we raised a
        // snapshot, so we can just ignore the change.
        i.Fs(e), this.xs = this.xs.Ae(e, this.ti(e).delete(t)), s && (this.Os = this.Os.Ae(e, s));
    }
    removeTarget(t) {
        this.Ms.delete(t);
    }
    /**
     * 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.
     */    Js(t) {
        const e = this.Ks(t).Ss();
        return this.Ls.ei(t).size + e.Ts.size - e.Is.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.
     */    Ns(t) {
        this.Ks(t).Ns();
    }
    Ks(t) {
        let e = this.Ms.get(t);
        return e || (e = new le, this.Ms.set(t, e)), e;
    }
    ti(t) {
        let e = this.xs.get(t);
        return e || (e = new jt(Ce), this.xs = this.xs.Ae(t, e)), e;
    }
    /**
     * Verifies that the user is still interested in this target (by calling
     * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs
     * from watch.
     */    Gs(t) {
        const e = null !== this.Ys(t);
        return e || ge("WatchChangeAggregator", "Detected inactive target", t), e;
    }
    /**
     * 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).
     */    Ys(t) {
        const e = this.Ms.get(t);
        return e && e.ys ? null : this.Ls.si(t);
    }
    /**
     * 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).
     */    zs(t) {
        this.Ms.set(t, new le), this.Ls.ei(t).forEach(e => {
            this.Qs(t, e, /*updatedDocument=*/ null);
        });
    }
    /**
     * Returns whether the LocalStore considers the document to be part of the
     * specified target.
     */    Zs(t, e) {
        return this.Ls.ei(t).has(e);
    }
}

function fe() {
    return new Ut(C.N);
}

function Te() {
    return new Ut(C.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.
 */ const Ee = (() => {
    const t = {
        asc: "ASCENDING",
        desc: "DESCENDING"
    };
    return t;
})(), Ie = (() => {
    const t = {
        "<": "LESS_THAN",
        "<=": "LESS_THAN_OR_EQUAL",
        ">": "GREATER_THAN",
        ">=": "GREATER_THAN_OR_EQUAL",
        "==": "EQUAL",
        "array-contains": "ARRAY_CONTAINS",
        in: "IN",
        "array-contains-any": "ARRAY_CONTAINS_ANY"
    };
    return t;
})();

/**
 * Generates JsonObject values for the Datastore API suitable for sending to
 * either GRPC stub methods or via the JSON/HTTP REST API.
 * TODO(klimt): We can remove the databaseId argument if we keep the full
 * resource name in documents.
 */
class we {
    constructor(t, e) {
        this.ii = t, this.options = e;
    }
    ni(t) {
        const e = void 0 === t.code ? w.UNKNOWN : qt(t.code);
        return new R(e, t.message || "");
    }
    /**
     * 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.
     */    ri(t) {
        return this.options.hi || L(t) ? t : {
            value: t
        };
    }
    /**
     * Returns a number (or null) from a google.protobuf.Int32Value proto.
     */    oi(t) {
        let e;
        return e = "object" == typeof t ? t.value : t, L(e) ? null : e;
    }
    /**
     * Returns an IntegerValue for `value`.
     */    _t(t) {
        return {
            integerValue: "" + t
        };
    }
    /**
     * Returns an DoubleValue for `value` that is encoded based the serializer's
     * `useProto3Json` setting.
     */    lt(t) {
        if (this.options.hi) {
            if (isNaN(t)) return {
                doubleValue: "NaN"
            };
            if (t === 1 / 0) return {
                doubleValue: "Infinity"
            };
            if (t === -1 / 0) return {
                doubleValue: "-Infinity"
            };
        }
        return {
            doubleValue: M(t) ? "-0" : t
        };
    }
    /**
     * 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.
     */    ai(t) {
        return O(t) ? this._t(t) : this.lt(t);
    }
    /**
     * Returns a value for a Date that's appropriate to put into a proto.
     */    C(t) {
        if (this.options.hi) {
            return `${new Date(1e3 * t.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + t.nanoseconds).slice(-9)}Z`;
        }
        return {
            seconds: "" + t.seconds,
            nanos: t.nanoseconds
        };
    }
    v(t) {
        const e = H(t);
        return new p(e.seconds, e.nanos);
    }
    /**
     * Returns a value for bytes that's appropriate to put in a proto.
     *
     * Visible for testing.
     */    ui(t) {
        return this.options.hi ? t.toBase64() : t.toUint8Array();
    }
    /**
     * Returns a ByteString based on the proto string value.
     */    ci(t) {
        return this.options.hi ? (ve(void 0 === t || "string" == typeof t), k.fromBase64String(t || "")) : (ve(void 0 === t || t instanceof Uint8Array), 
        k.fromUint8Array(t || new Uint8Array));
    }
    toVersion(t) {
        return this.C(t.C());
    }
    fromVersion(t) {
        return ve(!!t), y.v(this.v(t));
    }
    _i(t, e) {
        return this.li(e || this.ii).child("documents").child(t).j();
    }
    di(t) {
        const e = v.K(t);
        return ve(Re(e)), e;
    }
    fi(t) {
        return this._i(t.path);
    }
    Z(t) {
        const e = this.di(t);
        return ve(e.get(1) === this.ii.projectId), ve(!e.get(3) && !this.ii.database || e.get(3) === this.ii.database), 
        new C(this.Ti(e));
    }
    Ei(t) {
        return this._i(t);
    }
    Ii(t) {
        const e = this.di(t);
        // 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 === e.length ? v.G : this.Ti(e);
    }
    get wi() {
        return new v([ "projects", this.ii.projectId, "databases", this.ii.database ]).j();
    }
    li(t) {
        return new v([ "projects", t.projectId, "databases", t.database ]);
    }
    Ti(t) {
        return ve(t.length > 4 && "documents" === t.get(4)), t.k(5);
    }
    /** Creates an api.Document from key and fields (but no create/update time) */    Ri(t, e) {
        return {
            name: this.fi(t),
            fields: e.proto.mapValue.fields
        };
    }
    Ai(t) {
        return {
            name: this.fi(t.key),
            fields: t.Lt().mapValue.fields,
            updateTime: this.C(t.version.C())
        };
    }
    mi(t, e) {
        const s = this.Z(t.name), i = this.fromVersion(t.updateTime), n = new Rt({
            mapValue: {
                fields: t.fields
            }
        });
        return new Vt(s, i, n, {
            hasCommittedMutations: !!e
        });
    }
    Pi(t) {
        ve(!!t.found), t.found.name, t.found.updateTime;
        const e = this.Z(t.found.name), s = this.fromVersion(t.found.updateTime), i = new Rt({
            mapValue: {
                fields: t.found.fields
            }
        });
        return new Vt(e, s, i, {});
    }
    Vi(t) {
        ve(!!t.missing), ve(!!t.readTime);
        const e = this.Z(t.missing), s = this.fromVersion(t.readTime);
        return new gt(e, s);
    }
    gi(t) {
        return "found" in t ? this.Pi(t) : "missing" in t ? this.Vi(t) : be();
    }
    pi(t) {
        let e;
        if ("targetChange" in t) {
            t.targetChange;
            // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
            // if unset
            const s = this.yi(t.targetChange.targetChangeType || "NO_CHANGE"), i = t.targetChange.targetIds || [], n = this.ci(t.targetChange.resumeToken), r = t.targetChange.cause, h = r && this.ni(r);
            e = new _e(s, i, n, h || null);
        } else if ("documentChange" in t) {
            t.documentChange;
            const s = t.documentChange;
            s.document, s.document.name, s.document.updateTime;
            const i = this.Z(s.document.name), n = this.fromVersion(s.document.updateTime), r = new Rt({
                mapValue: {
                    fields: s.document.fields
                }
            }), h = new Vt(i, n, r, {}), o = s.targetIds || [], a = s.removedTargetIds || [];
            e = new ue(o, a, h.key, h);
        } else if ("documentDelete" in t) {
            t.documentDelete;
            const s = t.documentDelete;
            s.document;
            const i = this.Z(s.document), n = s.readTime ? this.fromVersion(s.readTime) : y.min(), r = new gt(i, n), h = s.removedTargetIds || [];
            e = new ue([], h, r.key, r);
        } else if ("documentRemove" in t) {
            t.documentRemove;
            const s = t.documentRemove;
            s.document;
            const i = this.Z(s.document), n = s.removedTargetIds || [];
            e = new ue([], n, i, null);
        } else {
            if (!("filter" in t)) return be();
            {
                t.filter;
                const s = t.filter;
                s.targetId;
                const i = s.count || 0, n = new Mt(i), r = s.targetId;
                e = new ce(r, n);
            }
        }
        return e;
    }
    yi(t) {
        return "NO_CHANGE" === t ? 0 /* NoChange */ : "ADD" === t ? 1 /* Added */ : "REMOVE" === t ? 2 /* Removed */ : "CURRENT" === t ? 3 /* Current */ : "RESET" === t ? 4 /* Reset */ : be();
    }
    bi(t) {
        // 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 t)) return y.min();
        const e = t.targetChange;
        return e.targetIds && e.targetIds.length ? y.min() : e.readTime ? this.fromVersion(e.readTime) : y.min();
    }
    vi(t) {
        let e;
        if (t instanceof ft) e = {
            update: this.Ri(t.key, t.value)
        }; else if (t instanceof It) e = {
            delete: this.fi(t.key)
        }; else if (t instanceof Tt) e = {
            update: this.Ri(t.key, t.data),
            updateMask: this.Si(t.Vt)
        }; else if (t instanceof Et) e = {
            transform: {
                document: this.fi(t.key),
                fieldTransforms: t.fieldTransforms.map(t => this.Di(t))
            }
        }; else {
            if (!(t instanceof wt)) return be();
            e = {
                verify: this.fi(t.key)
            };
        }
        return t.Rt.Tt || (e.currentDocument = this.Ci(t.Rt)), e;
    }
    Fi(t) {
        const e = t.currentDocument ? this.Ni(t.currentDocument) : lt.ft();
        if (t.update) {
            t.update.name;
            const s = this.Z(t.update.name), i = new Rt({
                mapValue: {
                    fields: t.update.fields
                }
            });
            if (t.updateMask) {
                const n = this.$i(t.updateMask);
                return new Tt(s, i, n, e);
            }
            return new ft(s, i, e);
        }
        if (t.delete) {
            const s = this.Z(t.delete);
            return new It(s, e);
        }
        if (t.transform) {
            const s = this.Z(t.transform.document), i = t.transform.fieldTransforms.map(t => this.ki(t));
            return ve(!0 === e.exists), new Et(s, i);
        }
        if (t.verify) {
            const s = this.Z(t.verify);
            return new wt(s, e);
        }
        return be();
    }
    Ci(t) {
        return void 0 !== t.updateTime ? {
            updateTime: this.toVersion(t.updateTime)
        } : void 0 !== t.exists ? {
            exists: t.exists
        } : be();
    }
    Ni(t) {
        return void 0 !== t.updateTime ? lt.updateTime(this.fromVersion(t.updateTime)) : void 0 !== t.exists ? lt.exists(t.exists) : lt.ft();
    }
    Li(t, e) {
        // NOTE: Deletes don't have an updateTime.
        let s = t.updateTime ? this.fromVersion(t.updateTime) : this.fromVersion(e);
        s.isEqual(y.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
        s = this.fromVersion(e));
        let i = null;
        return t.transformResults && t.transformResults.length > 0 && (i = t.transformResults), 
        new _t(s, i);
    }
    Mi(t, e) {
        return t && t.length > 0 ? (ve(void 0 !== e), t.map(t => this.Li(t, e))) : [];
    }
    Di(t) {
        const e = t.transform;
        if (e instanceof nt) return {
            fieldPath: t.field.j(),
            setToServerValue: "REQUEST_TIME"
        };
        if (e instanceof rt) return {
            fieldPath: t.field.j(),
            appendMissingElements: {
                values: e.elements
            }
        };
        if (e instanceof ht) return {
            fieldPath: t.field.j(),
            removeAllFromArray: {
                values: e.elements
            }
        };
        if (e instanceof ot) return {
            fieldPath: t.field.j(),
            increment: e.ct
        };
        throw be();
    }
    ki(t) {
        let e = null;
        if ("setToServerValue" in t) ve("REQUEST_TIME" === t.setToServerValue), e = nt.instance; else if ("appendMissingElements" in t) {
            const s = t.appendMissingElements.values || [];
            e = new rt(s);
        } else if ("removeAllFromArray" in t) {
            const s = t.removeAllFromArray.values || [];
            e = new ht(s);
        } else "increment" in t ? e = new ot(this, t.increment) : be();
        const s = D.X(t.fieldPath);
        return new ct(s, e);
    }
    Oi(t) {
        return {
            documents: [ this.Ei(t.path) ]
        };
    }
    xi(t) {
        ve(1 === t.documents.length);
        const e = t.documents[0];
        return bt.Wt(this.Ii(e)).ee();
    }
    Bi(t) {
        // Dissect the path into parent, collectionId, and optional key filter.
        const e = {
            structuredQuery: {}
        }, s = t.path;
        null !== t.collectionGroup ? (e.parent = this.Ei(s), e.structuredQuery.from = [ {
            collectionId: t.collectionGroup,
            allDescendants: !0
        } ]) : (e.parent = this.Ei(s.L()), e.structuredQuery.from = [ {
            collectionId: s.O()
        } ]);
        const i = this.qi(t.filters);
        i && (e.structuredQuery.where = i);
        const n = this.Ui(t.orderBy);
        n && (e.structuredQuery.orderBy = n);
        const r = this.ri(t.limit);
        return null !== r && (e.structuredQuery.limit = r), t.startAt && (e.structuredQuery.startAt = this.Qi(t.startAt)), 
        t.endAt && (e.structuredQuery.endAt = this.Qi(t.endAt)), e;
    }
    Wi(t) {
        let e = this.Ii(t.parent);
        const s = t.structuredQuery, i = s.from ? s.from.length : 0;
        let n = null;
        if (i > 0) {
            ve(1 === i);
            const t = s.from[0];
            t.allDescendants ? n = t.collectionId : e = e.child(t.collectionId);
        }
        let r = [];
        s.where && (r = this.ji(s.where));
        let h = [];
        s.orderBy && (h = this.Ki(s.orderBy));
        let o = null;
        s.limit && (o = this.oi(s.limit));
        let a = null;
        s.startAt && (a = this.Gi(s.startAt));
        let u = null;
        return s.endAt && (u = this.Gi(s.endAt)), new bt(e, n, h, r, o, "F" /* First */ , a, u).ee();
    }
    zi(t) {
        const e = this.Hi(t.Te);
        return null == e ? null : {
            "goog-listen-tags": e
        };
    }
    Hi(t) {
        switch (t) {
          case 0 /* Listen */ :
            return null;

          case 1 /* ExistenceFilterMismatch */ :
            return "existence-filter-mismatch";

          case 2 /* LimboResolution */ :
            return "limbo-document";

          default:
            return be();
        }
    }
    ee(t) {
        let e;
        const s = t.target;
        return e = s.Ot() ? {
            documents: this.Oi(s)
        } : {
            query: this.Bi(s)
        }, e.targetId = t.targetId, t.resumeToken.rt() > 0 && (e.resumeToken = this.ui(t.resumeToken)), 
        e;
    }
    qi(t) {
        if (0 === t.length) return;
        const e = t.map(t => t instanceof vt ? this.Yi(t) : be());
        return 1 === e.length ? e[0] : {
            compositeFilter: {
                op: "AND",
                filters: e
            }
        };
    }
    ji(t) {
        return t ? void 0 !== t.unaryFilter ? [ this.Ji(t) ] : void 0 !== t.fieldFilter ? [ this.Xi(t) ] : void 0 !== t.compositeFilter ? t.compositeFilter.filters.map(t => this.ji(t)).reduce((t, e) => t.concat(e)) : be() : [];
    }
    Ui(t) {
        if (0 !== t.length) return t.map(t => this.Zi(t));
    }
    Ki(t) {
        return t.map(t => this.tn(t));
    }
    Qi(t) {
        return {
            before: t.before,
            values: t.position
        };
    }
    Gi(t) {
        const e = !!t.before, s = t.values || [];
        return new $t(s, e);
    }
    // visible for testing
    en(t) {
        return Ee[t];
    }
    // visible for testing
    sn(t) {
        switch (t) {
          case "ASCENDING":
            return "asc" /* ASCENDING */;

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

          default:
            return;
        }
    }
    // visible for testing
    nn(t) {
        return Ie[t];
    }
    rn(t) {
        switch (t) {
          case "EQUAL":
            return "==" /* EQUAL */;

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

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

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

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

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

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

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

          case "OPERATOR_UNSPECIFIED":
          default:
            return be();
        }
    }
    hn(t) {
        return {
            fieldPath: t.j()
        };
    }
    on(t) {
        return D.X(t.fieldPath);
    }
    // visible for testing
    Zi(t) {
        return {
            field: this.hn(t.field),
            direction: this.en(t.dir)
        };
    }
    tn(t) {
        return new kt(this.on(t.field), this.sn(t.direction));
    }
    Xi(t) {
        return vt.create(this.on(t.fieldFilter.field), this.rn(t.fieldFilter.op), t.fieldFilter.value);
    }
    // visible for testing
    Yi(t) {
        if ("==" /* EQUAL */ === t.op) {
            if (st(t.value)) return {
                unaryFilter: {
                    field: this.hn(t.field),
                    op: "IS_NAN"
                }
            };
            if (et(t.value)) return {
                unaryFilter: {
                    field: this.hn(t.field),
                    op: "IS_NULL"
                }
            };
        }
        return {
            fieldFilter: {
                field: this.hn(t.field),
                op: this.nn(t.op),
                value: t.value
            }
        };
    }
    Ji(t) {
        switch (t.unaryFilter.op) {
          case "IS_NAN":
            const e = this.on(t.unaryFilter.field);
            return vt.create(e, "==" /* EQUAL */ , {
                doubleValue: NaN
            });

          case "IS_NULL":
            const s = this.on(t.unaryFilter.field);
            return vt.create(s, "==" /* EQUAL */ , {
                nullValue: "NULL_VALUE"
            });

          case "OPERATOR_UNSPECIFIED":
          default:
            return be();
        }
    }
    Si(t) {
        const e = [];
        return t.fields.forEach(t => e.push(t.j())), {
            fieldPaths: e
        };
    }
    $i(t) {
        const e = t.fieldPaths || [];
        return new ut(e.map(t => D.X(t)));
    }
}

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

/**
 * @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 singleton helpers where setup code can inject a platform at runtime.
 * setPlatform needs to be set before Firestore is used and must be set exactly
 * once.
 */ class Ae {
    static an(t) {
        Ae.platform && be(), Ae.platform = t;
    }
    static nt() {
        return Ae.platform || be(), Ae.platform;
    }
}

/**
 * @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 me = new e("@firebase/firestore");

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

function Ve(t) {
    me.logLevel = t;
}

function ge(t, ...e) {
    if (me.logLevel <= s.DEBUG) {
        const s = e.map(ye);
        me.debug(`Firestore (${E}): ${t}`, ...s);
    }
}

function pe(t, ...e) {
    if (me.logLevel <= s.ERROR) {
        const s = e.map(ye);
        me.error(`Firestore (${E}): ${t}`, ...s);
    }
}

/**
 * Converts an additional log parameter to a string representation.
 */ function ye(t) {
    if ("string" == typeof t) return t;
    {
        const e = Ae.nt();
        try {
            return e.un(t);
        } catch (e) {
            // Converting to JSON failed, just log the object directly
            return 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.
 */
/**
 * Unconditionally fails, throwing an Error with the given message.
 * Messages are stripped in production builds.
 *
 * Returns `never` and can be used in expressions:
 * @example
 * let futureVar = fail('not implemented yet');
 */ function be(t = "Unexpected state") {
    // Log the failure in addition to throw an exception, just in case the
    // exception is swallowed.
    const e = `FIRESTORE (${E}) INTERNAL ASSERTION FAILED: ` + t;
    // 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 pe(e), new Error(e);
}

/**
 * Fails if the given assertion condition is false, throwing an Error with the
 * given message if it did.
 *
 * Messages are stripped in production builds.
 */ function ve(t, e) {
    t || be();
}

/**
 * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
 * instance of `T` before casting.
 */ function Se(t, 
// eslint-disable-next-line @typescript-eslint/no-explicit-any
e) {
    return 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 De {
    static cn() {
        // Alphanumeric characters
        const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length;
        // The largest byte value that is a multiple of `char.length`.
                let s = "";
        for (;s.length < 20; ) {
            const i = Ae.nt()._n(40);
            for (let n = 0; n < i.length; ++n) 
            // Only accept values that are [0, maxMultiple), this ensures they can
            // be evenly mapped to indices of `chars` via a modulo operation.
            s.length < 20 && i[n] < e && (s += t.charAt(i[n] % t.length));
        }
        return s;
    }
}

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

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

/**
 * Returns the immediate lexicographically-following string. This is useful to
 * construct an inclusive range for indexeddb iterators.
 */ function Ne(t) {
    // Return the input string, with an additional NUL byte appended.
    return 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.
 */ class $e {
    /**
     * Constructs a DatabaseInfo using the provided host, databaseId and
     * persistenceKey.
     *
     * @param databaseId The database to use.
     * @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.
     */
    constructor(t, e, s, i, n) {
        this.ii = t, this.persistenceKey = e, this.host = s, this.ssl = i, this.forceLongPolling = n;
    }
}

/** The default database name for a project. */
/** Represents the database ID a Firestore client is associated with. */
class ke {
    constructor(t, e) {
        this.projectId = t, this.database = e || "(default)";
    }
    get ln() {
        return "(default)" === this.database;
    }
    isEqual(t) {
        return t instanceof ke && t.projectId === this.projectId && t.database === this.database;
    }
    S(t) {
        return Ce(this.projectId, t.projectId) || Ce(this.database, t.database);
    }
}

/**
 * @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 implement the
 * Equatable interface 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 Le {
    constructor(t) {
        this.dn = 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.fn = {};
    }
    /** Get a value for this key, or undefined if it does not exist. */    get(t) {
        const e = this.dn(t), s = this.fn[e];
        if (void 0 !== s) for (const [e, i] of s) if (e.isEqual(t)) return i;
    }
    has(t) {
        return void 0 !== this.get(t);
    }
    /** Put this key and value in the map. */    set(t, e) {
        const s = this.dn(t), i = this.fn[s];
        if (void 0 !== i) {
            for (let s = 0; s < i.length; s++) if (i[s][0].isEqual(t)) return void (i[s] = [ t, e ]);
            i.push([ t, e ]);
        } else this.fn[s] = [ [ t, e ] ];
    }
    /**
     * Remove this key from the map. Returns a boolean if anything was deleted.
     */    delete(t) {
        const e = this.dn(t), s = this.fn[e];
        if (void 0 === s) return !1;
        for (let i = 0; i < s.length; i++) if (s[i][0].isEqual(t)) return 1 === s.length ? delete this.fn[e] : s.splice(i, 1), 
        !0;
        return !1;
    }
    forEach(t) {
        N(this.fn, (e, s) => {
            for (const [e, i] of s) t(e, i);
        });
    }
    B() {
        return $(this.fn);
    }
}

/**
 * @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 Me {
    /**
     * @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(t, e, s, i) {
        this.batchId = t, this.Tn = e, this.baseMutations = s, this.mutations = i;
    }
    /**
     * Applies all the mutations in this MutationBatch to the specified document
     * to create a new remote document
     *
     * @param docKey The key of the document to apply mutations to.
     * @param maybeDoc The document to apply mutations to.
     * @param batchResult The result of applying the MutationBatch to the
     * backend.
     */    at(t, e, s) {
        const i = s.En;
        for (let s = 0; s < this.mutations.length; s++) {
            const n = this.mutations[s];
            if (n.key.isEqual(t)) {
                const t = i[s];
                e = n.at(e, t);
            }
        }
        return e;
    }
    /**
     * Computes the local view of a document given all the mutations in this
     * batch.
     *
     * @param docKey The key of the document to apply mutations to.
     * @param maybeDoc The document to apply mutations to.
     */    ot(t, e) {
        // First, apply the base state. This allows us to apply non-idempotent
        // transform against a consistent set of values.
        for (const s of this.baseMutations) s.key.isEqual(t) && (e = s.ot(e, e, this.Tn));
        const s = e;
        // Second, apply all user-provided mutations.
                for (const i of this.mutations) i.key.isEqual(t) && (e = i.ot(e, s, this.Tn));
        return e;
    }
    /**
     * Computes the local view for all provided documents given the mutations in
     * this batch.
     */    In(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).
        let e = t;
        return this.mutations.forEach(s => {
            const i = this.ot(s.key, t.get(s.key));
            i && (e = e.Ae(s.key, i));
        }), e;
    }
    keys() {
        return this.mutations.reduce((t, e) => t.add(e.key), ee());
    }
    isEqual(t) {
        return this.batchId === t.batchId && Fe(this.mutations, t.mutations, (t, e) => t.isEqual(e)) && Fe(this.baseMutations, t.baseMutations, (t, e) => t.isEqual(e));
    }
}

/** The result of applying a mutation batch to the backend. */ class Oe {
    constructor(t, e, s, i, 
    /**
     * A pre-computed mapping from each mutated document to the resulting
     * version.
     */
    n) {
        this.batch = t, this.wn = e, this.En = s, this.streamToken = i, this.Rn = n;
    }
    /**
     * 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=>version mapping (docVersions).
     */    static from(t, e, s, i) {
        ve(t.mutations.length === s.length);
        let n = Zt();
        const r = t.mutations;
        for (let t = 0; t < r.length; t++) n = n.Ae(r[t].key, s[t].version);
        return new Oe(t, e, s, i, 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.
 */
/**
 * 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 xe {
    constructor(t) {
        // NOTE: next/catchCallback will always point to our own wrapper functions,
        // not the user's raw next() or catch() callbacks.
        this.An = null, this.mn = null, 
        // When the operation resolves, we'll set result or error and mark isDone.
        this.result = void 0, this.error = void 0, this.Pn = !1, 
        // Set to true when .then() or .catch() are called and prevents additional
        // chaining.
        this.Vn = !1, t(t => {
            this.Pn = !0, this.result = t, this.An && 
            // value should be defined unless T is Void, but we can't express
            // that in the type system.
            this.An(t);
        }, t => {
            this.Pn = !0, this.error = t, this.mn && this.mn(t);
        });
    }
    catch(t) {
        return this.next(void 0, t);
    }
    next(t, e) {
        return this.Vn && be(), this.Vn = !0, this.Pn ? this.error ? this.gn(e, this.error) : this.pn(t, this.result) : new xe((s, i) => {
            this.An = e => {
                this.pn(t, e).next(s, i);
            }, this.mn = t => {
                this.gn(e, t).next(s, i);
            };
        });
    }
    yn() {
        return new Promise((t, e) => {
            this.next(t, e);
        });
    }
    bn(t) {
        try {
            const e = t();
            return e instanceof xe ? e : xe.resolve(e);
        } catch (t) {
            return xe.reject(t);
        }
    }
    pn(t, e) {
        return t ? this.bn(() => t(e)) : xe.resolve(e);
    }
    gn(t, e) {
        return t ? this.bn(() => t(e)) : xe.reject(e);
    }
    static resolve(t) {
        return new xe((e, s) => {
            e(t);
        });
    }
    static reject(t) {
        return new xe((e, s) => {
            s(t);
        });
    }
    static vn(
    // Accept all Promise types in waitFor().
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    t) {
        return new xe((e, s) => {
            let i = 0, n = 0, r = !1;
            t.forEach(t => {
                ++i, t.next(() => {
                    ++n, r && n === i && e();
                }, t => s(t));
            }), r = !0, n === i && e();
        });
    }
    /**
     * 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 Sn(t) {
        let e = xe.resolve(!1);
        for (const s of t) e = e.next(t => t ? xe.resolve(t) : s());
        return e;
    }
    static forEach(t, e) {
        const s = [];
        return t.forEach((t, i) => {
            s.push(e.call(this, t, i));
        }), this.vn(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.
 */
/**
 * 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 Be {
    constructor() {
        // A mapping of document key to the new cache entry that should be written (or null if any
        // existing cache entry should be removed).
        this.Dn = new Le(t => t.toString()), this.Cn = !1;
    }
    set readTime(t) {
        this.Fn = t;
    }
    get readTime() {
        return this.Fn;
    }
    /**
     * Buffers a `RemoteDocumentCache.addEntry()` call.
     *
     * You can only modify documents that have already been retrieved via
     * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
     */    Nn(t, e) {
        this.$n(), this.readTime = e, this.Dn.set(t.key, t);
    }
    /**
     * Buffers a `RemoteDocumentCache.removeEntry()` call.
     *
     * You can only remove documents that have already been retrieved via
     * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).
     */    kn(t, e) {
        this.$n(), e && (this.readTime = e), this.Dn.set(t, null);
    }
    /**
     * 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.
     * @return The cached Document or NoDocument entry, or null if we have nothing
     * cached.
     */    Ln(t, e) {
        this.$n();
        const s = this.Dn.get(e);
        return void 0 !== s ? xe.resolve(s) : this.Mn(t, e);
    }
    /**
     * 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.
     * @return A map of cached `Document`s or `NoDocument`s, indexed by key. If an
     *     entry cannot be found, the corresponding key will be mapped to a null
     *     value.
     */    getEntries(t, e) {
        return this.On(t, e);
    }
    /**
     * Applies buffered changes to the underlying RemoteDocumentCache, using
     * the provided transaction.
     */    apply(t) {
        return this.$n(), this.Cn = !0, this.xn(t);
    }
    /** Helper to assert this.changes is not null  */    $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.
 */ const qe = "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 Ue {
    constructor() {
        this.Bn = [];
    }
    qn(t) {
        this.Bn.push(t);
    }
    Un() {
        this.Bn.forEach(t => 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 Qe {
    constructor(t, e, s) {
        this.Qn = t, this.Wn = e, this.jn = s;
    }
    /**
     * Get the local view of the document identified by `key`.
     *
     * @return Local view of the document or null if we don't have any cached
     * state for it.
     */    Kn(t, e) {
        return this.Wn.Gn(t, e).next(s => this.zn(t, e, s));
    }
    /** Internal version of `getDocument` that allows reusing batches. */    zn(t, e, s) {
        return this.Qn.Ln(t, e).next(t => {
            for (const i of s) t = i.ot(e, t);
            return t;
        });
    }
    // Returns the view of the given `docs` as they would appear after applying
    // all mutations in the given `batches`.
    Hn(t, e, s) {
        let i = Ht();
        return e.forEach((t, e) => {
            for (const i of s) e = i.ot(t, e);
            i = i.Ae(t, e);
        }), i;
    }
    /**
     * 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.
     */    Yn(t, e) {
        return this.Qn.getEntries(t, e).next(e => this.Jn(t, e));
    }
    /**
     * Similar to `getDocuments`, but creates the local view from the given
     * `baseDocs` without retrieving documents from the local store.
     */    Jn(t, e) {
        return this.Wn.Xn(t, e).next(s => {
            const i = this.Hn(t, e, s);
            let n = zt();
            return i.forEach((t, e) => {
                // TODO(http://b/32275378): Don't conflate missing / deleted.
                e || (e = new gt(t, y.min())), n = n.Ae(t, e);
            }), n;
        });
    }
    /**
     * Performs a query against the local view of all documents.
     *
     * @param transaction The persistence transaction.
     * @param query The query to match documents against.
     * @param sinceReadTime If not set to SnapshotVersion.min(), return only
     *     documents that have been read since this snapshot version (exclusive).
     */    Zn(t, e, s) {
        return e.Ot() ? this.tr(t, e.path) : e._e() ? this.er(t, e, s) : this.sr(t, e, s);
    }
    tr(t, e) {
        // Just do a simple document lookup.
        return this.Kn(t, new C(e)).next(t => {
            let e = Jt();
            return t instanceof Vt && (e = e.Ae(t.key, t)), e;
        });
    }
    er(t, e, s) {
        const i = e.collectionGroup;
        let n = Jt();
        return this.jn.ir(t, i).next(r => xe.forEach(r, r => {
            const h = e.Zt(r.child(i));
            return this.sr(t, h, s).next(t => {
                t.forEach((t, e) => {
                    n = n.Ae(t, e);
                });
            });
        }).next(() => n));
    }
    sr(t, e, s) {
        // Query the remote documents and overlay mutations.
        let i, n;
        return this.Qn.Zn(t, e, s).next(s => (i = s, this.Wn.nr(t, e))).next(e => (n = e, 
        this.rr(t, n, i).next(t => {
            i = t;
            for (const t of n) for (const e of t.mutations) {
                const s = e.key, n = i.get(s), r = e.ot(n, n, t.Tn);
                i = r instanceof Vt ? i.Ae(s, r) : i.remove(s);
            }
        }))).next(() => (
        // Finally, filter out any documents that don't actually match
        // the query.
        i.forEach((t, s) => {
            e.matches(s) || (i = i.remove(t));
        }), i));
    }
    rr(t, e, s) {
        let i = ee();
        for (const t of e) for (const e of t.mutations) e instanceof Tt && null === s.get(e.key) && (i = i.add(e.key));
        let n = s;
        return this.Qn.getEntries(t, i).next(t => (t.forEach((t, e) => {
            null !== e && e instanceof Vt && (n = n.Ae(t, e));
        }), 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 We {
    constructor(t, e, s, i) {
        this.targetId = t, this.fromCache = e, this.hr = s, this.or = i;
    }
    static ar(t, e) {
        let s = ee(), i = ee();
        for (const t of e.docChanges) switch (t.type) {
          case 0 /* Added */ :
            s = s.add(t.doc.key);
            break;

          case 1 /* Removed */ :
            i = i.add(t.doc.key);
 // do nothing
                }
        return new We(t, e.fromCache, s, i);
    }
}

/**
 * @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 je {
    constructor(t, e) {
        this.previousValue = t, e && (e.ur = t => this.cr(t), this._r = t => e.lr(t));
    }
    cr(t) {
        return this.previousValue = Math.max(t, this.previousValue), this.previousValue;
    }
    next() {
        const t = ++this.previousValue;
        return this._r && this._r(t), t;
    }
}

je.dr = -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 Ke {
    constructor() {
        this.promise = new Promise((t, e) => {
            this.resolve = t, this.reject = 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.
 */
/**
 * 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 Ge {
    constructor(
    /**
     * The AsyncQueue to run backoff operations on.
     */
    t, 
    /**
     * The ID to use when scheduling backoff operations on the AsyncQueue.
     */
    e, 
    /**
     * 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.
     */
    s = 1e3
    /**
     * The multiplier to use to determine the extended base delay after each
     * attempt.
     */ , i = 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.
     */ , n = 6e4) {
        this.Tr = t, this.Er = e, this.Ir = s, this.wr = i, this.Rr = n, this.Ar = 0, this.mr = null, 
        /** The last backoff attempt, as epoch milliseconds. */
        this.Pr = 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.Ar = 0;
    }
    /**
     * Resets the backoff delay to the maximum delay (e.g. for use after a
     * RESOURCE_EXHAUSTED error).
     */    Vr() {
        this.Ar = this.Rr;
    }
    /**
     * 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.
     */    gr(t) {
        // Cancel any pending backoff operation.
        this.cancel();
        // First schedule using the current base (which may be 0 and should be
        // honored as such).
        const e = Math.floor(this.Ar + this.pr()), s = Math.max(0, Date.now() - this.Pr), i = Math.max(0, e - s);
        // Guard against lastAttemptTime being in the future due to a clock change.
                i > 0 && ge("ExponentialBackoff", `Backing off for ${i} ms ` + `(base delay: ${this.Ar} ms, ` + `delay with jitter: ${e} ms, ` + `last attempt: ${s} ms ago)`), 
        this.mr = this.Tr.yr(this.Er, i, () => (this.Pr = Date.now(), t())), 
        // Apply backoff factor to determine next delay and ensure it is within
        // bounds.
        this.Ar *= this.wr, this.Ar < this.Ir && (this.Ar = this.Ir), this.Ar > this.Rr && (this.Ar = this.Rr);
    }
    br() {
        null !== this.mr && (this.mr.vr(), this.mr = null);
    }
    cancel() {
        null !== this.mr && (this.mr.cancel(), this.mr = null);
    }
    /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */    pr() {
        return (Math.random() - .5) * this.Ar;
    }
}

/**
 * @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.
 */
/**
 * Encodes a resource path into a IndexedDb-compatible string form.
 */
function ze(t) {
    let e = "";
    for (let s = 0; s < t.length; s++) e.length > 0 && (e = Ye(e)), e = He(t.get(s), e);
    return Ye(e);
}

/** Encodes a single segment of a resource path into the given result */ function He(t, e) {
    let s = e;
    const i = t.length;
    for (let e = 0; e < i; e++) {
        const i = t.charAt(e);
        switch (i) {
          case "\0":
            s += "";
            break;

          case "":
            s += "";
            break;

          default:
            s += i;
        }
    }
    return s;
}

/** Encodes a path separator into the given result */ function Ye(t) {
    return t + "";
}

/**
 * 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 Je(t) {
    // 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 e = t.length;
    if (ve(e >= 2), 2 === e) return ve("" === t.charAt(0) && "" === t.charAt(1)), 
    v.G;
    // Escape characters cannot exist past the second-to-last position in the
    // source value.
        const s = e - 2, i = [];
    let n = "";
    for (let r = 0; r < e; ) {
        // The last two characters of a valid encoded path must be a separator, so
        // there must be an end to this segment.
        const e = t.indexOf("", r);
        switch ((e < 0 || e > s) && be(), t.charAt(e + 1)) {
          case "":
            const s = t.substring(r, e);
            let h;
            0 === n.length ? 
            // Avoid copying for the common case of a segment that excludes \0
            // and \001
            h = s : (n += s, h = n, n = ""), i.push(h);
            break;

          case "":
            n += t.substring(r, e), n += "\0";
            break;

          case "":
            // The escape character can be used in the output to encode itself.
            n += t.substring(r, e + 1);
            break;

          default:
            be();
        }
        r = e + 2;
    }
    return new v(i);
}

/**
 * @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 Xe {
    constructor() {
        this.Sr = new Ze;
    }
    Dr(t, e) {
        return this.Sr.add(e), xe.resolve();
    }
    ir(t, e) {
        return xe.resolve(this.Sr.getEntries(e));
    }
}

/**
 * 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 Ze {
    constructor() {
        this.index = {};
    }
    // Returns false if the entry already existed.
    add(t) {
        const e = t.O(), s = t.L(), i = this.index[e] || new jt(v.N), n = !i.has(s);
        return this.index[e] = i.add(s), n;
    }
    has(t) {
        const e = t.O(), s = t.L(), i = this.index[e];
        return i && i.has(s);
    }
    getEntries(t) {
        return (this.index[t] || new jt(v.N)).W();
    }
}

/**
 * @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.
 */
/**
 * A persisted implementation of IndexManager.
 */ class ts {
    constructor() {
        /**
         * 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.Cr = new Ze;
    }
    /**
     * 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.
     */    Dr(t, e) {
        if (!this.Cr.has(e)) {
            const s = e.O(), i = e.L();
            t.qn(() => {
                // Add the collection to the in memory cache only if the transaction was
                // successfully committed.
                this.Cr.add(e);
            });
            const n = {
                collectionId: s,
                parent: ze(i)
            };
            return es(t).put(n);
        }
        return xe.resolve();
    }
    ir(t, e) {
        const s = [], i = IDBKeyRange.bound([ e, "" ], [ Ne(e), "" ], 
        /*lowerOpen=*/ !1, 
        /*upperOpen=*/ !0);
        return es(t).Fr(i).next(t => {
            for (const i of t) {
                // 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 (i.collectionId !== e) break;
                s.push(Je(i.parent));
            }
            return s;
        });
    }
}

/**
 * Helper to get a typed SimpleDbStore for the collectionParents
 * document store.
 */ function es(t) {
    return Ts.Nr(t, Bs.store);
}

/**
 * @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 ss {
    /**
     * @param {LocalSerializer} serializer The document serializer.
     * @param {IndexManager} indexManager The query indexes that need to be maintained.
     */
    constructor(t, e) {
        this.serializer = t, this.jn = 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.
     */    Nn(t, e, s) {
        return ns(t).put(rs(e), s);
    }
    /**
     * 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.
     */    kn(t, e) {
        const s = ns(t), i = rs(e);
        return s.delete(i);
    }
    /**
     * Updates the current cache size.
     *
     * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the
     * cache's metadata.
     */    updateMetadata(t, e) {
        return this.getMetadata(t).next(s => (s.byteSize += e, this.$r(t, s)));
    }
    Ln(t, e) {
        return ns(t).get(rs(e)).next(t => this.kr(t));
    }
    /**
     * Looks up an entry in the cache.
     *
     * @param documentKey The key of the entry to look up.
     * @return The cached MaybeDocument entry and its size, or null if we have nothing cached.
     */    Lr(t, e) {
        return ns(t).get(rs(e)).next(t => {
            const e = this.kr(t);
            return e ? {
                Mr: e,
                size: hs(t)
            } : null;
        });
    }
    getEntries(t, e) {
        let s = Ht();
        return this.Or(t, e, (t, e) => {
            const i = this.kr(e);
            s = s.Ae(t, i);
        }).next(() => s);
    }
    /**
     * Looks up several entries in the cache.
     *
     * @param documentKeys The set of keys entries to look up.
     * @return A map of MaybeDocuments indexed by key (if a document cannot be
     *     found, the key will be mapped to null) and a map of sizes indexed by
     *     key (zero if the key cannot be found).
     */    xr(t, e) {
        let s = Ht(), i = new Ut(C.N);
        return this.Or(t, e, (t, e) => {
            const n = this.kr(e);
            n ? (s = s.Ae(t, n), i = i.Ae(t, hs(e))) : (s = s.Ae(t, null), i = i.Ae(t, 0));
        }).next(() => ({
            Br: s,
            qr: i
        }));
    }
    Or(t, e, s) {
        if (e.B()) return xe.resolve();
        const i = IDBKeyRange.bound(e.first().path.W(), e.last().path.W()), n = e.be();
        let r = n.Ne();
        return ns(t).Ur({
            range: i
        }, (t, e, i) => {
            const h = C.st(t);
            // Go through keys not found in cache.
                        for (;r && C.N(r, h) < 0; ) s(r, null), r = n.Ne();
            r && r.isEqual(h) && (
            // Key found in cache.
            s(r, e), r = n.$e() ? n.Ne() : null), 
            // Skip to the next key (if there is one).
            r ? i.Qr(r.path.W()) : i.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 (;r; ) s(r, null), r = n.$e() ? n.Ne() : null;
        });
    }
    Zn(t, e, s) {
        let i = Jt();
        const n = e.path.length + 1, r = {};
        if (s.isEqual(y.min())) {
            // Documents are ordered by key, so we can use a prefix scan to narrow
            // down the documents we need to match the query against.
            const t = e.path.W();
            r.range = IDBKeyRange.lowerBound(t);
        } else {
            // Execute an index-free query and filter by read time. This is safe
            // since all document changes to queries that have a
            // lastLimboFreeSnapshotVersion (`sinceReadTime`) have a read time set.
            const t = e.path.W(), i = this.serializer.Wr(s);
            r.range = IDBKeyRange.lowerBound([ t, i ], 
            /* open= */ !0), r.index = ks.collectionReadTimeIndex;
        }
        return ns(t).Ur(r, (t, s, r) => {
            // The query is actually returning any path that starts with the query
            // path prefix which may include documents in subcollections. For
            // example, a query on 'rooms' will return rooms/abc/messages/xyx but we
            // shouldn't match it. Fix this by discarding rows with document keys
            // more than one segment longer than the query path.
            if (t.length !== n) return;
            const h = this.serializer.jr(s);
            e.path.q(h.key.path) ? h instanceof Vt && e.matches(h) && (i = i.Ae(h.key, h)) : r.done();
        }).next(() => i);
    }
    /**
     * Returns the set of documents that have changed since the specified read
     * time.
     */
    // PORTING NOTE: This is only used for multi-tab synchronization.
    Kr(t, e) {
        let s = zt(), i = this.serializer.Wr(e);
        const n = ns(t), r = IDBKeyRange.lowerBound(i, !0);
        return n.Ur({
            index: ks.readTimeIndex,
            range: r
        }, (t, e) => {
            // Unlike `getEntry()` and others, `getNewDocumentChanges()` parses
            // the documents directly since we want to keep sentinel deletes.
            const n = this.serializer.jr(e);
            s = s.Ae(n.key, n), i = e.readTime;
        }).next(() => ({
            Gr: s,
            readTime: this.serializer.zr(i)
        }));
    }
    /**
     * Returns the read time of the most recently read document in the cache, or
     * SnapshotVersion.min() if not available.
     */
    // PORTING NOTE: This is only used for multi-tab synchronization.
    Hr(t) {
        const e = ns(t);
        // If there are no existing entries, we return SnapshotVersion.min().
                let s = y.min();
        return e.Ur({
            index: ks.readTimeIndex,
            reverse: !0
        }, (t, e, i) => {
            e.readTime && (s = this.serializer.zr(e.readTime)), i.done();
        }).next(() => s);
    }
    Yr(t) {
        return new ss.Jr(this, !!t && t.Xr);
    }
    Zr(t) {
        return this.getMetadata(t).next(t => t.byteSize);
    }
    getMetadata(t) {
        return is(t).get(Ls.key).next(t => (ve(!!t), t));
    }
    $r(t, e) {
        return is(t).put(Ls.key, e);
    }
    /**
     * Decodes `remoteDoc` and returns the document (or null, if the document
     * corresponds to the format used for sentinel deletes).
     */    kr(t) {
        if (t) {
            const e = this.serializer.jr(t);
            return e instanceof gt && e.version.isEqual(y.min()) ? null : e;
        }
        return null;
    }
}

/**
 * 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.
 */ function is(t) {
    return Ts.Nr(t, Ls.store);
}

/**
 * Helper to get a typed SimpleDbStore for the remoteDocuments object store.
 */ function ns(t) {
    return Ts.Nr(t, ks.store);
}

function rs(t) {
    return t.path.W();
}

/**
 * Retrusn an approximate size for the given document.
 */ function hs(t) {
    let e;
    if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {
        if (!t.noDocument) throw be();
        e = t.noDocument;
    }
    return JSON.stringify(e).length;
}

/**
 * @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. */ ss.Jr = class extends Be {
    /**
     * @param documentCache The IndexedDbRemoteDocumentCache to apply the changes to.
     * @param trackRemovals Whether to create sentinel deletes that can be tracked by
     * `getNewDocumentChanges()`.
     */
    constructor(t, e) {
        super(), this.th = t, this.Xr = e, 
        // A map of document sizes prior to applying the changes in this buffer.
        this.eh = new Le(t => t.toString());
    }
    xn(t) {
        const e = [];
        let s = 0, i = new jt((t, e) => Ce(t.j(), e.j()));
        return this.Dn.forEach((n, r) => {
            const h = this.eh.get(n);
            if (r) {
                const o = this.th.serializer.sh(r, this.readTime);
                i = i.add(n.path.L());
                const a = hs(o);
                s += a - h, e.push(this.th.Nn(t, n, o));
            } else if (s -= h, this.Xr) {
                // 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 s = this.th.serializer.sh(new gt(n, y.min()), this.readTime);
                e.push(this.th.Nn(t, n, s));
            } else e.push(this.th.kn(t, n));
        }), i.forEach(s => {
            e.push(this.th.jn.Dr(t, s));
        }), e.push(this.th.updateMetadata(t, s)), xe.vn(e);
    }
    Mn(t, e) {
        // Record the size of everything we load from the cache so we can compute a delta later.
        return this.th.Lr(t, e).next(t => null === t ? (this.eh.set(e, 0), null) : (this.eh.set(e, t.size), 
        t.Mr));
    }
    On(t, e) {
        // Record the size of everything we load from the cache so we can compute
        // a delta later.
        return this.th.xr(t, e).next(({Br: t, qr: e}) => (
        // Note: `getAllFromCache` returns two maps instead of a single map from
        // keys to `DocumentSizeEntry`s. This is to allow returning the
        // `NullableMaybeDocumentMap` directly, without a conversion.
        e.forEach((t, e) => {
            this.eh.set(t, e);
        }), t));
    }
};

/**
 * 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 os {
    constructor(t) {
        this.ih = t;
    }
    next() {
        return this.ih += 2, this.ih;
    }
    static nh() {
        // 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 os(0);
    }
    static rh() {
        // Sync engine assigns target IDs for limbo document detection.
        return new os(-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 as {
    constructor(t, e) {
        this.hh = t, this.serializer = e;
    }
    // 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.
    oh(t) {
        return this.ah(t).next(e => {
            const s = new os(e.highestTargetId);
            return e.highestTargetId = s.next(), this.uh(t, e).next(() => e.highestTargetId);
        });
    }
    _h(t) {
        return this.ah(t).next(t => y.v(new p(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds)));
    }
    lh(t) {
        return this.ah(t).next(t => t.highestListenSequenceNumber);
    }
    dh(t, e, s) {
        return this.ah(t).next(i => (i.highestListenSequenceNumber = e, s && (i.lastRemoteSnapshotVersion = s.C()), 
        e > i.highestListenSequenceNumber && (i.highestListenSequenceNumber = e), this.uh(t, i)));
    }
    fh(t, e) {
        return this.Th(t, e).next(() => this.ah(t).next(s => (s.targetCount += 1, this.Eh(e, s), 
        this.uh(t, s))));
    }
    Ih(t, e) {
        return this.Th(t, e);
    }
    wh(t, e) {
        return this.Rh(t, e.targetId).next(() => us(t).delete(e.targetId)).next(() => this.ah(t)).next(e => (ve(e.targetCount > 0), 
        e.targetCount -= 1, this.uh(t, e)));
    }
    /**
     * 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.
     */    Ah(t, e, s) {
        let i = 0;
        const n = [];
        return us(t).Ur((r, h) => {
            const o = this.serializer.mh(h);
            o.sequenceNumber <= e && null === s.get(o.targetId) && (i++, n.push(this.wh(t, o)));
        }).next(() => xe.vn(n)).next(() => i);
    }
    /**
     * Call provided function with each `TargetData` that we have cached.
     */    js(t, e) {
        return us(t).Ur((t, s) => {
            const i = this.serializer.mh(s);
            e(i);
        });
    }
    ah(t) {
        return cs(t).get(xs.key).next(t => (ve(null !== t), t));
    }
    uh(t, e) {
        return cs(t).put(xs.key, e);
    }
    Th(t, e) {
        return us(t).put(this.serializer.Ph(e));
    }
    /**
     * 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.
     */    Eh(t, e) {
        let s = !1;
        return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, s = !0), 
        t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber, 
        s = !0), s;
    }
    Vh(t) {
        return this.ah(t).next(t => t.targetCount);
    }
    gh(t, e) {
        // 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 s = e.canonicalId(), i = IDBKeyRange.bound([ s, Number.NEGATIVE_INFINITY ], [ s, Number.POSITIVE_INFINITY ]);
        let n = null;
        return us(t).Ur({
            range: i,
            index: Ms.queryTargetsIndexName
        }, (t, s, i) => {
            const r = this.serializer.mh(s);
            // After finding a potential match, check that the target is
            // actually equal to the requested target.
                        e.isEqual(r.target) && (n = r, i.done());
        }).next(() => n);
    }
    ph(t, e, s) {
        // PORTING NOTE: The reverse index (documentsTargets) is maintained by
        // IndexedDb.
        const i = [], n = _s(t);
        return e.forEach(e => {
            const r = ze(e.path);
            i.push(n.put(new Os(s, r))), i.push(this.hh.yh(t, s, e));
        }), xe.vn(i);
    }
    bh(t, e, s) {
        // PORTING NOTE: The reverse index (documentsTargets) is maintained by
        // IndexedDb.
        const i = _s(t);
        return xe.forEach(e, e => {
            const n = ze(e.path);
            return xe.vn([ i.delete([ s, n ]), this.hh.vh(t, s, e) ]);
        });
    }
    Rh(t, e) {
        const s = _s(t), i = IDBKeyRange.bound([ e ], [ e + 1 ], 
        /*lowerOpen=*/ !1, 
        /*upperOpen=*/ !0);
        return s.delete(i);
    }
    Sh(t, e) {
        const s = IDBKeyRange.bound([ e ], [ e + 1 ], 
        /*lowerOpen=*/ !1, 
        /*upperOpen=*/ !0), i = _s(t);
        let n = ee();
        return i.Ur({
            range: s,
            Dh: !0
        }, (t, e, s) => {
            const i = Je(t[1]), r = new C(i);
            n = n.add(r);
        }).next(() => n);
    }
    Ch(t, e) {
        const s = ze(e.path), i = IDBKeyRange.bound([ s ], [ Ne(s) ], 
        /*lowerOpen=*/ !1, 
        /*upperOpen=*/ !0);
        let n = 0;
        return _s(t).Ur({
            index: Os.documentTargetsIndex,
            Dh: !0,
            range: i
        }, ([t, e], s, i) => {
            // 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 !== t && (n++, i.done());
        }).next(() => n > 0);
    }
    /**
     * Looks up a TargetData entry by target ID.
     *
     * @param targetId The target ID of the TargetData entry to look up.
     * @return The cached TargetData entry, or null if the cache has no entry for
     * the target.
     */
    // PORTING NOTE: Multi-tab only.
    si(t, e) {
        return us(t).get(e).next(t => t ? this.serializer.mh(t) : null);
    }
}

/**
 * Helper to get a typed SimpleDbStore for the queries object store.
 */ function us(t) {
    return Ts.Nr(t, Ms.store);
}

/**
 * Helper to get a typed SimpleDbStore for the target globals object store.
 */ function cs(t) {
    return Ts.Nr(t, xs.store);
}

/**
 * Helper to get a typed SimpleDbStore for the document target object store.
 */ function _s(t) {
    return Ts.Nr(t, Os.store);
}

/**
 * @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 ls {
    constructor(t) {
        this.Fh = t;
    }
    /** Decodes a remote document from storage locally to a Document. */    jr(t) {
        if (t.document) return this.Fh.mi(t.document, !!t.hasCommittedMutations);
        if (t.noDocument) {
            const e = C.st(t.noDocument.path), s = this.Nh(t.noDocument.readTime);
            return new gt(e, s, {
                hasCommittedMutations: !!t.hasCommittedMutations
            });
        }
        if (t.unknownDocument) {
            const e = C.st(t.unknownDocument.path), s = this.Nh(t.unknownDocument.version);
            return new pt(e, s);
        }
        return be();
    }
    /** Encodes a document for storage locally. */    sh(t, e) {
        const s = this.Wr(e), i = t.key.path.L().W();
        if (t instanceof Vt) {
            const e = this.Fh.Ai(t), n = t.hasCommittedMutations;
            return new ks(
            /* unknownDocument= */ null, 
            /* noDocument= */ null, e, n, s, i);
        }
        if (t instanceof gt) {
            const e = t.key.path.W(), n = this.$h(t.version), r = t.hasCommittedMutations;
            return new ks(
            /* unknownDocument= */ null, new Ns(e, n), 
            /* document= */ null, r, s, i);
        }
        if (t instanceof pt) {
            const e = t.key.path.W(), n = this.$h(t.version);
            return new ks(new $s(e, n), 
            /* noDocument= */ null, 
            /* document= */ null, 
            /* hasCommittedMutations= */ !0, s, i);
        }
        return be();
    }
    Wr(t) {
        const e = t.C();
        return [ e.seconds, e.nanoseconds ];
    }
    zr(t) {
        const e = new p(t[0], t[1]);
        return y.v(e);
    }
    $h(t) {
        const e = t.C();
        return new vs(e.seconds, e.nanoseconds);
    }
    Nh(t) {
        const e = new p(t.seconds, t.nanoseconds);
        return y.v(e);
    }
    /** Encodes a batch of mutations into a DbMutationBatch for local storage. */    kh(t, e) {
        const s = e.baseMutations.map(t => this.Fh.vi(t)), i = e.mutations.map(t => this.Fh.vi(t));
        return new Cs(t, e.batchId, e.Tn.toMillis(), s, i);
    }
    /** Decodes a DbMutationBatch into a MutationBatch */    Lh(t) {
        const e = (t.baseMutations || []).map(t => this.Fh.Fi(t)), s = t.mutations.map(t => this.Fh.Fi(t)), i = p.fromMillis(t.localWriteTimeMs);
        return new Me(t.batchId, i, e, s);
    }
    /** Decodes a DbTarget into TargetData */    mh(t) {
        const e = this.Nh(t.readTime), s = void 0 !== t.lastLimboFreeSnapshotVersion ? this.Nh(t.lastLimboFreeSnapshotVersion) : y.min();
        let i;
        return i = void 0 !== t.query.documents ? this.Fh.xi(t.query) : this.Fh.Wi(t.query), 
        new Lt(i, t.targetId, 0 /* Listen */ , t.lastListenSequenceNumber, e, s, k.fromBase64String(t.resumeToken));
    }
    /** Encodes TargetData into a DbTarget for storage locally. */    Ph(t) {
        const e = this.$h(t.Ee), s = this.$h(t.lastLimboFreeSnapshotVersion);
        let i;
        i = t.target.Ot() ? this.Fh.Oi(t.target) : this.Fh.Bi(t.target);
        // We can't store the resumeToken as a ByteString in IndexedDb, so we
        // convert it to a base64 string for storage.
                const n = t.resumeToken.toBase64();
        // lastListenSequenceNumber is always 0 until we do real GC.
                return new Ms(t.targetId, t.target.canonicalId(), e, n, t.sequenceNumber, s, i);
    }
}

/**
 * A helper function for figuring out what kind of query has been stored.
 */
/**
 * @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 ds = "Failed to obtain exclusive access to the persistence layer. To allow shared access, make sure to invoke `enablePersistence()` with `synchronizeTabs:true` in all tabs.";

/**
 * Oldest acceptable age in milliseconds for client metadata before the client
 * is considered inactive and its associated data is garbage collected.
 */ class fs extends Ue {
    constructor(t, e) {
        super(), this.Mh = t, this.Oh = e;
    }
}

/**
 * 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 Ts {
    constructor(t, e, s, i, n, r, h, o) {
        if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = s, 
        this.Tr = r, this.xh = o, this.Bh = null, this.qh = !1, this.isPrimary = !1, this.networkEnabled = !0, 
        /** Our window.unload handler, if registered. */
        this.Uh = null, this.inForeground = !1, 
        /** Our 'visibilitychange' listener if registered. */
        this.Qh = null, 
        /** The client metadata refresh task. */
        this.Wh = null, 
        /** The last time we garbage collected the client metadata object store. */
        this.jh = Number.NEGATIVE_INFINITY, 
        /** A listener to notify on primary state changes. */
        this.Kh = t => Promise.resolve(), !Ts.Gh()) throw new R(w.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.");
        if (this.hh = new ws(this, n), this.zh = e + Ts.Hh, this.serializer = new ls(h), 
        this.document = i.document, this.Yh = new as(this.hh, this.serializer), this.jn = new ts, 
        this.Qn = new ss(this.serializer, this.jn), !i.window || !i.window.localStorage) throw new R(w.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
        this.window = i.window, this.Jh = this.window.localStorage;
    }
    static Nr(t, e) {
        if (t instanceof fs) return Ws.Nr(t.Mh, e);
        throw be();
    }
    /**
     * Attempt to start IndexedDb persistence.
     *
     * @return {Promise<void>} Whether persistence was enabled.
     */    start() {
        return Ws.Xh(this.zh, ys, new bs(this.serializer)).then(t => (this.Zh = t, this.to())).then(() => {
            if (!this.isPrimary && !this.allowTabSynchronization) 
            // Fail `start()` if `synchronizeTabs` is disabled and we cannot
            // obtain the primary lease.
            throw new R(w.FAILED_PRECONDITION, ds);
            return this.eo(), this.so(), this.io(), this.runTransaction("getHighestListenSequenceNumber", "readonly", t => this.Yh.lh(t));
        }).then(t => {
            this.Bh = new je(t, this.xh);
        }).then(() => {
            this.qh = !0;
        }).catch(t => (this.Zh && this.Zh.close(), Promise.reject(t)));
    }
    /**
     * 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.
     */    no(t) {
        return this.Kh = async e => {
            if (this.ro) return t(e);
        }, t(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.
     */    ho(t) {
        this.Zh.oo(async e => {
            // Check if an attempt is made to delete IndexedDB.
            null === e.newVersion && await t();
        });
    }
    /**
     * 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.
     */    ao(t) {
        this.networkEnabled !== t && (this.networkEnabled = t, 
        // Schedule a primary lease refresh for immediate execution. The eventual
        // lease update will be propagated via `primaryStateListener`.
        this.Tr.uo(async () => {
            this.ro && await this.to();
        }));
    }
    /**
     * 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.
     */    to() {
        return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", t => Is(t).put(new Us(this.clientId, Date.now(), this.networkEnabled, this.inForeground)).next(() => {
            if (this.isPrimary) return this.co(t).next(t => {
                t || (this.isPrimary = !1, this.Tr.uo(() => this.Kh(!1)));
            });
        }).next(() => this._o(t)).next(e => this.isPrimary && !e ? this.lo(t).next(() => !1) : !!e && this.do(t).next(() => !0))).catch(t => {
            if (!this.allowTabSynchronization) {
                if (Gs(t)) 
                // Proceed with the existing state. Any subsequent access to
                // IndexedDB will verify the lease.
                return ge("IndexedDbPersistence", "Failed to extend owner lease: ", t), this.isPrimary;
                throw t;
            }
            return ge("IndexedDbPersistence", "Releasing owner lease after error during lease refresh", t), 
            /* isPrimary= */ !1;
        }).then(t => {
            this.isPrimary !== t && this.Tr.uo(() => this.Kh(t)), this.isPrimary = t;
        });
    }
    co(t) {
        return Es(t).get(Ss.key).next(t => xe.resolve(this.fo(t)));
    }
    To(t) {
        return Is(t).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 Eo() {
        if (this.isPrimary && !this.Io(this.jh, 18e5)) {
            this.jh = Date.now(), 
            // 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.
            (await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", t => {
                const e = Ts.Nr(t, Us.store);
                return e.Fr().next(t => {
                    const s = this.wo(t, 18e5), i = t.filter(t => -1 === s.indexOf(t));
                    // Delete metadata for clients that are no longer considered active.
                    return xe.forEach(i, t => e.delete(t.clientId)).next(() => i);
                });
            }).catch(() => [])).forEach(t => {
                this.window.localStorage.removeItem(this.Ro(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.
     */    io() {
        this.Wh = this.Tr.yr("client_metadata_refresh" /* ClientMetadataRefresh */ , 4e3, () => this.to().then(() => this.Eo()).then(() => this.io()));
    }
    /** Checks whether `client` is the local client. */    fo(t) {
        return !!t && t.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.
     */    _o(t) {
        return Es(t).get(Ss.key).next(e => {
            // 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.
            if (null !== e && this.Io(e.leaseTimestampMs, 5e3) && !this.Ao(e.ownerId)) {
                if (this.fo(e) && this.networkEnabled) return !0;
                if (!this.fo(e)) {
                    if (!e.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 R(w.FAILED_PRECONDITION, ds);
                    return !1;
                }
            }
            return !(!this.networkEnabled || !this.inForeground) || Is(t).Fr().next(t => void 0 === this.wo(t, 5e3).find(t => {
                if (this.clientId !== t.clientId) {
                    const e = !this.networkEnabled && t.networkEnabled, s = !this.inForeground && t.inForeground, i = this.networkEnabled === t.networkEnabled;
                    if (e || s && i) return !0;
                }
                return !1;
            }));
        }).next(t => (this.isPrimary !== t && ge("IndexedDbPersistence", `Client ${t ? "is" : "is not"} eligible for a primary lease.`), 
        t));
    }
    async mo() {
        // The shutdown() operations are idempotent and can be called even when
        // start() aborted (e.g. because it couldn't acquire the persistence lease).
        this.qh = !1, this.Po(), this.Wh && (this.Wh.cancel(), this.Wh = null), this.Vo(), 
        this.po(), await this.runTransaction("shutdown", "readwrite", t => this.lo(t).next(() => this.To(t))).catch(t => {
            ge("IndexedDbPersistence", "Proceeding with shutdown despite failure: ", t);
        }), this.Zh.close(), 
        // Remove the entry marking the client as zombied from LocalStorage since
        // we successfully deleted its metadata from IndexedDb.
        this.yo();
    }
    /**
     * Returns clients that are not zombied and have an updateTime within the
     * provided threshold.
     */    wo(t, e) {
        return t.filter(t => this.Io(t.updateTimeMs, e) && !this.Ao(t.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.
     */    bo() {
        return this.runTransaction("getActiveClients", "readonly", t => Is(t).Fr().next(t => this.wo(t, 18e5).map(t => t.clientId)));
    }
    static async clearPersistence(t) {
        if (!Ts.Gh()) return Promise.resolve();
        const e = t + Ts.Hh;
        await Ws.delete(e);
    }
    get ro() {
        return this.qh;
    }
    vo(t) {
        return As.So(t, this.serializer, this.jn, this.hh);
    }
    Do() {
        return this.Yh;
    }
    Co() {
        return this.Qn;
    }
    Fo() {
        return this.jn;
    }
    runTransaction(t, e, s) {
        ge("IndexedDbPersistence", "Starting transaction:", t);
        const i = "readonly" === e ? "readonly" : "readwrite";
        let n;
        // Do all transactions as readwrite against all object stores, since we
        // are the only reader/writer.
                return this.Zh.runTransaction(i, Qs, i => (n = new fs(i, this.Bh ? this.Bh.next() : je.dr), 
        "readwrite-primary" === e ? this.co(n).next(t => !!t || this._o(n)).next(e => {
            if (!e) throw pe(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1, 
            this.Tr.uo(() => this.Kh(!1)), new R(w.FAILED_PRECONDITION, qe);
            return s(n);
        }).next(t => this.do(n).next(() => t)) : this.No(n).next(() => s(n)))).then(t => (n.Un(), 
        t));
    }
    /**
     * 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.
    No(t) {
        return Es(t).get(Ss.key).next(t => {
            if (null !== t && this.Io(t.leaseTimestampMs, 5e3) && !this.Ao(t.ownerId) && !this.fo(t) && (!this.allowTabSynchronization || !t.allowTabSynchronization)) throw new R(w.FAILED_PRECONDITION, ds);
        });
    }
    /**
     * Obtains or extends the new primary lease for the local client. This
     * method does not verify that the client is eligible for this lease.
     */    do(t) {
        const e = new Ss(this.clientId, this.allowTabSynchronization, Date.now());
        return Es(t).put(Ss.key, e);
    }
    static Gh() {
        return Ws.Gh();
    }
    /**
     * Generates a string used as a prefix when storing data in IndexedDB and
     * LocalStorage.
     */    static $o(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 e = t.ii.projectId;
        return t.ii.ln || (e += "." + t.ii.database), "firestore/" + t.persistenceKey + "/" + e + "/";
    }
    /** Checks the primary lease and removes it if we are the current primary. */    lo(t) {
        const e = Es(t);
        return e.get(Ss.key).next(t => this.fo(t) ? (ge("IndexedDbPersistence", "Releasing primary lease."), 
        e.delete(Ss.key)) : xe.resolve());
    }
    /** Verifies that `updateTimeMs` is within `maxAgeMs`. */    Io(t, e) {
        const s = Date.now();
        return !(t < s - e) && (!(t > s) || (pe(`Detected an update time that is in the future: ${t} > ${s}`), 
        !1));
    }
    eo() {
        null !== this.document && "function" == typeof this.document.addEventListener && (this.Qh = () => {
            this.Tr.uo(() => (this.inForeground = "visible" === this.document.visibilityState, 
            this.to()));
        }, this.document.addEventListener("visibilitychange", this.Qh), this.inForeground = "visible" === this.document.visibilityState);
    }
    Vo() {
        this.Qh && (this.document.removeEventListener("visibilitychange", this.Qh), this.Qh = 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.
     */    so() {
        "function" == typeof this.window.addEventListener && (this.Uh = () => {
            // 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.Po(), this.Tr.uo(() => this.mo());
        }, this.window.addEventListener("unload", this.Uh));
    }
    po() {
        this.Uh && (this.window.removeEventListener("unload", this.Uh), this.Uh = 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()`.
     */    Ao(t) {
        try {
            const e = null !== this.Jh.getItem(this.Ro(t));
            return ge("IndexedDbPersistence", `Client '${t}' ${e ? "is" : "is not"} zombied in LocalStorage`), 
            e;
        } catch (t) {
            // Gracefully handle if LocalStorage isn't working.
            return pe("IndexedDbPersistence", "Failed to get zombied client id.", t), !1;
        }
    }
    /**
     * Record client as zombied (a client that had its tab closed). Zombied
     * clients are ignored during primary tab selection.
     */    Po() {
        try {
            this.Jh.setItem(this.Ro(this.clientId), String(Date.now()));
        } catch (t) {
            // Gracefully handle if LocalStorage isn't available / working.
            pe("Failed to set zombie client id.", t);
        }
    }
    /** Removes the zombied client entry if it exists. */    yo() {
        try {
            this.Jh.removeItem(this.Ro(this.clientId));
        } catch (t) {
            // Ignore
        }
    }
    Ro(t) {
        return `firestore_zombie_${this.persistenceKey}_${t}`;
    }
}

/**
 * The name of the main (and currently only) IndexedDB database. this name is
 * appended to the prefix provided to the IndexedDbPersistence constructor.
 */
/**
 * Helper to get a typed SimpleDbStore for the primary client object store.
 */
function Es(t) {
    return Ts.Nr(t, Ss.store);
}

/**
 * Helper to get a typed SimpleDbStore for the client metadata object store.
 */ function Is(t) {
    return Ts.Nr(t, Us.store);
}

/** Provides LRU functionality for IndexedDB persistence. */ Ts.Hh = "main";

class ws {
    constructor(t, e) {
        this.db = t, this.ko = new oi(this, e);
    }
    Lo(t) {
        const e = this.Mo(t);
        return this.db.Do().Vh(t).next(t => e.next(e => t + e));
    }
    Mo(t) {
        let e = 0;
        return this.Oo(t, t => {
            e++;
        }).next(() => e);
    }
    js(t, e) {
        return this.db.Do().js(t, e);
    }
    Oo(t, e) {
        return this.xo(t, (t, s) => e(s));
    }
    yh(t, e, s) {
        return Rs(t, s);
    }
    vh(t, e, s) {
        return Rs(t, s);
    }
    Ah(t, e, s) {
        return this.db.Do().Ah(t, e, s);
    }
    Bo(t, e) {
        return Rs(t, e);
    }
    /**
     * 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.
     */    qo(t, e) {
        /** Returns true if any mutation queue contains the given document. */
        return function(t, e) {
            let s = !1;
            return ps(t).Uo(i => ms(t, i, e).next(t => (t && (s = !0), xe.resolve(!t)))).next(() => s);
        }
        /**
 * Delete a mutation batch and the associated document mutations.
 * @return A PersistencePromise of the document mutations that were removed.
 */ (t, e);
    }
    Qo(t, e) {
        const s = this.db.Co().Yr(), i = [];
        let n = 0;
        return this.xo(t, (r, h) => {
            if (h <= e) {
                const e = this.qo(t, r).next(e => {
                    if (!e) 
                    // Our size accounting requires us to read all documents before
                    // removing them.
                    return n++, s.Ln(t, r).next(() => (s.kn(r), _s(t).delete([ 0, ze(r.path) ])));
                });
                i.push(e);
            }
        }).next(() => xe.vn(i)).next(() => s.apply(t)).next(() => n);
    }
    removeTarget(t, e) {
        const s = e.Ie(t.Oh);
        return this.db.Do().Ih(t, s);
    }
    Wo(t, e) {
        return Rs(t, e);
    }
    /**
     * 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.
     */    xo(t, e) {
        const s = _s(t);
        let i, n = je.dr;
        return s.Ur({
            index: Os.documentTargetsIndex
        }, ([t, s], {path: r, sequenceNumber: h}) => {
            0 === t ? (
            // if nextToReport is valid, report it, this is a new key so the
            // last one must not be a member of any targets.
            n !== je.dr && e(new C(Je(i)), n), 
            // 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.
            n = h, i = r) : 
            // set nextToReport to be invalid, we know we don't need to report
            // this one since we found a target for it.
            n = je.dr;
        }).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.
            n !== je.dr && e(new C(Je(i)), n);
        });
    }
    jo(t) {
        return this.db.Co().Zr(t);
    }
}

function Rs(t, e) {
    return _s(t).put(
    /**
 * @return A value suitable for writing a sentinel row in the target-document
 * store.
 */
    function(t, e) {
        return new Os(0, ze(t.path), e);
    }(e, t.Oh));
}

/**
 * @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. */ class As {
    constructor(
    /**
     * The normalized userId (e.g. null UID => "" userId) used to store /
     * retrieve mutations.
     */
    t, e, s, i) {
        this.userId = t, this.serializer = e, this.jn = s, this.hh = i, 
        /**
         * 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.Ko = {};
    }
    /**
     * 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 So(t, e, s, i) {
        // 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.
        ve("" !== t.uid);
        const n = t.t() ? t.uid : "";
        return new As(n, e, s, i);
    }
    Go(t) {
        let e = !0;
        const s = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);
        return Vs(t).Ur({
            index: Cs.userMutationsIndex,
            range: s
        }, (t, s, i) => {
            e = !1, i.done();
        }).next(() => e);
    }
    zo(t, e, s) {
        return this.Ho(t).next(e => (
        // We can't store the resumeToken as a ByteString in IndexedDB, so we
        // convert it to a Base64 string for storage.
        e.lastStreamToken = s.toBase64(), ps(t).put(e)));
    }
    Yo(t) {
        return this.Ho(t).next(t => k.fromBase64String(t.lastStreamToken));
    }
    Jo(t, e) {
        return this.Ho(t).next(s => (
        // We can't store the resumeToken as a ByteString in IndexedDB, so we
        // convert it to a Base64 string for storage.
        s.lastStreamToken = e.toBase64(), ps(t).put(s)));
    }
    Xo(t, e, s, i) {
        const n = gs(t), r = Vs(t);
        // 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 r.add({}).next(h => {
            ve("number" == typeof h);
            const o = new Me(h, e, s, i), a = this.serializer.kh(this.userId, o), u = [];
            let c = new jt((t, e) => Ce(t.j(), e.j()));
            for (const t of i) {
                const e = Fs.key(this.userId, t.key.path, h);
                c = c.add(t.key.path.L()), u.push(r.put(a)), u.push(n.put(e, Fs.PLACEHOLDER));
            }
            return c.forEach(e => {
                u.push(this.jn.Dr(t, e));
            }), t.qn(() => {
                this.Ko[h] = o.keys();
            }), xe.vn(u).next(() => o);
        });
    }
    Zo(t, e) {
        return Vs(t).get(e).next(t => t ? (ve(t.userId === this.userId), this.serializer.Lh(t)) : 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.
    ta(t, e) {
        return this.Ko[e] ? xe.resolve(this.Ko[e]) : this.Zo(t, e).next(t => {
            if (t) {
                const s = t.keys();
                return this.Ko[e] = s, s;
            }
            return null;
        });
    }
    ea(t, e) {
        const s = e + 1, i = IDBKeyRange.lowerBound([ this.userId, s ]);
        let n = null;
        return Vs(t).Ur({
            index: Cs.userMutationsIndex,
            range: i
        }, (t, e, i) => {
            e.userId === this.userId && (ve(e.batchId >= s), n = this.serializer.Lh(e)), i.done();
        }).next(() => n);
    }
    sa(t) {
        const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);
        let s = -1;
        return Vs(t).Ur({
            index: Cs.userMutationsIndex,
            range: e,
            reverse: !0
        }, (t, e, i) => {
            s = e.batchId, i.done();
        }).next(() => s);
    }
    ia(t) {
        const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);
        return Vs(t).Fr(Cs.userMutationsIndex, e).next(t => t.map(t => this.serializer.Lh(t)));
    }
    Gn(t, e) {
        // Scan the document-mutation index starting with a prefix starting with
        // the given documentKey.
        const s = Fs.prefixForPath(this.userId, e.path), i = IDBKeyRange.lowerBound(s), n = [];
        return gs(t).Ur({
            range: i
        }, (s, i, r) => {
            const [h, o, a] = s, u = Je(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 (h === this.userId && e.path.isEqual(u)) 
            // Look up the mutation batch in the store.
            return Vs(t).get(a).next(t => {
                if (!t) throw be();
                ve(t.userId === this.userId), n.push(this.serializer.Lh(t));
            });
            r.done();
        }).next(() => n);
    }
    Xn(t, e) {
        let s = new jt(Ce);
        const i = [];
        return e.forEach(e => {
            const n = Fs.prefixForPath(this.userId, e.path), r = IDBKeyRange.lowerBound(n), h = gs(t).Ur({
                range: r
            }, (t, i, n) => {
                const [r, h, o] = t, a = Je(h);
                // 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.
                                r === this.userId && e.path.isEqual(a) ? s = s.add(o) : n.done();
            });
            i.push(h);
        }), xe.vn(i).next(() => this.na(t, s));
    }
    nr(t, e) {
        const s = e.path, i = s.length + 1, n = Fs.prefixForPath(this.userId, s), r = IDBKeyRange.lowerBound(n);
        // 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 h = new jt(Ce);
        return gs(t).Ur({
            range: r
        }, (t, e, n) => {
            const [r, o, a] = t, u = Je(o);
            r === this.userId && s.q(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 === i && (h = h.add(a)) : n.done();
        }).next(() => this.na(t, h));
    }
    na(t, e) {
        const s = [], i = [];
        // TODO(rockwood): Implement this using iterate.
        return e.forEach(e => {
            i.push(Vs(t).get(e).next(t => {
                if (null === t) throw be();
                ve(t.userId === this.userId), s.push(this.serializer.Lh(t));
            }));
        }), xe.vn(i).next(() => s);
    }
    ra(t, e) {
        return Ps(t.Mh, this.userId, e).next(s => (t.qn(() => {
            this.ha(e.batchId);
        }), xe.forEach(s, e => this.hh.Bo(t, e))));
    }
    /**
     * 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
    ha(t) {
        delete this.Ko[t];
    }
    oa(t) {
        return this.Go(t).next(e => {
            if (!e) return xe.resolve();
            // Verify that there are no entries in the documentMutations index if
            // the queue is empty.
                        const s = IDBKeyRange.lowerBound(Fs.prefixForUser(this.userId)), i = [];
            return gs(t).Ur({
                range: s
            }, (t, e, s) => {
                if (t[0] === this.userId) {
                    const e = Je(t[1]);
                    i.push(e);
                } else s.done();
            }).next(() => {
                ve(0 === i.length);
            });
        });
    }
    Ch(t, e) {
        return ms(t, this.userId, e);
    }
    // PORTING NOTE: Multi-tab only (state is held in memory in other clients).
    /** Returns the mutation queue's metadata from IndexedDb. */
    Ho(t) {
        return ps(t).get(this.userId).next(t => t || new Ds(this.userId, -1, 
        /*lastStreamToken=*/ ""));
    }
}

/**
 * @return true if the mutation queue for the given user contains a pending
 *         mutation for the given key.
 */ function ms(t, e, s) {
    const i = Fs.prefixForPath(e, s.path), n = i[1], r = IDBKeyRange.lowerBound(i);
    let h = !1;
    return gs(t).Ur({
        range: r,
        Dh: !0
    }, (t, s, i) => {
        const [r, o, /*batchID*/ a] = t;
        r === e && o === n && (h = !0), i.done();
    }).next(() => h);
}

function Ps(t, e, s) {
    const i = t.store(Cs.store), n = t.store(Fs.store), r = [], h = IDBKeyRange.only(s.batchId);
    let o = 0;
    const a = i.Ur({
        range: h
    }, (t, e, s) => (o++, s.delete()));
    r.push(a.next(() => {
        ve(1 === o);
    }));
    const u = [];
    for (const t of s.mutations) {
        const i = Fs.key(e, t.key.path, s.batchId);
        r.push(n.delete(i)), u.push(t.key);
    }
    return xe.vn(r).next(() => u);
}

/**
 * Helper to get a typed SimpleDbStore for the mutations object store.
 */ function Vs(t) {
    return Ts.Nr(t, Cs.store);
}

/**
 * Helper to get a typed SimpleDbStore for the mutationQueues object store.
 */ function gs(t) {
    return Ts.Nr(t, Fs.store);
}

/**
 * Helper to get a typed SimpleDbStore for the mutationQueues object store.
 */ function ps(t) {
    return Ts.Nr(t, Ds.store);
}

/**
 * @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.
 */ const ys = 10;

/** Performs database creation and schema upgrades. */ class bs {
    constructor(t) {
        this.serializer = t;
    }
    /**
     * 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.
     */    createOrUpgrade(t, e, s, i) {
        ve(s < i && s >= 0 && i <= ys);
        const n = new zs(e);
        s < 1 && i >= 1 && (function(t) {
            t.createObjectStore(Ss.store);
        }
        /**
 * An object to be stored in the 'mutationQueues' store in IndexedDb.
 *
 * Each user gets a single queue of MutationBatches to apply to the server.
 * DbMutationQueue tracks the metadata about the queue.
 */ (t), function(t) {
            t.createObjectStore(Ds.store, {
                keyPath: Ds.keyPath
            }), t.createObjectStore(Cs.store, {
                keyPath: Cs.keyPath,
                autoIncrement: !0
            }).createIndex(Cs.userMutationsIndex, Cs.userMutationsKeyPath, {
                unique: !0
            }), t.createObjectStore(Fs.store);
        }
        /**
 * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads
 * and rewrites all data.
 */ (t), qs(t), function(t) {
            t.createObjectStore(ks.store);
        }
        /**
 * Represents the known absence of a document at a particular version.
 * Stored in IndexedDb as part of a DbRemoteDocument object.
 */ (t));
        // Migration 2 to populate the targetGlobal object no longer needed since
        // migration 3 unconditionally clears it.
                let r = xe.resolve();
        return s < 3 && i >= 3 && (
        // Brand new clients don't need to drop and recreate--only clients that
        // potentially have corrupt data.
        0 !== s && (!function(t) {
            t.deleteObjectStore(Os.store), t.deleteObjectStore(Ms.store), t.deleteObjectStore(xs.store);
        }(t), qs(t)), r = r.next(() => 
        /**
 * Creates the target global singleton row.
 *
 * @param {IDBTransaction} txn The version upgrade transaction for indexeddb
 */
        function(t) {
            const e = t.store(xs.store), s = new xs(
            /*highestTargetId=*/ 0, 
            /*lastListenSequenceNumber=*/ 0, y.min().C(), 
            /*targetCount=*/ 0);
            return e.put(xs.key, s);
        }
        /**
 * Creates indices on the RemoteDocuments store used for both multi-tab
 * and Index-Free queries.
 */ (n))), s < 4 && i >= 4 && (0 !== s && (
        // 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.
        r = r.next(() => function(t, e) {
            return e.store(Cs.store).Fr().next(s => {
                t.deleteObjectStore(Cs.store), t.createObjectStore(Cs.store, {
                    keyPath: Cs.keyPath,
                    autoIncrement: !0
                }).createIndex(Cs.userMutationsIndex, Cs.userMutationsKeyPath, {
                    unique: !0
                });
                const i = e.store(Cs.store), n = s.map(t => i.put(t));
                return xe.vn(n);
            });
        }
        /**
 * An object to be stored in the 'documentMutations' store in IndexedDb.
 *
 * A manually maintained index of all the mutation batches that affect a given
 * document key. The rows in this table are references based on the contents of
 * DbMutationBatch.mutations.
 */ (t, n))), r = r.next(() => {
            !function(t) {
                t.createObjectStore(Us.store, {
                    keyPath: Us.keyPath
                });
            }
            // Visible for testing
            (t);
        })), s < 5 && i >= 5 && (r = r.next(() => this.removeAcknowledgedMutations(n))), 
        s < 6 && i >= 6 && (r = r.next(() => (function(t) {
            t.createObjectStore(Ls.store);
        }
        /**
 * An object to be stored in the 'targets' store in IndexedDb.
 *
 * This is based on and should be kept in sync with the proto used in the iOS
 * client.
 *
 * Each query the client listens to against the server is tracked on disk so
 * that the query can be efficiently resumed on restart.
 */ (t), this.addDocumentGlobal(n)))), s < 7 && i >= 7 && (r = r.next(() => this.ensureSequenceNumbers(n))), 
        s < 8 && i >= 8 && (r = r.next(() => this.createCollectionParentIndex(t, n))), s < 9 && i >= 9 && (r = r.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(t) {
                t.objectStoreNames.contains("remoteDocumentChanges") && t.deleteObjectStore("remoteDocumentChanges");
            }(t), function(t) {
                const e = t.objectStore(ks.store);
                e.createIndex(ks.readTimeIndex, ks.readTimeIndexPath, {
                    unique: !1
                }), e.createIndex(ks.collectionReadTimeIndex, ks.collectionReadTimeIndexPath, {
                    unique: !1
                });
            }
            /**
 * A record of the metadata state of each client.
 *
 * PORTING NOTE: This is used to synchronize multi-tab state and does not need
 * to be ported to iOS or Android.
 */ (e);
        })), s < 10 && i >= 10 && (r = r.next(() => this.rewriteCanonicalIds(n))), r;
    }
    addDocumentGlobal(t) {
        let e = 0;
        return t.store(ks.store).Ur((t, s) => {
            e += hs(s);
        }).next(() => {
            const s = new Ls(e);
            return t.store(Ls.store).put(Ls.key, s);
        });
    }
    removeAcknowledgedMutations(t) {
        const e = t.store(Ds.store), s = t.store(Cs.store);
        return e.Fr().next(e => xe.forEach(e, e => {
            const i = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);
            return s.Fr(Cs.userMutationsIndex, i).next(s => xe.forEach(s, s => {
                ve(s.userId === e.userId);
                const i = this.serializer.Lh(s);
                return Ps(t, e.userId, i).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.
     */    ensureSequenceNumbers(t) {
        const e = t.store(Os.store), s = t.store(ks.store);
        return t.store(xs.store).get(xs.key).next(t => {
            const i = [];
            return s.Ur((s, n) => {
                const r = new v(s), h = function(t) {
                    return [ 0, ze(t) ];
                }
                /**
 * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.
 */ (r);
                i.push(e.get(h).next(s => s ? xe.resolve() : (s => e.put(new Os(0, ze(s), t.highestListenSequenceNumber)))(r)));
            }).next(() => xe.vn(i));
        });
    }
    createCollectionParentIndex(t, e) {
        // Create the index.
        t.createObjectStore(Bs.store, {
            keyPath: Bs.keyPath
        });
        const s = e.store(Bs.store), i = new Ze, n = t => {
            if (i.add(t)) {
                const e = t.O(), i = t.L();
                return s.put({
                    collectionId: e,
                    parent: ze(i)
                });
            }
        };
        // Helper to add an index entry iff we haven't already written it.
                // Index existing remote documents.
        return e.store(ks.store).Ur({
            Dh: !0
        }, (t, e) => {
            const s = new v(t);
            return n(s.L());
        }).next(() => e.store(Fs.store).Ur({
            Dh: !0
        }, ([t, e, s], i) => {
            const r = Je(e);
            return n(r.L());
        }));
    }
    rewriteCanonicalIds(t) {
        const e = t.store(Ms.store);
        return e.Ur((t, s) => {
            const i = this.serializer.mh(s), n = this.serializer.Ph(i);
            return e.put(n);
        });
    }
}

class vs {
    constructor(t, e) {
        this.seconds = t, this.nanoseconds = e;
    }
}

/**
 * A singleton object to be stored in the 'owner' store in IndexedDb.
 *
 * A given database can have a single primary tab assigned at a given time. That
 * tab must validate that it is still holding the primary lease before every
 * operation that requires locked access. The primary tab should regularly
 * write an updated timestamp to this lease to prevent other tabs from
 * "stealing" the primary lease
 */ class Ss {
    constructor(t, 
    /** Whether to allow shared access from multiple tabs. */
    e, s) {
        this.ownerId = t, this.allowTabSynchronization = e, this.leaseTimestampMs = s;
    }
}

/**
 * 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.
 */ Ss.store = "owner", 
/**
 * The key string used for the single object that exists in the
 * DbPrimaryClient store.
 */
Ss.key = "owner";

class Ds {
    constructor(
    /**
     * The normalized user ID to which this queue belongs.
     */
    t, 
    /**
     * An identifier for the highest numbered batch that has been acknowledged
     * by the server. All MutationBatches in this queue with batchIds less
     * than or equal to this value are considered to have been acknowledged by
     * the server.
     *
     * NOTE: this is deprecated and no longer used by the code.
     */
    e, 
    /**
     * A stream token that was previously sent by the server.
     *
     * See StreamingWriteRequest in datastore.proto for more details about
     * usage.
     *
     * After sending this token, earlier tokens may not be used anymore so
     * only a single stream token is retained.
     */
    s) {
        this.userId = t, this.lastAcknowledgedBatchId = e, this.lastStreamToken = s;
    }
}

/** Name of the IndexedDb object store.  */ Ds.store = "mutationQueues", 
/** Keys are automatically assigned via the userId property. */
Ds.keyPath = "userId";

/**
 * An object to be stored in the 'mutations' store in IndexedDb.
 *
 * Represents a batch of user-level mutations intended to be sent to the server
 * in a single write. Each user-level batch gets a separate DbMutationBatch
 * with a new batchId.
 */
class Cs {
    constructor(
    /**
     * The normalized user ID to which this batch belongs.
     */
    t, 
    /**
     * An identifier for this batch, allocated using an auto-generated key.
     */
    e, 
    /**
     * The local write time of the batch, stored as milliseconds since the
     * epoch.
     */
    s, 
    /**
     * A list of "mutations" that represent a partial base state from when this
     * write batch was initially created. During local application of the write
     * batch, these baseMutations are applied prior to the real writes in order
     * to override certain document fields from the remote document cache. This
     * is necessary in the case of non-idempotent writes (e.g. `increment()`
     * transforms) to make sure that the local view of the modified documents
     * doesn't flicker if the remote document cache receives the result of the
     * non-idempotent write before the write is removed from the queue.
     *
     * These mutations are never sent to the backend.
     */
    i, 
    /**
     * A list of mutations to apply. All mutations will be applied atomically.
     *
     * Mutations are serialized via JsonProtoSerializer.toMutation().
     */
    n) {
        this.userId = t, this.batchId = e, this.localWriteTimeMs = s, this.baseMutations = i, 
        this.mutations = n;
    }
}

/** Name of the IndexedDb object store.  */ Cs.store = "mutations", 
/** Keys are automatically assigned via the userId, batchId properties. */
Cs.keyPath = "batchId", 
/** The index name for lookup of mutations by user. */
Cs.userMutationsIndex = "userMutationsIndex", 
/** The user mutations index is keyed by [userId, batchId] pairs. */
Cs.userMutationsKeyPath = [ "userId", "batchId" ];

class Fs {
    constructor() {}
    /**
     * Creates a [userId] key for use in the DbDocumentMutations index to iterate
     * over all of a user's document mutations.
     */    static prefixForUser(t) {
        return [ t ];
    }
    /**
     * Creates a [userId, encodedPath] key for use in the DbDocumentMutations
     * index to iterate over all at document mutations for a given path or lower.
     */    static prefixForPath(t, e) {
        return [ t, ze(e) ];
    }
    /**
     * Creates a full index key of [userId, encodedPath, batchId] for inserting
     * and deleting into the DbDocumentMutations index.
     */    static key(t, e, s) {
        return [ t, ze(e), s ];
    }
}

Fs.store = "documentMutations", 
/**
 * 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.
 */
Fs.PLACEHOLDER = new Fs;

class Ns {
    constructor(t, e) {
        this.path = t, this.readTime = e;
    }
}

/**
 * Represents a document that is known to exist but whose data is unknown.
 * Stored in IndexedDb as part of a DbRemoteDocument object.
 */ class $s {
    constructor(t, e) {
        this.path = t, this.version = e;
    }
}

/**
 * An object to be stored in the 'remoteDocuments' store in IndexedDb.
 * It represents either:
 *
 * - A complete document.
 * - A "no document" representing a document that is known not to exist (at
 * some version).
 * - An "unknown document" representing a document that is known to exist (at
 * some version) but whose contents are unknown.
 *
 * Note: This is the persisted equivalent of a MaybeDocument and could perhaps
 * be made more general if necessary.
 */ class ks {
    // TODO: We are currently storing full document keys almost three times
    // (once as part of the primary key, once - partly - as `parentPath` and once
    // inside the encoded documents). During our next migration, we should
    // rewrite the primary key as parentPath + document ID which would allow us
    // to drop one value.
    constructor(
    /**
     * Set to an instance of DbUnknownDocument if the data for a document is
     * not known, but it is known that a document exists at the specified
     * version (e.g. it had a successful update applied to it)
     */
    t, 
    /**
     * Set to an instance of a DbNoDocument if it is known that no document
     * exists.
     */
    e, 
    /**
     * Set to an instance of a Document if there's a cached version of the
     * document.
     */
    s, 
    /**
     * Documents that were written to the remote document store based on
     * a write acknowledgment are marked with `hasCommittedMutations`. These
     * documents are potentially inconsistent with the backend's copy and use
     * the write's commit version as their document version.
     */
    i, 
    /**
     * When the document was read from the backend. Undefined for data written
     * prior to schema version 9.
     */
    n, 
    /**
     * The path of the collection this document is part of. Undefined for data
     * written prior to schema version 9.
     */
    r) {
        this.unknownDocument = t, this.noDocument = e, this.document = s, this.hasCommittedMutations = i, 
        this.readTime = n, this.parentPath = r;
    }
}

ks.store = "remoteDocuments", 
/**
 * An index that provides access to all entries sorted by read time (which
 * corresponds to the last modification time of each row).
 *
 * This index is used to provide a changelog for Multi-Tab.
 */
ks.readTimeIndex = "readTimeIndex", ks.readTimeIndexPath = "readTime", 
/**
 * An index that provides access to documents in a collection sorted by read
 * time.
 *
 * This index is used to allow the RemoteDocumentCache to fetch newly changed
 * documents in a collection.
 */
ks.collectionReadTimeIndex = "collectionReadTimeIndex", ks.collectionReadTimeIndexPath = [ "parentPath", "readTime" ];

/**
 * Contains a single entry that has metadata about the remote document cache.
 */
class Ls {
    /**
     * @param byteSize Approximately the total size in bytes of all the documents in the document
     * cache.
     */
    constructor(t) {
        this.byteSize = t;
    }
}

Ls.store = "remoteDocumentGlobal", Ls.key = "remoteDocumentGlobalKey";

class Ms {
    constructor(
    /**
     * An auto-generated sequential numeric identifier for the query.
     *
     * Queries are stored using their canonicalId as the key, but these
     * canonicalIds can be quite long so we additionally assign a unique
     * queryId which can be used by referenced data structures (e.g.
     * indexes) to minimize the on-disk cost.
     */
    t, 
    /**
     * The canonical string representing this query. This is not unique.
     */
    e, 
    /**
     * The last readTime received from the Watch Service for this query.
     *
     * This is the same value as TargetChange.read_time in the protos.
     */
    s, 
    /**
     * 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.
     *
     * This is related to the snapshotVersion in that the resumeToken
     * effectively also encodes that value, but the resumeToken is opaque
     * and sometimes encodes additional information.
     *
     * A consequence of this is that the resumeToken should be used when
     * asking the server to reason about where this client is in the watch
     * stream, but the client should use the snapshotVersion for its own
     * purposes.
     *
     * This is the same value as TargetChange.resume_token in the protos.
     */
    i, 
    /**
     * A sequence number representing the last time this query was
     * listened to, used for garbage collection purposes.
     *
     * Conventionally this would be a timestamp value, but device-local
     * clocks are unreliable and they must be able to create new listens
     * even while disconnected. Instead this should be a monotonically
     * increasing number that's incremented on each listen call.
     *
     * This is different from the queryId since the queryId is an
     * immutable identifier assigned to the Query on first use while
     * lastListenSequenceNumber is updated every time the query is
     * listened to.
     */
    n, 
    /**
     * Denotes the maximum snapshot version at which the associated query view
     * contained no limbo documents.  Undefined for data written prior to
     * schema version 9.
     */
    r, 
    /**
     * The query for this target.
     *
     * Because canonical ids are not unique we must store the actual query. We
     * use the proto to have an object we can persist without having to
     * duplicate translation logic to and from a `Query` object.
     */
    h) {
        this.targetId = t, this.canonicalId = e, this.readTime = s, this.resumeToken = i, 
        this.lastListenSequenceNumber = n, this.lastLimboFreeSnapshotVersion = r, this.query = h;
    }
}

Ms.store = "targets", 
/** Keys are automatically assigned via the targetId property. */
Ms.keyPath = "targetId", 
/** The name of the queryTargets index. */
Ms.queryTargetsIndexName = "queryTargetsIndex", 
/**
 * The index of all canonicalIds to the targets that they match. This is not
 * a unique mapping because canonicalId does not promise a unique name for all
 * possible queries, so we append the targetId to make the mapping unique.
 */
Ms.queryTargetsKeyPath = [ "canonicalId", "targetId" ];

/**
 * An object representing an association between a target and a document, or a
 * sentinel row marking the last sequence number at which a document was used.
 * Each document cached must have a corresponding sentinel row before lru
 * garbage collection is enabled.
 *
 * The target associations and sentinel rows are co-located so that orphaned
 * documents and their sequence numbers can be identified efficiently via a scan
 * of this store.
 */
class Os {
    constructor(
    /**
     * The targetId identifying a target or 0 for a sentinel row.
     */
    t, 
    /**
     * The path to the document, as encoded in the key.
     */
    e, 
    /**
     * If this is a sentinel row, this should be the sequence number of the last
     * time the document specified by `path` was used. Otherwise, it should be
     * `undefined`.
     */
    s) {
        this.targetId = t, this.path = e, this.sequenceNumber = s;
    }
}

/** Name of the IndexedDb object store.  */ Os.store = "targetDocuments", 
/** Keys are automatically assigned via the targetId, path properties. */
Os.keyPath = [ "targetId", "path" ], 
/** The index name for the reverse index. */
Os.documentTargetsIndex = "documentTargetsIndex", 
/** We also need to create the reverse index for these properties. */
Os.documentTargetsKeyPath = [ "path", "targetId" ];

/**
 * A record of global state tracked across all Targets, tracked separately
 * to avoid the need for extra indexes.
 *
 * This should be kept in-sync with the proto used in the iOS client.
 */
class xs {
    constructor(
    /**
     * The highest numbered target id across all targets.
     *
     * See DbTarget.targetId.
     */
    t, 
    /**
     * The highest numbered lastListenSequenceNumber across all targets.
     *
     * See DbTarget.lastListenSequenceNumber.
     */
    e, 
    /**
     * A global snapshot version representing the last consistent snapshot we
     * received from the backend. This is monotonically increasing and any
     * snapshots received from the backend prior to this version (e.g. for
     * targets resumed with a resumeToken) should be suppressed (buffered)
     * until the backend has caught up to this snapshot version again. This
     * prevents our cache from ever going backwards in time.
     */
    s, 
    /**
     * The number of targets persisted.
     */
    i) {
        this.highestTargetId = t, this.highestListenSequenceNumber = e, this.lastRemoteSnapshotVersion = s, 
        this.targetCount = i;
    }
}

/**
 * The key string used for the single object that exists in the
 * DbTargetGlobal store.
 */ xs.key = "targetGlobalKey", xs.store = "targetGlobal";

/**
 * An object representing an association between a Collection id (e.g. 'messages')
 * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.
 * This is used to efficiently find all collections to query when performing
 * a Collection Group query.
 */
class Bs {
    constructor(
    /**
     * The collectionId (e.g. 'messages')
     */
    t, 
    /**
     * The path to the parent (either a document location or an empty path for
     * a root-level collection).
     */
    e) {
        this.collectionId = t, this.parent = e;
    }
}

/** Name of the IndexedDb object store. */ function qs(t) {
    t.createObjectStore(Os.store, {
        keyPath: Os.keyPath
    }).createIndex(Os.documentTargetsIndex, Os.documentTargetsKeyPath, {
        unique: !0
    }), 
    // NOTE: This is unique only because the TargetId is the suffix.
    t.createObjectStore(Ms.store, {
        keyPath: Ms.keyPath
    }).createIndex(Ms.queryTargetsIndexName, Ms.queryTargetsKeyPath, {
        unique: !0
    }), t.createObjectStore(xs.store);
}

Bs.store = "collectionParents", 
/** Keys are automatically assigned via the collectionId, parent properties. */
Bs.keyPath = [ "collectionId", "parent" ];

class Us {
    constructor(
    // Note: Previous schema versions included a field
    // "lastProcessedDocumentChangeId". Don't use anymore.
    /** The auto-generated client id assigned at client startup. */
    t, 
    /** The last time this state was updated. */
    e, 
    /** Whether the client's network connection is enabled. */
    s, 
    /** Whether this client is running in a foreground tab. */
    i) {
        this.clientId = t, this.updateTimeMs = e, this.networkEnabled = s, this.inForeground = i;
    }
}

/** Name of the IndexedDb object store. */ Us.store = "clientMetadata", 
/** Keys are automatically assigned via the clientId properties. */
Us.keyPath = "clientId";

const Qs = [ ...[ ...[ ...[ Ds.store, Cs.store, Fs.store, ks.store, Ms.store, Ss.store, xs.store, Os.store ], Us.store ], Ls.store ], Bs.store ];

// V2 is no longer usable (see comment at top of file)
// Visible for testing
/**
 * 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 Ws {
    constructor(t) {
        this.db = t, 
        // 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 === Ws.aa(i()) && pe("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.
     *
     * 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.
     */    static Xh(t, e, s) {
        return ge("SimpleDb", "Opening database:", t), new xe((i, 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 = window.indexedDB.open(t, e);
            r.onsuccess = t => {
                const e = t.target.result;
                i(new Ws(e));
            }, r.onblocked = () => {
                n(new R(w.FAILED_PRECONDITION, "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 e = t.target.error;
                "VersionError" === e.name ? n(new R(w.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.")) : n(e);
            }, r.onupgradeneeded = e => {
                ge("SimpleDb", 'Database "' + t + '" requires upgrade from version:', e.oldVersion);
                const i = e.target.result;
                s.createOrUpgrade(i, r.transaction, e.oldVersion, ys).next(() => {
                    ge("SimpleDb", "Database upgrade to version " + ys + " complete");
                });
            };
        }).yn();
    }
    /** Deletes the specified database. */    static delete(t) {
        return ge("SimpleDb", "Removing database:", t), Ys(window.indexedDB.deleteDatabase(t)).yn();
    }
    /** Returns true if IndexedDB is available in the current environment. */    static Gh() {
        if ("undefined" == typeof window || null == window.indexedDB) return !1;
        if (Ws.ua()) return !0;
        // In some Node environments, `window` is defined, but `window.navigator` is
        // not. We don't support IndexedDB persistence in Node if the
        // isMockPersistence() check above returns false.
                if (void 0 === window.navigator) return !1;
        // 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 t = i(), e = Ws.aa(t), s = 0 < e && e < 10, n = Ws.ca(t), r = 0 < n && n < 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 !(t.indexOf("MSIE ") > 0 || t.indexOf("Trident/") > 0 || t.indexOf("Edge/") > 0 || s || r);
    }
    /**
     * Returns true if the backing IndexedDB store is the Node IndexedDBShim
     * (see https://github.com/axemclion/IndexedDBShim).
     */    static ua() {
        var t;
        return "undefined" != typeof __PRIVATE_process && "YES" === (null === (t = __PRIVATE_process.__PRIVATE_env) || void 0 === t ? void 0 : t._a);
    }
    /** Helper to get a typed SimpleDbStore from a transaction. */    static Nr(t, e) {
        return t.store(e);
    }
    // visible for testing
    /** Parse User Agent to determine iOS version. Returns -1 if not found. */
    static aa(t) {
        const e = t.match(/i(?:phone|pad|pod) os ([\d_]+)/i), s = e ? e[1].split("_").slice(0, 2).join(".") : "-1";
        return Number(s);
    }
    // visible for testing
    /** Parse User Agent to determine Android version. Returns -1 if not found. */
    static ca(t) {
        const e = t.match(/Android ([\d.]+)/i), s = e ? e[1].split(".").slice(0, 2).join(".") : "-1";
        return Number(s);
    }
    oo(t) {
        this.db.onversionchange = e => t(e);
    }
    async runTransaction(t, e, s) {
        const i = "readonly" === t;
        let n = 0;
        for (;;) {
            ++n;
            const t = zs.open(this.db, i ? "readonly" : "readwrite", e);
            try {
                const e = s(t).catch(e => (
                // Abort the transaction if there was an error.
                t.abort(e), xe.reject(e))).yn();
                // 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 e.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.la, e;
            } catch (t) {
                // 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.
                const e = "FirebaseError" !== t.name && n < 3;
                if (ge("SimpleDb", "Transaction failed with error: %s. Retrying: %s.", t.message, e), 
                !e) return Promise.reject(t);
            }
        }
    }
    close() {
        this.db.close();
    }
}

/**
 * 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 js {
    constructor(t) {
        this.da = t, this.fa = !1, this.Ta = null;
    }
    get Pn() {
        return this.fa;
    }
    get Ea() {
        return this.Ta;
    }
    set cursor(t) {
        this.da = t;
    }
    /**
     * This function can be called to stop iteration at any point.
     */    done() {
        this.fa = !0;
    }
    /**
     * This function can be called to skip to that next key, which could be
     * an index or a primary key.
     */    Qr(t) {
        this.Ta = t;
    }
    /**
     * Delete the current cursor value from the object store.
     *
     * NOTE: You CANNOT do this with a keysOnly query.
     */    delete() {
        return Ys(this.da.delete());
    }
}

/** An error that wraps exceptions that thrown during IndexedDB execution. */ class Ks extends R {
    constructor(t) {
        super(w.UNAVAILABLE, "IndexedDB transaction failed: " + t), this.name = "IndexedDbTransactionError";
    }
}

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

/**
 * Wraps an IDBTransaction and exposes a store() method to get a handle to a
 * specific object store.
 */ class zs {
    constructor(t) {
        this.transaction = t, this.aborted = !1, 
        /**
         * A promise that resolves with the result of the IndexedDb transaction.
         */
        this.Ia = new Ke, this.transaction.oncomplete = () => {
            this.Ia.resolve();
        }, this.transaction.onabort = () => {
            t.error ? this.Ia.reject(new Ks(t.error)) : this.Ia.resolve();
        }, this.transaction.onerror = t => {
            const e = Xs(t.target.error);
            this.Ia.reject(new Ks(e));
        };
    }
    static open(t, e, s) {
        return new zs(t.transaction(s, e));
    }
    get la() {
        return this.Ia.promise;
    }
    abort(t) {
        t && this.Ia.reject(t), this.aborted || (ge("SimpleDb", "Aborting transaction:", t ? t.message : "Client-initiated abort"), 
        this.aborted = !0, this.transaction.abort());
    }
    /**
     * 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(t) {
        const e = this.transaction.objectStore(t);
        return new Hs(e);
    }
}

/**
 * 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 Hs {
    constructor(t) {
        this.store = t;
    }
    put(t, e) {
        let s;
        return void 0 !== e ? (ge("SimpleDb", "PUT", this.store.name, t, e), s = this.store.put(e, t)) : (ge("SimpleDb", "PUT", this.store.name, "<auto-key>", t), 
        s = this.store.put(t)), Ys(s);
    }
    /**
     * 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.
     * @return The key of the value to add.
     */    add(t) {
        return ge("SimpleDb", "ADD", this.store.name, t, t), Ys(this.store.add(t));
    }
    /**
     * 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.
     * @return The object with the specified key or null if no object exists.
     */    get(t) {
        // We're doing an unsafe cast to ValueType.
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        return Ys(this.store.get(t)).next(e => (
        // Normalize nonexistence to null.
        void 0 === e && (e = null), ge("SimpleDb", "GET", this.store.name, t, e), e));
    }
    delete(t) {
        return ge("SimpleDb", "DELETE", this.store.name, t), Ys(this.store.delete(t));
    }
    /**
     * 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() {
        return ge("SimpleDb", "COUNT", this.store.name), Ys(this.store.count());
    }
    Fr(t, e) {
        const s = this.cursor(this.options(t, e)), i = [];
        return this.wa(s, (t, e) => {
            i.push(e);
        }).next(() => i);
    }
    Ra(t, e) {
        ge("SimpleDb", "DELETE ALL", this.store.name);
        const s = this.options(t, e);
        s.Dh = !1;
        const i = this.cursor(s);
        return this.wa(i, (t, e, s) => s.delete());
    }
    Ur(t, e) {
        let s;
        e ? s = t : (s = {}, e = t);
        const i = this.cursor(s);
        return this.wa(i, e);
    }
    /**
     * 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.
     */    Uo(t) {
        const e = this.cursor({});
        return new xe((s, i) => {
            e.onerror = t => {
                const e = Xs(t.target.error);
                i(e);
            }, e.onsuccess = e => {
                const i = e.target.result;
                i ? t(i.primaryKey, i.value).next(t => {
                    t ? i.continue() : s();
                }) : s();
            };
        });
    }
    wa(t, e) {
        const s = [];
        return new xe((i, n) => {
            t.onerror = t => {
                n(t.target.error);
            }, t.onsuccess = t => {
                const n = t.target.result;
                if (!n) return void i();
                const r = new js(n), h = e(n.primaryKey, n.value, r);
                if (h instanceof xe) {
                    const t = h.catch(t => (r.done(), xe.reject(t)));
                    s.push(t);
                }
                r.Pn ? i() : null === r.Ea ? n.continue() : n.continue(r.Ea);
            };
        }).next(() => xe.vn(s));
    }
    options(t, e) {
        let s = void 0;
        return void 0 !== t && ("string" == typeof t ? s = t : e = t), {
            index: s,
            range: e
        };
    }
    cursor(t) {
        let e = "next";
        if (t.reverse && (e = "prev"), t.index) {
            const s = this.store.index(t.index);
            return t.Dh ? s.openKeyCursor(t.range, e) : s.openCursor(t.range, e);
        }
        return this.store.openCursor(t.range, e);
    }
}

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

// Guard so we only report the error once.
let Js = !1;

function Xs(t) {
    const e = Ws.aa(i());
    if (e >= 12.2 && e < 13) {
        const e = "An internal error was encountered in the Indexed Database server";
        if (t.message.indexOf(e) >= 0) {
            // Wrap error in a more descriptive one.
            const t = new R("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely ` + "due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.");
            return Js || (Js = !0, 
            // Throw a global exception outside of this promise chain, for the user to
            // potentially catch.
            setTimeout(() => {
                throw t;
            }, 0)), t;
        }
    }
    return 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.
 */
/**
 * 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 Zs {
    constructor(t, e, s, i, n) {
        this.Aa = t, this.Er = e, this.ma = s, this.op = i, this.Pa = n, this.Va = new Ke, 
        this.then = this.Va.promise.then.bind(this.Va.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.Va.promise.catch(t => {});
    }
    /**
     * 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 ga(t, e, s, i, n) {
        const r = Date.now() + s, h = new Zs(t, e, r, i, n);
        return h.start(s), h;
    }
    /**
     * Starts the timer. This is called immediately after construction by
     * createAndSchedule().
     */    start(t) {
        this.pa = setTimeout(() => this.ya(), t);
    }
    /**
     * Queues the operation to run immediately (if it hasn't already been run or
     * canceled).
     */    vr() {
        return this.ya();
    }
    /**
     * 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(t) {
        null !== this.pa && (this.clearTimeout(), this.Va.reject(new R(w.CANCELLED, "Operation cancelled" + (t ? ": " + t : ""))));
    }
    ya() {
        this.Aa.uo(() => null !== this.pa ? (this.clearTimeout(), this.op().then(t => this.Va.resolve(t))) : Promise.resolve());
    }
    clearTimeout() {
        null !== this.pa && (this.Pa(this), clearTimeout(this.pa), this.pa = null);
    }
}

class ti {
    constructor() {
        // The last promise in the queue.
        this.ba = Promise.resolve(), 
        // The last retryable operation. Retryable operation are run in order and
        // retried with backoff.
        this.va = Promise.resolve(), 
        // Is this AsyncQueue being shut down? Once it is set to true, it will not
        // be changed again.
        this.Sa = !1, 
        // Operations scheduled to be queued in the future. Operations are
        // automatically removed after they are run or canceled.
        this.Da = [], 
        // visible for testing
        this.Ca = null, 
        // Flag set while there's an outstanding AsyncQueue operation, used for
        // assertion sanity-checks.
        this.Fa = !1, 
        // List of TimerIds to fast-forward delays for.
        this.Na = [], 
        // Backoff timer used to schedule retries for retryable operations
        this.$a = new Ge(this, "async_queue_retry" /* 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.ka = () => this.$a.br();
        const t = Ae.nt().window;
        t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this.ka);
    }
    // Is this AsyncQueue being shut down? If true, this instance will not enqueue
    // any new operations, Promises from enqueue requests will not resolve.
    get La() {
        return this.Sa;
    }
    /**
     * Adds a new operation to the queue without waiting for it to complete (i.e.
     * we ignore the Promise result).
     */    uo(t) {
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this.enqueue(t);
    }
    /**
     * Regardless if the queue has initialized shutdown, adds a new operation to the
     * queue without waiting for it to complete (i.e. we ignore the Promise result).
     */    Ma(t) {
        this.Oa(), 
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this.xa(t);
    }
    /**
     * Regardless if the queue has initialized shutdown, adds a new operation to the
     * queue.
     */    Ba(t) {
        return this.Oa(), this.xa(t);
    }
    /**
     * Adds a new operation to the queue and initialize the shut down of this queue.
     * Returns a promise that will be resolved when the promise returned by the new
     * operation is (with its value).
     * Once this method is called, the only possible way to request running an operation
     * is through `enqueueAndForgetEvenAfterShutdown`.
     */    async qa(t) {
        if (this.Oa(), !this.Sa) {
            this.Sa = !0;
            const e = Ae.nt().window;
            e && e.removeEventListener("visibilitychange", this.ka), await this.Ba(t);
        }
    }
    /**
     * Adds a new operation to the queue. Returns a promise that will be resolved
     * when the promise returned by the new operation is (with its value).
     */    enqueue(t) {
        return this.Oa(), this.Sa ? new Promise(t => {}) : this.xa(t);
    }
    /**
     * Enqueue a retryable operation.
     *
     * A retryable operation is rescheduled with backoff if it fails with a
     * IndexedDbTransactionError (the error type used by SimpleDb). All
     * retryable operations are executed in order and only run if all prior
     * operations were retried successfully.
     */    Ua(t) {
        this.Oa(), this.Sa || (this.va = this.va.then(() => {
            const e = new Ke, s = async () => {
                try {
                    await t(), e.resolve(), this.$a.reset();
                } catch (t) {
                    if (!Gs(t)) throw e.resolve(), t;
 // Failure will be handled by AsyncQueue
                                        ge("AsyncQueue", "Operation failed with retryable error: " + t), 
                    this.$a.gr(s);
                }
            };
            return this.uo(s), e.promise;
        }));
    }
    xa(t) {
        const e = this.ba.then(() => (this.Fa = !0, t().catch(t => {
            // 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 this.Ca = t, this.Fa = !1, pe("INTERNAL UNHANDLED ERROR: ", t.stack || t.message || ""), 
            t;
        }).then(t => (this.Fa = !1, t))));
        return this.ba = e, e;
    }
    /**
     * Schedules an operation to be queued on the AsyncQueue once the specified
     * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel
     * or fast-forward the operation prior to its running.
     */    yr(t, e, s) {
        this.Oa(), 
        // Fast-forward delays for timerIds that have been overriden.
        this.Na.indexOf(t) > -1 && (e = 0);
        const i = Zs.ga(this, t, e, s, t => this.Qa(t));
        return this.Da.push(i), i;
    }
    Oa() {
        this.Ca && be();
    }
    /**
     * Verifies there's an operation currently in-progress on the AsyncQueue.
     * Unfortunately we can't verify that the running code is in the promise chain
     * of that operation, so this isn't a foolproof check, but it should be enough
     * to catch some bugs.
     */    Wa() {}
    /**
     * Waits until all currently queued tasks are finished executing. Delayed
     * operations are not run.
     */    async ja() {
        // 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 t;
        do {
            t = this.ba, await t;
        } while (t !== this.ba);
    }
    /**
     * For Tests: Determine if a delayed operation with a particular TimerId
     * exists.
     */    Ka(t) {
        for (const e of this.Da) if (e.Er === t) return !0;
        return !1;
    }
    /**
     * 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.
     */    Ga(t) {
        // Note that draining may generate more delayed ops, so we do that first.
        return this.ja().then(() => {
            // Run ops in the same order they'd run if they ran naturally.
            this.Da.sort((t, e) => t.ma - e.ma);
            for (const e of this.Da) if (e.vr(), "all" /* All */ !== t && e.Er === t) break;
            return this.ja();
        });
    }
    /**
     * For Tests: Skip all subsequent delays for a timer id.
     */    za(t) {
        this.Na.push(t);
    }
    /** Called once a DelayedOperation is run or canceled. */    Qa(t) {
        // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.
        const e = this.Da.indexOf(t);
        this.Da.splice(e, 1);
    }
}

/**
 * Returns a FirestoreError that can be surfaced to the user if the provided
 * error is an IndexedDbTransactionError. Re-throws the error otherwise.
 */ function ei(t, e) {
    if (pe("AsyncQueue", `${e}: ${t}`), Gs(t)) return new R(w.UNAVAILABLE, `${e}: ${t}`);
    throw 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.
 */ function si([t, e], [s, i]) {
    const n = Ce(t, s);
    return 0 === n ? Ce(e, i) : n;
}

/**
 * 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 ii {
    constructor(t) {
        this.Ha = t, this.buffer = new jt(si), this.Ya = 0;
    }
    Ja() {
        return ++this.Ya;
    }
    Xa(t) {
        const e = [ t, this.Ja() ];
        if (this.buffer.size < this.Ha) this.buffer = this.buffer.add(e); else {
            const t = this.buffer.last();
            si(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));
        }
    }
    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];
    }
}

const ni = {
    Za: !1,
    tu: 0,
    eu: 0,
    su: 0
};

class ri {
    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.
    t, 
    // The percentage of sequence numbers that we will attempt to collect
    e, 
    // 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.
    s) {
        this.iu = t, this.nu = e, this.ru = s;
    }
    static hu(t) {
        return new ri(t, ri.ou, ri.au);
    }
}

ri.uu = -1, ri.cu = 1048576, ri._u = 41943040, ri.ou = 10, ri.au = 1e3, ri.lu = new ri(ri._u, ri.ou, ri.au), 
ri.DISABLED = new ri(ri.uu, 0, 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 hi {
    constructor(t, e) {
        this.ko = t, this.Aa = e, this.du = !1, this.fu = null;
    }
    start(t) {
        this.ko.Tu.iu !== ri.uu && this.Eu(t);
    }
    stop() {
        this.fu && (this.fu.cancel(), this.fu = null);
    }
    get ro() {
        return null !== this.fu;
    }
    Eu(t) {
        const e = this.du ? 3e5 : 6e4;
        ge("LruGarbageCollector", `Garbage collection scheduled in ${e}ms`), this.fu = this.Aa.yr("lru_garbage_collection" /* LruGarbageCollection */ , e, async () => {
            this.fu = null, this.du = !0;
            try {
                await t.Iu(this.ko);
            } catch (t) {
                Gs(t) ? ge("LruGarbageCollector", "Ignoring IndexedDB error during garbage collection: ", t) : await ci(t);
            }
            await this.Eu(t);
        });
    }
}

/** Implements the steps for LRU garbage collection. */ class oi {
    constructor(t, e) {
        this.wu = t, this.Tu = e;
    }
    /** Given a percentile of target to collect, returns the number of targets to collect. */    Ru(t, e) {
        return this.wu.Lo(t).next(t => Math.floor(e / 100 * t));
    }
    /** Returns the nth sequence number, counting in order from the smallest. */    Au(t, e) {
        if (0 === e) return xe.resolve(je.dr);
        const s = new ii(e);
        return this.wu.js(t, t => s.Xa(t.sequenceNumber)).next(() => this.wu.Oo(t, t => s.Xa(t))).next(() => s.maxValue);
    }
    /**
     * Removes targets with a sequence number equal to or less than the given upper bound, and removes
     * document associations with those targets.
     */    Ah(t, e, s) {
        return this.wu.Ah(t, e, s);
    }
    /**
     * Removes documents that have a sequence number equal to or less than the upper bound and are not
     * otherwise pinned.
     */    Qo(t, e) {
        return this.wu.Qo(t, e);
    }
    mu(t, e) {
        return this.Tu.iu === ri.uu ? (ge("LruGarbageCollector", "Garbage collection skipped; disabled"), 
        xe.resolve(ni)) : this.jo(t).next(s => s < this.Tu.iu ? (ge("LruGarbageCollector", `Garbage collection skipped; Cache size ${s} ` + `is lower than threshold ${this.Tu.iu}`), 
        ni) : this.Pu(t, e));
    }
    jo(t) {
        return this.wu.jo(t);
    }
    Pu(t, e) {
        let i, n, r, h, o, a, u;
        const c = Date.now();
        return this.Ru(t, this.Tu.nu).next(e => (
        // Cap at the configured max
        e > this.Tu.ru ? (ge("LruGarbageCollector", "Capping sequence numbers to collect down " + `to the maximum of ${this.Tu.ru} ` + `from ${e}`), 
        n = this.Tu.ru) : n = e, h = Date.now(), this.Au(t, n))).next(s => (i = s, o = Date.now(), 
        this.Ah(t, i, e))).next(e => (r = e, a = Date.now(), this.Qo(t, i))).next(t => {
            if (u = Date.now(), Pe() <= s.DEBUG) {
                ge("LruGarbageCollector", "LRU Garbage Collection\n" + `\tCounted targets in ${h - c}ms\n` + `\tDetermined least recently used ${n} in ` + `${o - h}ms\n` + `\tRemoved ${r} targets in ` + `${a - o}ms\n` + `\tRemoved ${t} documents in ` + `${u - a}ms\n` + `Total Duration: ${u - c}ms`);
            }
            return xe.resolve({
                Za: !0,
                tu: n,
                eu: r,
                su: 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.
 */
/**
 * Local storage in the Firestore client. Coordinates persistence components
 * like the mutation queue and remote document cache to present a
 * latency-compensated view of stored data.
 *
 * The LocalStore is responsible for accepting mutations from the Sync Engine.
 * Writes from the client are put into a queue as provisional Mutations until
 * they are processed by the RemoteStore and confirmed as having been written
 * to the server.
 *
 * The local store provides the local version of documents that have been
 * modified locally. It maintains the constraint:
 *
 *   LocalDocument = RemoteDocument + Active(LocalMutations)
 *
 * (Active mutations are those that are enqueued and have not been previously
 * acknowledged or rejected).
 *
 * The RemoteDocument ("ground truth") state is provided via the
 * applyChangeBatch method. It will be some version of a server-provided
 * document OR will be a server-provided document PLUS acknowledged mutations:
 *
 *   RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)
 *
 * Note that this "dirty" version of a RemoteDocument will not be identical to a
 * server base version, since it has LocalMutations added to it pending getting
 * an authoritative copy from the server.
 *
 * Since LocalMutations can be rejected by the server, we have to be able to
 * revert a LocalMutation that has already been applied to the LocalDocument
 * (typically done by replaying all remaining LocalMutations to the
 * RemoteDocument to re-apply).
 *
 * The LocalStore is responsible for the garbage collection of the documents it
 * contains. For now, it every doc referenced by a view, the mutation queue, or
 * the RemoteStore.
 *
 * It also maintains the persistence of mapping queries to resume tokens and
 * target ids. It needs to know this data about queries to properly know what
 * docs it would be allowed to garbage collect.
 *
 * The LocalStore must be able to efficiently execute queries against its local
 * cache of the documents, to provide the initial set of results before any
 * remote changes have been received.
 *
 * Note: In TypeScript, most methods return Promises since the implementation
 * may rely on fetching data from IndexedDB which is async.
 * These Promises will only be rejected on an I/O error or other internal
 * (unexpected) failure (e.g. failed assert) and always represent an
 * unrecoverable error (should be caught / reported by the async_queue).
 */
class ai {
    constructor(
    /** Manages our in-memory or durable persistence. */
    t, e, s) {
        this.persistence = t, this.Vu = e, 
        /**
         * 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.gu = new Ut(Ce), 
        /** Maps a target to its targetID. */
        // TODO(wuandy): Evaluate if TargetId can be part of Target.
        this.pu = new Le(t => t.canonicalId()), 
        /**
         * The read time of the last entry processed by `getNewDocumentChanges()`.
         *
         * PORTING NOTE: This is only used for multi-tab synchronization.
         */
        this.yu = y.min(), this.Wn = t.vo(s), this.bu = t.Co(), this.Yh = t.Do(), this.vu = new Qe(this.bu, this.Wn, this.persistence.Fo()), 
        this.Vu.Su(this.vu);
    }
    /** Starts the LocalStore. */    start() {
        return Promise.resolve();
    }
    /**
     * 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 Du(t) {
        let e = this.Wn, s = this.vu;
        const i = await this.persistence.runTransaction("Handle user change", "readonly", i => {
            // Swap out the mutation queue, grabbing the pending mutation batches
            // before and after.
            let n;
            return this.Wn.ia(i).next(r => (n = r, e = this.persistence.vo(t), 
            // Recreate our LocalDocumentsView using the new
            // MutationQueue.
            s = new Qe(this.bu, e, this.persistence.Fo()), e.ia(i))).next(t => {
                const e = [], r = [];
                // Union the old/new changed keys.
                let h = ee();
                for (const t of n) {
                    e.push(t.batchId);
                    for (const e of t.mutations) h = h.add(e.key);
                }
                for (const e of t) {
                    r.push(e.batchId);
                    for (const t of e.mutations) h = h.add(t.key);
                }
                // Return the set of all (potentially) changed documents and the list
                // of mutation batch IDs that were affected by change.
                                return s.Yn(i, h).next(t => ({
                    Cu: t,
                    Fu: e,
                    Nu: r
                }));
            });
        });
        return this.Wn = e, this.vu = s, this.Vu.Su(this.vu), i;
    }
    /* Accept locally generated Mutations and commit them to storage. */    $u(t) {
        const e = p.now(), s = t.reduce((t, e) => t.add(e.key), ee());
        let i;
        return this.persistence.runTransaction("Locally write mutations", "readwrite", n => this.vu.Yn(n, s).next(s => {
            i = s;
            // 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 r = [];
            for (const e of t) {
                const t = e.Pt(i.get(e.key));
                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
                r.push(new Tt(e.key, t, mt(t.proto.mapValue), lt.exists(!0)));
            }
            return this.Wn.Xo(n, e, r, t);
        })).then(t => {
            const e = t.In(i);
            return {
                batchId: t.batchId,
                Dn: e
            };
        });
    }
    /**
     * Acknowledge 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.
     */    zo(t) {
        return this.persistence.runTransaction("Acknowledge batch", "readwrite-primary", e => {
            const s = t.batch.keys(), i = this.bu.Yr({
                Xr: !0
            });
            return this.Wn.zo(e, t.batch, t.streamToken).next(() => this.ku(e, t, i)).next(() => i.apply(e)).next(() => this.Wn.oa(e)).next(() => this.vu.Yn(e, s));
        });
    }
    /**
     * Remove mutations from the MutationQueue for the specified batch;
     * LocalDocuments will be recalculated.
     *
     * @returns The resulting modified documents.
     */    Lu(t) {
        return this.persistence.runTransaction("Reject batch", "readwrite-primary", e => {
            let s;
            return this.Wn.Zo(e, t).next(t => (ve(null !== t), s = t.keys(), this.Wn.ra(e, t))).next(() => this.Wn.oa(e)).next(() => this.vu.Yn(e, s));
        });
    }
    /**
     * Returns the largest (latest) batch id in mutation queue that is pending server response.
     * Returns `BATCHID_UNKNOWN` if the queue is empty.
     */    sa() {
        return this.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", t => this.Wn.sa(t));
    }
    /** Returns the last recorded stream token for the current user. */    Yo() {
        return this.persistence.runTransaction("Get last stream token", "readonly", t => this.Wn.Yo(t));
    }
    /**
     * Sets the stream token for the current user without acknowledging any
     * mutation batch. This is usually only useful after a stream handshake or in
     * response to an error that requires clearing the stream token.
     */    Jo(t) {
        return this.persistence.runTransaction("Set last stream token", "readwrite-primary", e => this.Wn.Jo(e, t));
    }
    /**
     * Returns the last consistent snapshot processed (used by the RemoteStore to
     * determine whether to buffer incoming snapshots from the backend).
     */    _h() {
        return this.persistence.runTransaction("Get last remote snapshot version", "readonly", t => this.Yh._h(t));
    }
    /**
     * Update 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.
     */    Mu(t) {
        const e = t.Ee;
        let s = this.gu;
        return this.persistence.runTransaction("Apply remote event", "readwrite-primary", i => {
            const n = this.bu.Yr({
                Xr: !0
            });
            // Reset newTargetDataByTargetMap in case this transaction gets re-run.
                        s = this.gu;
            const r = [];
            t.as.forEach((t, n) => {
                const h = s.get(n);
                if (!h) 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.
                                r.push(this.Yh.bh(i, t.Is, n).next(() => this.Yh.ph(i, t.Ts, n)));
                const o = t.resumeToken;
                // Update the resume token if the change includes one.
                                if (o.rt() > 0) {
                    const a = h.we(o, e).Ie(i.Oh);
                    s = s.Ae(n, a), 
                    // Update the target data if there are target changes (or if
                    // sufficient time has passed since the last update).
                    ai.Ou(h, a, t) && r.push(this.Yh.Ih(i, a));
                }
            });
            let h = zt(), o = ee();
            // 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.cs.forEach((t, e) => {
                o = o.add(t);
            }), 
            // Each loop iteration only affects its "own" doc, so it's safe to get all the remote
            // documents in advance in a single call.
            r.push(n.getEntries(i, o).next(s => {
                t.cs.forEach((o, a) => {
                    const u = s.get(o);
                    // 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.
                                        a instanceof gt && a.version.isEqual(y.min()) ? (
                    // NoDocuments with SnapshotVersion.min() are used in manufactured
                    // events. We remove these documents from cache since we lost
                    // access.
                    n.kn(o, e), h = h.Ae(o, a)) : null == u || a.version.S(u.version) > 0 || 0 === a.version.S(u.version) && u.hasPendingWrites ? (n.Nn(a, e), 
                    h = h.Ae(o, a)) : ge("LocalStore", "Ignoring outdated watch update for ", o, ". Current version:", u.version, " Watch version:", a.version), 
                    t._s.has(o) && r.push(this.persistence.hh.Wo(i, o));
                });
            })), !e.isEqual(y.min())) {
                const t = this.Yh._h(i).next(t => this.Yh.dh(i, i.Oh, e));
                r.push(t);
            }
            return xe.vn(r).next(() => n.apply(i)).next(() => this.vu.Jn(i, h));
        }).then(t => (this.gu = s, t));
    }
    /**
     * 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.
     */    static Ou(t, e, s) {
        // Always persist target data if we don't already have a resume token.
        if (ve(e.resumeToken.rt() > 0), 0 === t.resumeToken.rt()) return !0;
        // 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.
                return e.Ee.D() - t.Ee.D() >= this.xu || s.Ts.size + s.Es.size + s.Is.size > 0;
        // 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.
        }
    /**
     * Notify local store of the changed views to locally pin documents.
     */    async Bu(t) {
        try {
            await this.persistence.runTransaction("notifyLocalViewChanges", "readwrite", e => xe.forEach(t, t => xe.forEach(t.hr, s => this.persistence.hh.yh(e, t.targetId, s)).next(() => xe.forEach(t.or, s => this.persistence.hh.vh(e, t.targetId, s)))));
        } catch (t) {
            if (!Gs(t)) throw t;
            // 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.
            ge("LocalStore", "Failed to update sequence numbers: " + t);
        }
        for (const e of t) {
            const t = e.targetId;
            if (!e.fromCache) {
                const e = this.gu.get(t), s = e.Ee, i = e.Re(s);
                // Advance the last limbo free snapshot version
                                this.gu = this.gu.Ae(t, 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.
     */    qu(t) {
        return this.persistence.runTransaction("Get next mutation batch", "readonly", e => (void 0 === t && (t = -1), 
        this.Wn.ea(e, t)));
    }
    /**
     * Read the current value of a Document with a given key or null if not
     * found - used for testing.
     */    Uu(t) {
        return this.persistence.runTransaction("read document", "readonly", e => this.vu.Kn(e, t));
    }
    /**
     * 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`.
     */    Qu(t) {
        return this.persistence.runTransaction("Allocate target", "readwrite", e => {
            let s;
            return this.Yh.gh(e, t).next(i => i ? (
            // This target has been listened to previously, so reuse the
            // previous targetID.
            // TODO(mcg): freshen last accessed date?
            s = i, xe.resolve(s)) : this.Yh.oh(e).next(i => (s = new Lt(t, i, 0 /* Listen */ , e.Oh), 
            this.Yh.fh(e, s).next(() => s))));
        }).then(e => (null === this.gu.get(e.targetId) && (this.gu = this.gu.Ae(e.targetId, e), 
        this.pu.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.
    gh(t, e) {
        const s = this.pu.get(e);
        return void 0 !== s ? xe.resolve(this.gu.get(s)) : this.Yh.gh(t, e);
    }
    /**
     * Unpin 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.
    Wu(t, e) {
        const s = this.gu.get(t), i = e ? "readwrite" : "readwrite-primary";
        return this.persistence.runTransaction("Release target", i, t => e ? xe.resolve() : this.persistence.hh.removeTarget(t, s)).then(() => {
            this.gu = this.gu.remove(t), this.pu.delete(s.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.
     */    ju(t, e) {
        let s = y.min(), i = ee();
        return this.persistence.runTransaction("Execute query", "readonly", n => this.gh(n, t.ee()).next(t => {
            if (t) return s = t.lastLimboFreeSnapshotVersion, this.Yh.Sh(n, t.targetId).next(t => {
                i = t;
            });
        }).next(() => this.Vu.Zn(n, t, e ? s : y.min(), e ? i : ee())).next(t => ({
            documents: t,
            Ku: i
        })));
    }
    ku(t, e, s) {
        const i = e.batch, n = i.keys();
        let r = xe.resolve();
        return n.forEach(n => {
            r = r.next(() => s.Ln(t, n)).next(t => {
                let r = t;
                const h = e.Rn.get(n);
                ve(null !== h), (!r || r.version.S(h) < 0) && (r = i.at(n, r, e), r && 
                // 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.
                s.Nn(r, e.wn));
            });
        }), r.next(() => this.Wn.ra(t, i));
    }
    Iu(t) {
        return this.persistence.runTransaction("Collect garbage", "readwrite-primary", e => t.mu(e, this.gu));
    }
}

/**
 * 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.
 */ ai.xu = 3e8;

/**
 * An implementation of LocalStore that provides additional functionality
 * for MultiTabSyncEngine.
 */
// PORTING NOTE: Web only.
class ui extends ai {
    constructor(t, e, s) {
        super(t, e, s), this.persistence = t, this.Wn = t.vo(s), this.bu = t.Co(), this.Yh = t.Do();
    }
    /** Starts the LocalStore. */    start() {
        return this.Gu();
    }
    /** Returns the local view of the documents affected by a mutation batch. */    zu(t) {
        return this.persistence.runTransaction("Lookup mutation documents", "readonly", e => this.Wn.ta(e, t).next(t => t ? this.vu.Yn(e, t) : xe.resolve(null)));
    }
    Hu(t) {
        this.Wn.ha(t);
    }
    ao(t) {
        this.persistence.ao(t);
    }
    bo() {
        return this.persistence.bo();
    }
    Yu(t) {
        const e = this.gu.get(t);
        return e ? Promise.resolve(e.target) : this.persistence.runTransaction("Get target data", "readonly", e => this.Yh.si(e, t).next(t => t ? t.target : null));
    }
    /**
     * 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 changes since
     * the point of rejection.
     */    Kr() {
        return this.persistence.runTransaction("Get new document changes", "readonly", t => this.bu.Kr(t, this.yu)).then(({Gr: t, readTime: e}) => (this.yu = e, 
        t));
    }
    /**
     * Reads the newest document change from persistence and forwards the internal
     * synchronization marker so that calls to `getNewDocumentChanges()`
     * only return changes that happened after client initialization.
     */    async Gu() {
        this.yu = await this.persistence.runTransaction("Synchronize last document change read time", "readonly", t => this.bu.Hr(t));
    }
}

/**
 * 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.
 * @return A Promise that resolves after we recovered, or the original error.
 */ async function ci(t) {
    if (t.code !== w.FAILED_PRECONDITION || t.message !== qe) throw t;
    ge("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.
 */
/**
 * 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 _i {
    constructor() {
        // A set of outstanding references to a document sorted by key.
        this.Ju = new jt(li.Xu), 
        // A set of outstanding references to a document sorted by target id.
        this.Zu = new jt(li.tc);
    }
    /** Returns true if the reference set contains no references. */    B() {
        return this.Ju.B();
    }
    /** Adds a reference to the given document key for the given ID. */    yh(t, e) {
        const s = new li(t, e);
        this.Ju = this.Ju.add(s), this.Zu = this.Zu.add(s);
    }
    /** Add references to the given document keys for the given ID. */    ec(t, e) {
        t.forEach(t => this.yh(t, e));
    }
    /**
     * Removes a reference to the given document key for the given
     * ID.
     */    vh(t, e) {
        this.sc(new li(t, e));
    }
    ic(t, e) {
        t.forEach(t => this.vh(t, e));
    }
    /**
     * Clears all references with a given ID. Calls removeRef() for each key
     * removed.
     */    nc(t) {
        const e = C.EMPTY, s = new li(e, t), i = new li(e, t + 1), n = [];
        return this.Zu.Ke([ s, i ], t => {
            this.sc(t), n.push(t.key);
        }), n;
    }
    rc() {
        this.Ju.forEach(t => this.sc(t));
    }
    sc(t) {
        this.Ju = this.Ju.delete(t), this.Zu = this.Zu.delete(t);
    }
    hc(t) {
        const e = C.EMPTY, s = new li(e, t), i = new li(e, t + 1);
        let n = ee();
        return this.Zu.Ke([ s, i ], t => {
            n = n.add(t.key);
        }), n;
    }
    Ch(t) {
        const e = new li(t, 0), s = this.Ju.ze(e);
        return null !== s && t.isEqual(s.key);
    }
}

class li {
    constructor(t, e) {
        this.key = t, this.oc = e;
    }
    /** Compare by key then by ID */    static Xu(t, e) {
        return C.N(t.key, e.key) || Ce(t.oc, e.oc);
    }
    /** Compare by ID then by key */    static tc(t, e) {
        return Ce(t.oc, e.oc) || C.N(t.key, e.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.
 */
/**
 * Validates that no arguments were passed in the invocation of functionName.
 *
 * Forward the magic "arguments" variable as second parameter on which the
 * parameter validation is performed:
 * validateNoArgs('myFunction', arguments);
 */ function di(t, e) {
    if (0 !== e.length) throw new R(w.INVALID_ARGUMENT, `Function ${t}() does not support arguments, ` + "but was called with " + Ci(e.length, "argument") + ".");
}

/**
 * Validates the invocation of functionName has the exact number of arguments.
 *
 * Forward the magic "arguments" variable as second parameter on which the
 * parameter validation is performed:
 * validateExactNumberOfArgs('myFunction', arguments, 2);
 */ function fi(t, e, s) {
    if (e.length !== s) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires ` + Ci(s, "argument") + ", but was called with " + Ci(e.length, "argument") + ".");
}

/**
 * Validates the invocation of functionName has at least the provided number of
 * arguments (but can have many more).
 *
 * Forward the magic "arguments" variable as second parameter on which the
 * parameter validation is performed:
 * validateAtLeastNumberOfArgs('myFunction', arguments, 2);
 */ function Ti(t, e, s) {
    if (e.length < s) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires at least ` + Ci(s, "argument") + ", but was called with " + Ci(e.length, "argument") + ".");
}

/**
 * Validates the invocation of functionName has number of arguments between
 * the values provided.
 *
 * Forward the magic "arguments" variable as second parameter on which the
 * parameter validation is performed:
 * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);
 */ function Ei(t, e, s, i) {
    if (e.length < s || e.length > i) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires between ${s} and ` + `${i} arguments, but was called with ` + Ci(e.length, "argument") + ".");
}

/**
 * Validates the provided argument is an array and has as least the expected
 * number of elements.
 */
/**
 * Validates the provided positional argument has the native JavaScript type
 * using typeof checks.
 */
function Ii(t, e, s, i) {
    Vi(t, e, `${Di(s)} argument`, i);
}

/**
 * Validates the provided argument has the native JavaScript type using
 * typeof checks or is undefined.
 */ function wi(t, e, s, i) {
    void 0 !== i && Ii(t, e, s, i);
}

/**
 * Validates the provided named option has the native JavaScript type using
 * typeof checks.
 */ function Ri(t, e, s, i) {
    Vi(t, e, `${s} option`, i);
}

/**
 * Validates the provided named option has the native JavaScript type using
 * typeof checks or is undefined.
 */ function Ai(t, e, s, i) {
    void 0 !== i && Ri(t, e, s, i);
}

function mi(t, e, s, i, n) {
    void 0 !== i && function(t, e, s, i, n) {
        if (!(i instanceof Array)) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${e} ` + `option to be an array, but it was: ${pi(i)}`);
        for (let r = 0; r < i.length; ++r) if (!n(i[r])) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires all ${e} ` + `elements to be ${s}, but the value at index ${r} ` + `was: ${pi(i[r])}`);
    }(t, e, s, i, n);
}

/**
 * Validates that the provided named option equals one of the expected values.
 */
/**
 * Validates that the provided named option equals one of the expected values or
 * is undefined.
 */
function Pi(t, e, s, i, n) {
    void 0 !== i && function(t, e, s, i, n) {
        const r = [];
        for (const t of n) {
            if (t === i) return;
            r.push(pi(t));
        }
        const h = pi(i);
        throw new R(w.INVALID_ARGUMENT, `Invalid value ${h} provided to function ${t}() for option ` + `"${s}". Acceptable values: ${r.join(", ")}`);
    }(t, 0, s, i, n);
}

/**
 * Validates that the provided argument is a valid enum.
 *
 * @param functionName Function making the validation call.
 * @param enums Array containing all possible values for the enum.
 * @param position Position of the argument in `functionName`.
 * @param argument Argument to validate.
 * @return The value as T if the argument can be converted.
 */
/** Helper to validate the type of a provided input. */
function Vi(t, e, s, i) {
    let n = !1;
    if (n = "object" === e ? gi(i) : "non-empty string" === e ? "string" == typeof i && "" !== i : typeof i === e, 
    !n) {
        const n = pi(i);
        throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${s} ` + `to be of type ${e}, but it was: ${n}`);
    }
}

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

/** Returns a string describing the type / value of the provided input. */ function pi(t) {
    if (void 0 === t) return "undefined";
    if (null === t) return "null";
    if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), 
    JSON.stringify(t);
    if ("number" == typeof t || "boolean" == typeof t) return "" + t;
    if ("object" == typeof t) {
        if (t instanceof Array) return "an array";
        {
            const e = 
            /** Hacky method to try to get the constructor name for an object. */
            function(t) {
                if (t.constructor) {
                    const e = /function\s+([^\s(]+)\s*\(/.exec(t.constructor.toString());
                    if (e && e.length > 1) return e[1];
                }
                return null;
            }
            /** Validates the provided argument is defined. */ (t);
            return e ? `a custom ${e} object` : "an object";
        }
    }
    return "function" == typeof t ? "a function" : be();
}

function yi(t, e, s) {
    if (void 0 === s) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires a valid ${Di(e)} ` + "argument, but it was undefined.");
}

/**
 * Validates the provided positional argument is an object, and its keys and
 * values match the expected keys and types provided in optionTypes.
 */ function bi(t, e, s) {
    N(e, (e, i) => {
        if (s.indexOf(e) < 0) throw new R(w.INVALID_ARGUMENT, `Unknown option '${e}' passed to function ${t}(). ` + "Available options: " + s.join(", "));
    });
}

/**
 * Helper method to throw an error that the provided argument did not pass
 * an instanceof check.
 */ function vi(t, e, s, i) {
    const n = pi(i);
    return new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${Di(s)} ` + `argument to be a ${e}, but it was: ${n}`);
}

function Si(t, e, s) {
    if (s <= 0) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${Di(e)} argument to be a positive number, but it was: ${s}.`);
}

/** Converts a number to its english word representation */ function Di(t) {
    switch (t) {
      case 1:
        return "first";

      case 2:
        return "second";

      case 3:
        return "third";

      default:
        return t + "th";
    }
}

/**
 * Formats the given word as plural conditionally given the preceding number.
 */ function Ci(t, e) {
    return `${t} ${e}` + (1 === t ? "" : "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.
 */
/** Helper function to assert Uint8Array is available at runtime. */ function Fi() {
    if ("undefined" == typeof Uint8Array) throw new R(w.UNIMPLEMENTED, "Uint8Arrays are not available in this environment.");
}

/** Helper function to assert Base64 functions are available at runtime. */ function Ni() {
    if (!Ae.nt().ac) throw new R(w.UNIMPLEMENTED, "Blobs are unavailable in Firestore in this environment.");
}

/**
 * Immutable class holding a blob (binary data).
 * This class is directly exposed in the public API.
 *
 * Note that while you can't hide the constructor in JavaScript code, we are
 * using the hack above to make sure no-one outside this module can call it.
 */ class $i {
    constructor(t) {
        Ni(), this.uc = t;
    }
    static fromBase64String(t) {
        fi("Blob.fromBase64String", arguments, 1), Ii("Blob.fromBase64String", "string", 1, t), 
        Ni();
        try {
            return new $i(k.fromBase64String(t));
        } catch (t) {
            throw new R(w.INVALID_ARGUMENT, "Failed to construct Blob from Base64 string: " + t);
        }
    }
    static fromUint8Array(t) {
        if (fi("Blob.fromUint8Array", arguments, 1), Fi(), !(t instanceof Uint8Array)) throw vi("Blob.fromUint8Array", "Uint8Array", 1, t);
        return new $i(k.fromUint8Array(t));
    }
    toBase64() {
        return fi("Blob.toBase64", arguments, 0), Ni(), this.uc.toBase64();
    }
    toUint8Array() {
        return fi("Blob.toUint8Array", arguments, 0), Fi(), this.uc.toUint8Array();
    }
    toString() {
        return "Blob(base64: " + this.toBase64() + ")";
    }
    isEqual(t) {
        return this.uc.isEqual(t.uc);
    }
}

/**
 * @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 objects that are a part of this API are exposed to third-parties as
// compiled javascript so we want to flag our private members with a leading
// underscore to discourage their use.
/**
 * 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).
 */ class ki {
    /**
     * 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(...t) {
        !function(t, e, s, i) {
            if (!(e instanceof Array) || e.length < i) throw new R(w.INVALID_ARGUMENT, `Function ${t}() requires its ${s} argument to be an ` + "array with at least " + `${Ci(i, "element")}.`);
        }("FieldPath", t, "fieldNames", 1);
        for (let e = 0; e < t.length; ++e) if (Ii("FieldPath", "string", e, t[e]), 0 === t[e].length) throw new R(w.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty.");
        this.cc = new D(t);
    }
    static documentId() {
        return ki._c;
    }
    isEqual(t) {
        if (!(t instanceof ki)) throw vi("isEqual", "FieldPath", 1, t);
        return this.cc.isEqual(t.cc);
    }
}

/**
 * Internal Note: The backend doesn't technically support querying by
 * document ID. Instead it queries by the entire document name (full path
 * included), but in the cases we currently support documentId(), the net
 * effect is the same.
 */ ki._c = new ki(D.J().j());

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

/**
 * Parses a field path string into a FieldPath, treating dots as separators.
 */
/**
 * @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 opaque base class for FieldValue sentinel objects in our public API,
 * with public static methods for creating said sentinel objects.
 */
class Mi {
    constructor(t) {
        this.lc = t;
    }
}

class Oi extends Mi {
    constructor() {
        super("FieldValue.delete");
    }
    Di(t) {
        if (2 /* MergeSet */ !== t.dc) throw 1 /* Update */ === t.dc ? t.fc("FieldValue.delete() can only appear at the top level of your update data") : t.fc("FieldValue.delete() 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 t.Vt.push(t.path), null;
    }
    isEqual(t) {
        return t instanceof Oi;
    }
}

class xi extends Mi {
    constructor() {
        super("FieldValue.serverTimestamp");
    }
    Di(t) {
        return new ct(t.path, nt.instance);
    }
    isEqual(t) {
        return t instanceof xi;
    }
}

class Bi extends Mi {
    constructor(t) {
        super("FieldValue.arrayUnion"), this.Tc = t;
    }
    Di(t) {
        // Although array transforms are used with writes, the actual elements
        // being uniomed or removed are not considered writes since they cannot
        // contain any FieldValue sentinels, etc.
        const e = new zi({
            dc: 3 /* Argument */ ,
            methodName: this.lc,
            Ec: !0
        }, t.ii, t.serializer, t.ignoreUndefinedProperties), s = this.Tc.map(t => Yi(t, e)), i = new rt(s);
        return new ct(t.path, i);
    }
    isEqual(t) {
        // TODO(mrschmidt): Implement isEquals
        return this === t;
    }
}

class qi extends Mi {
    constructor(t) {
        super("FieldValue.arrayRemove"), this.Tc = t;
    }
    Di(t) {
        // Although array transforms are used with writes, the actual elements
        // being unioned or removed are not considered writes since they cannot
        // contain any FieldValue sentinels, etc.
        const e = new zi({
            dc: 3 /* Argument */ ,
            methodName: this.lc,
            Ec: !0
        }, t.ii, t.serializer, t.ignoreUndefinedProperties), s = this.Tc.map(t => Yi(t, e)), i = new ht(s);
        return new ct(t.path, i);
    }
    isEqual(t) {
        // TODO(mrschmidt): Implement isEquals
        return this === t;
    }
}

class Ui extends Mi {
    constructor(t) {
        super("FieldValue.increment"), this.Ic = t;
    }
    Di(t) {
        const e = new zi({
            dc: 3 /* Argument */ ,
            methodName: this.lc
        }, t.ii, t.serializer, t.ignoreUndefinedProperties), s = Yi(this.Ic, e), i = new ot(t.serializer, s);
        return new ct(t.path, i);
    }
    isEqual(t) {
        // TODO(mrschmidt): Implement isEquals
        return this === 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.
 */
/**
 * Immutable class representing a geo point as latitude-longitude pair.
 * This class is directly exposed in the public API, including its constructor.
 */
class Qi {
    constructor(t, e) {
        if (fi("GeoPoint", arguments, 2), Ii("GeoPoint", "number", 1, t), Ii("GeoPoint", "number", 2, e), 
        !isFinite(t) || t < -90 || t > 90) throw new R(w.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + t);
        if (!isFinite(e) || e < -180 || e > 180) throw new R(w.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + e);
        this.wc = t, this.Rc = e;
    }
    /**
     * Returns the latitude of this geo point, a number between -90 and 90.
     */    get latitude() {
        return this.wc;
    }
    /**
     * Returns the longitude of this geo point, a number between -180 and 180.
     */    get longitude() {
        return this.Rc;
    }
    isEqual(t) {
        return this.wc === t.wc && this.Rc === t.Rc;
    }
    /**
     * Actually private to JS consumers of our API, so this function is prefixed
     * with an underscore.
     */    p(t) {
        return Ce(this.wc, t.wc) || Ce(this.Rc, t.Rc);
    }
}

/**
 * @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 Wi = /^__.*__$/;

/** The result of parsing document data (e.g. for a setData call). */ class ji {
    constructor(t, e, s) {
        this.data = t, this.Vt = e, this.fieldTransforms = s;
    }
    Ac(t, e) {
        const s = [];
        return null !== this.Vt ? s.push(new Tt(t, this.data, this.Vt, e)) : s.push(new ft(t, this.data, e)), 
        this.fieldTransforms.length > 0 && s.push(new Et(t, this.fieldTransforms)), s;
    }
}

/** The result of parsing "update" data (i.e. for an updateData call). */ class Ki {
    constructor(t, e, s) {
        this.data = t, this.Vt = e, this.fieldTransforms = s;
    }
    Ac(t, e) {
        const s = [ new Tt(t, this.data, this.Vt, e) ];
        return this.fieldTransforms.length > 0 && s.push(new Et(t, this.fieldTransforms)), 
        s;
    }
}

function Gi(t) {
    switch (t) {
      case 0 /* Set */ :
 // fall through
              case 2 /* MergeSet */ :
 // fall through
              case 1 /* Update */ :
        return !0;

      case 3 /* Argument */ :
      case 4 /* ArrayArgument */ :
        return !1;

      default:
        throw be();
    }
}

/** A "context" object passed around while parsing user data. */ class zi {
    /**
     * 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(t, e, s, i, n, r) {
        this.settings = t, this.ii = e, this.serializer = s, this.ignoreUndefinedProperties = i, 
        // Minor hack: If fieldTransforms is undefined, we assume this is an
        // external call and we need to validate the entire path.
        void 0 === n && this.mc(), this.fieldTransforms = n || [], this.Vt = r || [];
    }
    get path() {
        return this.settings.path;
    }
    get dc() {
        return this.settings.dc;
    }
    /** Returns a new context with the specified settings overwritten. */    Pc(t) {
        return new zi(Object.assign(Object.assign({}, this.settings), t), this.ii, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.Vt);
    }
    Vc(t) {
        var e;
        const s = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), i = this.Pc({
            path: s,
            Ec: !1
        });
        return i.gc(t), i;
    }
    pc(t) {
        var e;
        const s = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), i = this.Pc({
            path: s,
            Ec: !1
        });
        return i.mc(), i;
    }
    yc(t) {
        // TODO(b/34871131): We don't support array paths right now; so make path
        // undefined.
        return this.Pc({
            path: void 0,
            Ec: !0
        });
    }
    fc(t) {
        const e = !this.path || this.path.B() ? "" : ` (found in field ${this.path.toString()})`;
        return new R(w.INVALID_ARGUMENT, `Function ${this.settings.methodName}() called with invalid data. ` + t + e);
    }
    /** Returns 'true' if 'fieldPath' was traversed when creating this context. */    contains(t) {
        return void 0 !== this.Vt.find(e => t.q(e)) || void 0 !== this.fieldTransforms.find(e => t.q(e.field));
    }
    mc() {
        // TODO(b/34871131): Remove null check once we have proper paths for fields
        // within arrays.
        if (this.path) for (let t = 0; t < this.path.length; t++) this.gc(this.path.get(t));
    }
    gc(t) {
        if (0 === t.length) throw this.fc("Document fields must not be empty");
        if (Gi(this.dc) && Wi.test(t)) throw this.fc('Document fields cannot begin and end with "__"');
    }
}

/**
 * Helper for parsing raw user input (provided via the API) into internal model
 * classes.
 */ class Hi {
    constructor(t, e, s) {
        this.ii = t, this.ignoreUndefinedProperties = e, this.serializer = s || Ae.nt().bc(t);
    }
    /** Parse document data from a non-merge set() call. */    vc(t, e) {
        const s = this.Sc(0 /* Set */ , t);
        Zi("Data must be an object, but it was:", s, e);
        const i = Ji(e, s);
        return new ji(new Rt(i), 
        /* fieldMask= */ null, s.fieldTransforms);
    }
    /** Parse document data from a set() call with '{merge:true}'. */    Dc(t, e, s) {
        const i = this.Sc(2 /* MergeSet */ , t);
        Zi("Data must be an object, but it was:", i, e);
        const n = Ji(e, i);
        let r, h;
        if (s) {
            const e = [];
            for (const n of s) {
                let s;
                if (n instanceof ki) s = n.cc; else {
                    if ("string" != typeof n) throw be();
                    s = en(t, n);
                }
                if (!i.contains(s)) throw new R(w.INVALID_ARGUMENT, `Field '${s}' is specified in your field mask but missing from your input data.`);
                sn(e, s) || e.push(s);
            }
            r = new ut(e), h = i.fieldTransforms.filter(t => r.dt(t.field));
        } else r = new ut(i.Vt), h = i.fieldTransforms;
        return new ji(new Rt(n), r, h);
    }
    /** Parse update data from an update() call. */    Cc(t, e) {
        const s = this.Sc(1 /* Update */ , t);
        Zi("Data must be an object, but it was:", s, e);
        const i = [], n = new At;
        N(e, (e, r) => {
            const h = en(t, e), o = s.pc(h);
            if (r instanceof Oi) 
            // Add it to the field mask, but don't add anything to updateData.
            i.push(h); else {
                const t = Yi(r, o);
                null != t && (i.push(h), n.set(h, t));
            }
        });
        const r = new ut(i);
        return new Ki(n.yt(), r, s.fieldTransforms);
    }
    /** Parse update data from a list of field/value arguments. */    Fc(t, e, s, i) {
        const n = this.Sc(1 /* Update */ , t), r = [ tn(t, e) ], h = [ s ];
        if (i.length % 2 != 0) throw new R(w.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 < i.length; e += 2) r.push(tn(t, i[e])), h.push(i[e + 1]);
        const o = [], a = new At;
        // We iterate in reverse order to pick the last value for a field if the
        // user specified the field multiple times.
        for (let t = r.length - 1; t >= 0; --t) if (!sn(o, r[t])) {
            const e = r[t], s = h[t], i = n.pc(e);
            if (s instanceof Oi) 
            // Add it to the field mask, but don't add anything to updateData.
            o.push(e); else {
                const t = Yi(s, i);
                null != t && (o.push(e), a.set(e, t));
            }
        }
        const u = new ut(o);
        return new Ki(a.yt(), u, n.fieldTransforms);
    }
    /** Creates a new top-level parse context. */    Sc(t, e) {
        return new zi({
            dc: t,
            methodName: e,
            path: D.G,
            Ec: !1
        }, this.ii, this.serializer, this.ignoreUndefinedProperties);
    }
    /**
     * 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).
     */    Nc(t, e, s = !1) {
        return Yi(e, this.Sc(s ? 4 /* ArrayArgument */ : 3 /* 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.
 * @return The parsed value, or null if the value was a FieldValue sentinel
 * that should not be included in the resulting parsed data.
 */ function Yi(t, e) {
    if (Xi(t)) return Zi("Unsupported field value:", e, t), Ji(t, e);
    if (t instanceof Mi) 
    // FieldValues usually parse into transforms (except FieldValue.delete())
    // 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(t, e) {
        // Sentinels are only supported with writes, and not within arrays.
        if (!Gi(e.dc)) throw e.fc(`${t.lc}() can only be used with update() and set()`);
        if (null === e.path) throw e.fc(`${t.lc}() is not currently supported inside arrays`);
        const s = t.Di(e);
        s && e.fieldTransforms.push(s);
    }
    /**
 * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)
 *
 * @return The parsed value
 */ (t, e), 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.
    e.path && e.Vt.push(e.path), t 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 (e.settings.Ec && 4 /* ArrayArgument */ !== e.dc) throw e.fc("Nested arrays are not supported");
        return function(t, e) {
            const s = [];
            let i = 0;
            for (const n of t) {
                let t = Yi(n, e.yc(i));
                null == t && (
                // Just include nulls in the array for fields being replaced with a
                // sentinel.
                t = {
                    nullValue: "NULL_VALUE"
                }), s.push(t), i++;
            }
            return {
                arrayValue: {
                    values: s
                }
            };
        }(t, e);
    }
    return function(t, e) {
        if (null === t) return {
            nullValue: "NULL_VALUE"
        };
        if ("number" == typeof t) return e.serializer.ai(t);
        if ("boolean" == typeof t) return {
            booleanValue: t
        };
        if ("string" == typeof t) return {
            stringValue: t
        };
        if (t instanceof Date) {
            const s = p.fromDate(t);
            return {
                timestampValue: e.serializer.C(s)
            };
        }
        if (t instanceof p) {
            // 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 s = new p(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));
            return {
                timestampValue: e.serializer.C(s)
            };
        }
        if (t instanceof Qi) return {
            geoPointValue: {
                latitude: t.latitude,
                longitude: t.longitude
            }
        };
        if (t instanceof $i) return {
            bytesValue: e.serializer.ui(t)
        };
        if (t instanceof Yn) {
            const s = e.ii, i = t.firestore.$c;
            if (!i.isEqual(s)) throw e.fc("Document reference is for database " + `${i.projectId}/${i.database} but should be ` + `for database ${s.projectId}/${s.database}`);
            return {
                referenceValue: e.serializer._i(t.kc.path, t.firestore.$c)
            };
        }
        if (void 0 === t && e.ignoreUndefinedProperties) return null;
        throw e.fc(`Unsupported field value: ${pi(t)}`);
    }
    /**
 * 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.
 */ (t, e);
}

function Ji(t, e) {
    const s = {};
    return $(t) ? 
    // If we encounter an empty object, we explicitly add it to the update
    // mask to ensure that the server creates a map entry.
    e.path && e.path.length > 0 && e.Vt.push(e.path) : N(t, (t, i) => {
        const n = Yi(i, e.Vc(t));
        null != n && (s[t] = n);
    }), {
        mapValue: {
            fields: s
        }
    };
}

function Xi(t) {
    return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof p || t instanceof Qi || t instanceof $i || t instanceof Yn || t instanceof Mi);
}

function Zi(t, e, s) {
    if (!Xi(s) || !gi(s)) {
        const i = pi(s);
        throw "an object" === i ? e.fc(t + " a custom object") : e.fc(t + " " + i);
    }
}

/**
 * Helper that calls fromDotSeparatedString() but wraps any error thrown.
 */ function tn(t, e) {
    if (e instanceof ki) return e.cc;
    if ("string" == typeof e) return en(t, e);
    throw new R(w.INVALID_ARGUMENT, `Function ${t}() called with invalid data. ${"Field path arguments must be of type string or FieldPath."}`);
}

/**
 * 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.
 */ function en(t, e) {
    try {
        return function(t) {
            if (t.search(Li) >= 0) throw new R(w.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not contain ` + "'~', '*', '/', '[', or ']'");
            try {
                return new ki(...t.split("."));
            } catch (e) {
                throw new R(w.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, ` + "begin with '.', end with '.', or contain '..'");
            }
        }(e).cc;
    } catch (e) {
        const i = (s = e) instanceof Error ? s.message : s.toString();
        throw new R(w.INVALID_ARGUMENT, `Function ${t}() called with invalid data. ${i}`);
    }
    /**
 * Extracts the message from a caught exception, which should be an Error object
 * though JS doesn't guarantee that.
 */
    var s;
    /** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */}

function sn(t, e) {
    return t.some(t => t.isEqual(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.
 */
/**
 * 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 nn {
    constructor(t, e, s, i, n, r) {
        this.Tr = t, this.Lc = s, this.Mc = i, this.Oc = n, this.listener = r, this.state = 0 /* Initial */ , 
        /**
         * A close count that's incremented every time the stream is closed; used by
         * getCloseGuardedDispatcher() to invalidate callbacks that happen after
         * close.
         */
        this.xc = 0, this.Bc = null, this.stream = null, this.$a = new Ge(t, e);
    }
    /**
     * 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.
     */    qc() {
        return 1 /* Starting */ === this.state || 2 /* Open */ === this.state || 4 /* Backoff */ === this.state;
    }
    /**
     * Returns true if the underlying RPC is open (the onOpen() listener has been
     * called) and the stream is ready for outbound requests.
     */    Uc() {
        return 2 /* Open */ === 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() {
        3 /* Error */ !== this.state ? this.auth() : this.Qc();
    }
    /**
     * 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.qc() && await this.close(0 /* 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.
     */    Wc() {
        this.state = 0 /* Initial */ , this.$a.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.
     */    jc() {
        // 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.Uc() && null === this.Bc && (this.Bc = this.Tr.yr(this.Lc, 6e4, () => this.Kc()));
    }
    /** Sends a message to the underlying stream. */    Gc(t) {
        this.zc(), this.stream.send(t);
    }
    /** Called by the idle timer when the stream should close due to inactivity. */    async Kc() {
        if (this.Uc()) 
        // 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 /* Initial */);
    }
    /** Marks the stream as active again. */    zc() {
        this.Bc && (this.Bc.cancel(), this.Bc = 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(t, e) {
        // Cancel any outstanding timers (they're guaranteed not to execute).
        this.zc(), this.$a.cancel(), 
        // Invalidates any stream-related callbacks (e.g. from auth or the
        // underlying stream), guaranteeing they won't execute.
        this.xc++, 3 /* Error */ !== t ? 
        // If this is an intentional close ensure we don't delay our next connection attempt.
        this.$a.reset() : e && e.code === w.RESOURCE_EXHAUSTED ? (
        // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)
        pe(e.toString()), pe("Using maximum backoff delay to prevent overloading the backend."), 
        this.$a.Vr()) : e && e.code === w.UNAUTHENTICATED && 
        // "unauthenticated" error means the token was rejected. Try force refreshing it in case it
        // just expired.
        this.Oc._(), 
        // Clean up the underlying stream because we are no longer interested in events.
        null !== this.stream && (this.Hc(), 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 = t, 
        // Notify the listener that the stream closed.
        await this.listener.Yc(e);
    }
    /**
     * Can be overridden to perform additional cleanup before the stream is closed.
     * Calling super.tearDown() is not required.
     */    Hc() {}
    auth() {
        this.state = 1 /* Starting */;
        const t = this.Jc(this.xc), e = this.xc;
        // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.
                this.Oc.getToken().then(t => {
            // 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.xc === e && 
            // 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.Xc(t);
        }, e => {
            t(() => {
                const t = new R(w.UNKNOWN, "Fetching auth token failed: " + e.message);
                return this.Zc(t);
            });
        });
    }
    Xc(t) {
        const e = this.Jc(this.xc);
        this.stream = this.t_(t), this.stream.e_(() => {
            e(() => (this.state = 2 /* Open */ , this.listener.e_()));
        }), this.stream.Yc(t => {
            e(() => this.Zc(t));
        }), this.stream.onMessage(t => {
            e(() => this.onMessage(t));
        });
    }
    Qc() {
        this.state = 4 /* Backoff */ , this.$a.gr(async () => {
            this.state = 0 /* Initial */ , this.start();
        });
    }
    // Visible for tests
    Zc(t) {
        // 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 ge("PersistentStream", `close with error: ${t}`), this.stream = null, this.close(3 /* Error */ , t);
    }
    /**
     * 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.
     */    Jc(t) {
        return e => {
            this.Tr.uo(() => this.xc === t ? e() : (ge("PersistentStream", "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 rn extends nn {
    constructor(t, e, s, i, n) {
        super(t, "listen_stream_connection_backoff" /* ListenStreamConnectionBackoff */ , "listen_stream_idle" /* ListenStreamIdle */ , e, s, n), 
        this.serializer = i;
    }
    t_(t) {
        return this.Mc.s_("Listen", t);
    }
    onMessage(t) {
        // A successful response means the stream is healthy
        this.$a.reset();
        const e = this.serializer.pi(t), s = this.serializer.bi(t);
        return this.listener.i_(e, s);
    }
    /**
     * 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.
     */    n_(t) {
        const e = {};
        e.database = this.serializer.wi, e.addTarget = this.serializer.ee(t);
        const s = this.serializer.zi(t);
        s && (e.labels = s), this.Gc(e);
    }
    /**
     * Unregisters interest in the results of the target associated with the
     * given targetId.
     */    r_(t) {
        const e = {};
        e.database = this.serializer.wi, e.removeTarget = t, this.Gc(e);
    }
}

/**
 * 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 hn extends nn {
    constructor(t, e, s, i, n) {
        super(t, "write_stream_connection_backoff" /* WriteStreamConnectionBackoff */ , "write_stream_idle" /* WriteStreamIdle */ , e, s, n), 
        this.serializer = i, this.h_ = !1, 
        /**
         * The last received stream token from the server, used to acknowledge which
         * responses the client has processed. Stream tokens are opaque checkpoint
         * markers whose only real value is their inclusion in the next request.
         *
         * PersistentWriteStream manages propagating this value from responses to the
         * next request.
         */
        this.lastStreamToken = k.ht;
    }
    /**
     * Tracks whether or not a handshake has been successfully exchanged and
     * the stream is ready to accept mutations.
     */    get o_() {
        return this.h_;
    }
    // Override of PersistentStream.start
    start() {
        this.h_ = !1, super.start();
    }
    Hc() {
        this.h_ && this.a_([]);
    }
    t_(t) {
        return this.Mc.s_("Write", t);
    }
    onMessage(t) {
        if (
        // Always capture the last stream token.
        ve(!!t.streamToken), this.lastStreamToken = this.serializer.ci(t.streamToken), this.h_) {
            // 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.$a.reset();
            const e = this.serializer.Mi(t.writeResults, t.commitTime), s = this.serializer.fromVersion(t.commitTime);
            return this.listener.u_(s, e);
        }
        // The first response is always the handshake response
        return ve(!t.writeResults || 0 === t.writeResults.length), this.h_ = !0, this.listener.c_();
    }
    /**
     * 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.
     */    __() {
        // TODO(dimond): Support stream resumption. We intentionally do not set the
        // stream token on the handshake, ignoring any stream token we might have.
        const t = {};
        t.database = this.serializer.wi, this.Gc(t);
    }
    /** Sends a group of mutations to the Firestore backend to apply. */    a_(t) {
        const e = {
            streamToken: this.serializer.ui(this.lastStreamToken),
            writes: t.map(t => this.serializer.vi(t))
        };
        this.Gc(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.
 */
/**
 * 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.
 */
/**
 * An implementation of Datastore that exposes additional state for internal
 * consumption.
 */
class on extends class {
    constructor() {
        // Make sure that the structural type of `Datastore` is unique.
        // See https://github.com/microsoft/TypeScript/issues/5451
        this.l_ = void 0;
    }
} {
    constructor(t, e, s) {
        super(), this.Mc = t, this.credentials = e, this.serializer = s;
    }
    /** Gets an auth token and invokes the provided RPC. */    d_(t, e) {
        return this.credentials.getToken().then(s => this.Mc.d_(t, e, s)).catch(t => {
            throw t.code === w.UNAUTHENTICATED && this.credentials._(), t;
        });
    }
    /** Gets an auth token and invokes the provided RPC with streamed results. */    f_(t, e) {
        return this.credentials.getToken().then(s => this.Mc.f_(t, e, s)).catch(t => {
            throw t.code === w.UNAUTHENTICATED && this.credentials._(), 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 transaction object responsible for accumulating the mutations to
 * perform and the base versions for any documents read.
 */
class an {
    constructor(t) {
        this.T_ = t, 
        // The version of each document that was read during this transaction.
        this.E_ = Zt(), this.mutations = [], this.I_ = !1, 
        /**
         * A deferred usage error that occurred previously in this transaction that
         * will cause the transaction to fail once it actually commits.
         */
        this.w_ = 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.R_ = new Set;
    }
    async A_(t) {
        if (this.m_(), this.mutations.length > 0) throw new R(w.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes.");
        const e = await async function(t, e) {
            const s = Se(t), i = {
                database: s.serializer.wi,
                documents: e.map(t => s.serializer.fi(t))
            }, n = await s.f_("BatchGetDocuments", i), r = new Map;
            n.forEach(t => {
                const e = s.serializer.gi(t);
                r.set(e.key.toString(), e);
            });
            const h = [];
            return e.forEach(t => {
                const e = r.get(t.toString());
                ve(!!e), h.push(e);
            }), h;
        }(this.T_, t);
        return e.forEach(t => {
            t instanceof gt || t instanceof Vt ? this.P_(t) : be();
        }), e;
    }
    set(t, e) {
        this.write(e.Ac(t, this.Rt(t))), this.R_.add(t);
    }
    update(t, e) {
        try {
            this.write(e.Ac(t, this.V_(t)));
        } catch (t) {
            this.w_ = t;
        }
        this.R_.add(t);
    }
    delete(t) {
        this.write([ new It(t, this.Rt(t)) ]), this.R_.add(t);
    }
    async commit() {
        if (this.m_(), this.w_) throw this.w_;
        let t = this.E_;
        // For each mutation, note that the doc was written.
                this.mutations.forEach(e => {
            t = t.remove(e.key);
        }), 
        // For each document that was read but not written to, we want to perform
        // a `verify` operation.
        t.forEach((t, e) => {
            this.mutations.push(new wt(t, this.Rt(t)));
        }), await async function(t, e) {
            const s = Se(t), i = {
                database: s.serializer.wi,
                writes: e.map(t => s.serializer.vi(t))
            }, n = await s.d_("Commit", i);
            return s.serializer.Mi(n.writeResults, n.commitTime);
        }(this.T_, this.mutations), this.I_ = !0;
    }
    P_(t) {
        let e;
        if (t instanceof Vt) e = t.version; else {
            if (!(t instanceof gt)) throw be();
            // For deleted docs, we must use baseVersion 0 when we overwrite them.
            e = y.min();
        }
        const s = this.E_.get(t.key);
        if (null !== s) {
            if (!e.isEqual(s)) 
            // This transaction will fail no matter what.
            throw new R(w.ABORTED, "Document version changed between two reads.");
        } else this.E_ = this.E_.Ae(t.key, e);
    }
    /**
     * Returns the version of this document when it was read in this transaction,
     * as a precondition, or no precondition if it was not read.
     */    Rt(t) {
        const e = this.E_.get(t);
        return !this.R_.has(t) && e ? lt.updateTime(e) : lt.ft();
    }
    /**
     * Returns the precondition for a document if the operation is an update.
     */    V_(t) {
        const e = this.E_.get(t);
        // The first time a document is written, we want to take into account the
        // read time and existence
                if (!this.R_.has(t) && e) {
            if (e.isEqual(y.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 R(w.INVALID_ARGUMENT, "Can't update a document that doesn't exist.");
            // Document exists, base precondition on document update time.
                        return lt.updateTime(e);
        }
        // Document was not read, so we just use the preconditions for a blind
        // update.
        return lt.exists(!0);
    }
    write(t) {
        this.m_(), this.mutations = this.mutations.concat(t);
    }
    m_() {}
}

/**
 * @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.
 */
/**
 * 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 un {
    constructor(t, e) {
        this.Aa = t, this.g_ = e, 
        /** The current OnlineState. */
        this.state = "Unknown" /* 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.p_ = 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.y_ = 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.b_ = !0;
    }
    /**
     * 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.
     */    v_() {
        0 === this.p_ && (this.S_("Unknown" /* Unknown */), this.y_ = this.Aa.yr("online_state_timeout" /* OnlineStateTimeout */ , 1e4, () => (this.y_ = null, 
        this.D_("Backend didn't respond within 10 seconds."), this.S_("Offline" /* 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.
     */    C_(t) {
        "Online" /* Online */ === this.state ? this.S_("Unknown" /* Unknown */) : (this.p_++, 
        this.p_ >= 1 && (this.F_(), this.D_("Connection failed 1 " + `times. Most recent error: ${t.toString()}`), 
        this.S_("Offline" /* 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(t) {
        this.F_(), this.p_ = 0, "Online" /* Online */ === t && (
        // We've connected to watch at least once. Don't warn the developer
        // about being offline going forward.
        this.b_ = !1), this.S_(t);
    }
    S_(t) {
        t !== this.state && (this.state = t, this.g_(t));
    }
    D_(t) {
        const e = `Could not reach Cloud Firestore backend. ${t}\n` + "This 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.b_ ? (pe(e), this.b_ = !1) : ge("OnlineStateTracker", e);
    }
    F_() {
        null !== this.y_ && (this.y_.cancel(), this.y_ = 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.
 */
/**
 * RemoteStore - An interface to remotely stored data, basically providing a
 * wrapper around the Datastore that is more reliable for the rest of the
 * system.
 *
 * RemoteStore is responsible for maintaining the connection to the server.
 * - maintaining a list of active listens.
 * - reconnecting when the connection is dropped.
 * - resuming all the active listens on reconnect.
 *
 * RemoteStore handles all incoming events from the Datastore.
 * - listening to the watch stream and repackaging the events as RemoteEvents
 * - notifying SyncEngine of any changes to the active listens.
 *
 * RemoteStore takes writes from other components and handles them reliably.
 * - pulling pending mutations from LocalStore and sending them to Datastore.
 * - retrying mutations that failed because of network problems.
 * - acking mutations to the SyncEngine once they are accepted or rejected.
 */
class cn {
    constructor(
    /**
     * The local store, used to fill the write pipeline with outbound mutations.
     */
    t, 
    /** The client-side proxy for interacting with the backend. */
    e, s, i, n) {
        this.N_ = t, this.T_ = e, this.Aa = s, 
        /**
         * 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.k_ = [], 
        /**
         * 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.L_ = new Map, this.M_ = null, 
        /**
         * Set to true by enableNetwork() and false by disableNetwork() and indicates
         * the user-preferred network state.
         */
        this.networkEnabled = !1, this.isPrimary = !1, 
        /**
         * When set to `true`, the network was taken offline due to an IndexedDB
         * failure. The state is flipped to `false` when access becomes available
         * again.
         */
        this.O_ = !1, this.x_ = n, this.x_.B_(t => {
            s.uo(async () => {
                this.q_() && (ge("RemoteStore", "Restarting streams for network reachability change."), 
                await this.U_());
            });
        }), this.Q_ = new un(s, i), 
        // Create streams (but note they're not started yet).
        this.W_ = function(t, e, s) {
            const i = Se(t);
            return new rn(e, i.Mc, i.credentials, i.serializer, s);
        }(this.T_, s, {
            e_: this.j_.bind(this),
            Yc: this.K_.bind(this),
            i_: this.G_.bind(this)
        }), this.z_ = function(t, e, s) {
            const i = Se(t);
            return new hn(e, i.Mc, i.credentials, i.serializer, s);
        }(this.T_, s, {
            e_: this.H_.bind(this),
            Yc: this.Y_.bind(this),
            c_: this.J_.bind(this),
            u_: this.u_.bind(this)
        });
    }
    /**
     * Starts up the remote store, creating streams, restoring state from
     * LocalStore, etc.
     */    start() {
        return this.enableNetwork();
    }
    /** Re-enables the network. Idempotent. */    enableNetwork() {
        return this.networkEnabled = !0, this.X_();
    }
    async X_() {
        this.q_() && (this.z_.lastStreamToken = await this.N_.Yo(), this.Z_() ? this.tl() : this.Q_.set("Unknown" /* Unknown */), 
        // This will start the write stream if necessary.
        await this.el());
    }
    /**
     * Temporarily disables the network. The network can be re-enabled using
     * enableNetwork().
     */    async disableNetwork() {
        this.networkEnabled = !1, await this.sl(), 
        // Set the OnlineState to Offline so get()s return from cache, etc.
        this.Q_.set("Offline" /* Offline */);
    }
    async sl() {
        await this.z_.stop(), await this.W_.stop(), this.k_.length > 0 && (ge("RemoteStore", `Stopping write stream with ${this.k_.length} pending writes`), 
        this.k_ = []), this.il();
    }
    async mo() {
        ge("RemoteStore", "RemoteStore shutting down."), this.networkEnabled = !1, await this.sl(), 
        this.x_.mo(), 
        // Set the OnlineState to Unknown (rather than Offline) to avoid potentially
        // triggering spurious listener events with cached data, etc.
        this.Q_.set("Unknown" /* Unknown */);
    }
    /**
     * 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.
     */    listen(t) {
        this.L_.has(t.targetId) || (
        // Mark this as something the client is currently listening for.
        this.L_.set(t.targetId, t), this.Z_() ? 
        // The listen will be sent in onWatchStreamOpen
        this.tl() : this.W_.Uc() && this.nl(t));
    }
    /**
     * Removes the listen from server. It is a no-op if the given target id is
     * not being listened to.
     */    rl(t) {
        this.L_.delete(t), this.W_.Uc() && this.hl(t), 0 === this.L_.size && (this.W_.Uc() ? this.W_.jc() : this.q_() && 
        // 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.
        this.Q_.set("Unknown" /* Unknown */));
    }
    /** {@link TargetMetadataProvider.getTargetDataForTarget} */    si(t) {
        return this.L_.get(t) || null;
    }
    /** {@link TargetMetadataProvider.getRemoteKeysForTarget} */    ei(t) {
        return this.ol.ei(t);
    }
    /**
     * We need to increment the the expected number of pending responses we're due
     * from watch so we wait for the ack to process any messages from this target.
     */    nl(t) {
        this.M_.Ns(t.targetId), this.W_.n_(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.
     */    hl(t) {
        this.M_.Ns(t), this.W_.r_(t);
    }
    tl() {
        this.M_ = new de(this), this.W_.start(), this.Q_.v_();
    }
    /**
     * Returns whether the watch stream should be started because it's necessary
     * and has not yet been started.
     */    Z_() {
        return this.q_() && !this.W_.qc() && this.L_.size > 0;
    }
    q_() {
        return !this.O_ && this.isPrimary && this.networkEnabled;
    }
    il() {
        this.M_ = null;
    }
    async j_() {
        this.L_.forEach((t, e) => {
            this.nl(t);
        });
    }
    async K_(t) {
        this.il(), 
        // If we still need the watch stream, retry the connection.
        this.Z_() ? (this.Q_.C_(t), this.tl()) : 
        // 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
        this.Q_.set("Unknown" /* Unknown */);
    }
    async G_(t, e) {
        if (
        // Mark the client as online since we got a message from the server
        this.Q_.set("Online" /* Online */), t instanceof _e && 2 /* Removed */ === t.state && t.cause) 
        // There was an error on a target, don't wait for a consistent snapshot
        // to raise events
        try {
            await this.al(t);
        } catch (e) {
            ge("RemoteStore", "Failed to remove targets %s: %s ", t.targetIds.join(","), e), 
            await this.ul(e);
        } else if (t instanceof ue ? this.M_.qs(t) : t instanceof ce ? this.M_.Hs(t) : this.M_.Ws(t), 
        !e.isEqual(y.min())) try {
            const t = await this.N_._h();
            e.S(t) >= 0 && 
            // We have received a target change with a global snapshot if the snapshot
            // version is not equal to SnapshotVersion.min().
            await this.cl(e);
        } catch (t) {
            ge("RemoteStore", "Failed to raise snapshot:", t), await this.ul(t);
        }
    }
    /**
     * Recovery logic for IndexedDB errors that takes the network offline until
     * IndexedDb probing succeeds. Retries are scheduled with backoff using
     * `enqueueRetryable()`.
     */    async ul(t) {
        if (!Gs(t)) throw t;
        this.O_ = !0, 
        // Disable network and raise offline snapshots
        await this.sl(), this.Q_.set("Offline" /* Offline */), 
        // Probe IndexedDB periodically and re-enable network
        this.Aa.Ua(async () => {
            ge("RemoteStore", "Retrying IndexedDB access"), 
            // Issue 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.
            await this.N_._h(), this.O_ = !1, await this.X_();
        });
    }
    /**
     * 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.
     */    cl(t) {
        const e = this.M_.Xs(t);
        // Update in-memory resume tokens. LocalStore will update the
        // persistent view of these when applying the completed RemoteEvent.
                // Finally raise remote event
        return e.as.forEach((e, s) => {
            if (e.resumeToken.rt() > 0) {
                const i = this.L_.get(s);
                // A watched target might have been removed already.
                                i && this.L_.set(s, i.we(e.resumeToken, t));
            }
        }), 
        // Re-establish listens for the targets that have been invalidated by
        // existence filter mismatches.
        e.us.forEach(t => {
            const e = this.L_.get(t);
            if (!e) 
            // A watched target might have been removed already.
            return;
            // Clear the resume token for the target, since we're in a known mismatch
            // state.
                        this.L_.set(t, e.we(k.ht, e.Ee)), 
            // Cause a hard reset by unwatching and rewatching immediately, but
            // deliberately don't send a resume token so that we get a full update.
            this.hl(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 s = new Lt(e.target, t, 1 /* ExistenceFilterMismatch */ , e.sequenceNumber);
            this.nl(s);
        }), this.ol.Mu(e);
    }
    /** Handles an error on a target */    async al(t) {
        const e = t.cause;
        for (const s of t.targetIds) 
        // A watched target might have been removed already.
        this.L_.has(s) && (await this.ol._l(s, e), this.L_.delete(s), this.M_.removeTarget(s));
    }
    /**
     * 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.
     */    async el() {
        if (this.ll()) {
            const t = this.k_.length > 0 ? this.k_[this.k_.length - 1].batchId : -1, e = await this.N_.qu(t);
            null === e ? 0 === this.k_.length && this.z_.jc() : (this.dl(e), await this.el());
        }
        this.fl() && this.Tl();
    }
    /**
     * Returns true if we can add to the write pipeline (i.e. the network is
     * enabled and the write pipeline is not full).
     */    ll() {
        return this.q_() && this.k_.length < 10;
    }
    // For testing
    El() {
        return this.k_.length;
    }
    /**
     * Queues additional writes to be sent to the write stream, sending them
     * immediately if the write stream is established.
     */    dl(t) {
        this.k_.push(t), this.z_.Uc() && this.z_.o_ && this.z_.a_(t.mutations);
    }
    fl() {
        return this.q_() && !this.z_.qc() && this.k_.length > 0;
    }
    Tl() {
        this.z_.start();
    }
    async H_() {
        this.z_.__();
    }
    J_() {
        // Record the stream token.
        return this.N_.Jo(this.z_.lastStreamToken).then(() => {
            // Send the write pipeline now that the stream is established.
            for (const t of this.k_) this.z_.a_(t.mutations);
        }).catch(ci);
    }
    u_(t, e) {
        const s = this.k_.shift(), i = Oe.from(s, t, e, this.z_.lastStreamToken);
        return this.ol.Il(i).then(() => this.el());
    }
    async Y_(t) {
        // If the write stream closed due to an error, invoke the error callbacks if
        // there are pending writes.
        t && this.k_.length > 0 && (this.z_.o_ ? 
        // This error affects the actual write.
        await this.wl(t) : 
        // If there was an error before the handshake has finished, it's
        // possible that the server is unable to process the stream token
        // we're sending. (Perhaps it's too old?)
        await this.Rl(t), 
        // The write stream might have been started by refilling the write
        // pipeline for failed writes
        this.fl() && this.Tl());
        // No pending writes, nothing to do
        }
    async Rl(t) {
        // Reset the token if it's a permanent error, signaling the write stream is
        // no longer valid. Note that the handshake does not count as a write: see
        // comments on isPermanentWriteError for details.
        if (Bt(t.code)) return ge("RemoteStore", "RemoteStore error before completed handshake; resetting stream token: ", this.z_.lastStreamToken), 
        this.z_.lastStreamToken = k.ht, this.N_.Jo(k.ht).catch(ci);
    }
    async wl(t) {
        // Only handle permanent errors here. If it's transient, just let the retry
        // logic kick in.
        if (Bt(e = t.code) && e !== w.ABORTED) {
            // This was a permanent error, the request itself was the problem
            // so it's not going to succeed if we resend it.
            const e = this.k_.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.
                        return this.z_.Wc(), this.ol.Al(e.batchId, t).then(() => this.el());
        }
        var e;
        /**
 * 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.
 */    }
    ml() {
        return new an(this.T_);
    }
    async U_() {
        this.networkEnabled = !1, await this.sl(), this.Q_.set("Unknown" /* Unknown */), 
        await this.enableNetwork();
    }
    async Pl() {
        this.q_() && (
        // 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).
        ge("RemoteStore", "RemoteStore restarting streams for new credential"), await this.U_());
    }
    /**
     * Toggles the network state when the client gains or loses its primary lease.
     */    async Vl(t) {
        this.isPrimary = t, t && this.networkEnabled ? await this.enableNetwork() : t || (await this.sl(), 
        this.Q_.set("Unknown" /* Unknown */));
    }
}

/**
 * @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>
/** Assembles the key for a client state in WebStorage */
function _n(t, e) {
    return `firestore_clients_${t}_${e}`;
}

// 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.
/** Assembles the key for a mutation batch in WebStorage */
function ln(t, e, s) {
    let i = `firestore_mutations_${t}_${s}`;
    return e.t() && (i += `_${e.uid}`), i;
}

// The format of the WebStorage key that stores a query target's metadata is:
//     firestore_targets_<persistence_prefix>_<target_id>
/** Assembles the key for a query state in WebStorage */
function dn(t, e) {
    return `firestore_targets_${t}_${e}`;
}

// The WebStorage prefix that stores the primary tab's online state. The
// format of the key is:
//     firestore_online_state_<persistence_prefix>
/**
 * 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 fn {
    constructor(t, e, s, i) {
        this.user = t, this.batchId = e, this.state = s, this.error = i;
    }
    /**
     * 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 gl(t, e, s) {
        const i = JSON.parse(s);
        let n = "object" == typeof i && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(i.state) && (void 0 === i.error || "object" == typeof i.error), r = void 0;
        return n && i.error && (n = "string" == typeof i.error.message && "string" == typeof i.error.code, 
        n && (r = new R(i.error.code, i.error.message))), n ? new fn(t, e, i.state, r) : (pe("SharedClientState", `Failed to parse mutation state for ID '${e}': ${s}`), 
        null);
    }
    pl() {
        const t = {
            state: this.state,
            updateTimeMs: Date.now()
        };
        return this.error && (t.error = {
            code: this.error.code,
            message: this.error.message
        }), JSON.stringify(t);
    }
}

/**
 * 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 Tn {
    constructor(t, e, s) {
        this.targetId = t, this.state = e, this.error = s;
    }
    /**
     * 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 gl(t, e) {
        const s = JSON.parse(e);
        let i = "object" == typeof s && -1 !== [ "not-current", "current", "rejected" ].indexOf(s.state) && (void 0 === s.error || "object" == typeof s.error), n = void 0;
        return i && s.error && (i = "string" == typeof s.error.message && "string" == typeof s.error.code, 
        i && (n = new R(s.error.code, s.error.message))), i ? new Tn(t, s.state, n) : (pe("SharedClientState", `Failed to parse target state for ID '${t}': ${e}`), 
        null);
    }
    pl() {
        const t = {
            state: this.state,
            updateTimeMs: Date.now()
        };
        return this.error && (t.error = {
            code: this.error.code,
            message: this.error.message
        }), JSON.stringify(t);
    }
}

/**
 * This class represents the immutable ClientState for a client read from
 * WebStorage, containing the list of active query targets.
 */ class En {
    constructor(t, e) {
        this.clientId = t, this.activeTargetIds = e;
    }
    /**
     * 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 gl(t, e) {
        const s = JSON.parse(e);
        let i = "object" == typeof s && s.activeTargetIds instanceof Array, n = ie();
        for (let t = 0; i && t < s.activeTargetIds.length; ++t) i = O(s.activeTargetIds[t]), 
        n = n.add(s.activeTargetIds[t]);
        return i ? new En(t, n) : (pe("SharedClientState", `Failed to parse client data for instance '${t}': ${e}`), 
        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 In {
    constructor(t, e) {
        this.clientId = t, this.onlineState = e;
    }
    /**
     * 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 gl(t) {
        const e = JSON.parse(t);
        return "object" == typeof e && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(e.onlineState) && "string" == typeof e.clientId ? new In(e.clientId, e.onlineState) : (pe("SharedClientState", `Failed to parse online state: ${t}`), 
        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 wn {
    constructor() {
        this.activeTargetIds = ie();
    }
    yl(t) {
        this.activeTargetIds = this.activeTargetIds.add(t);
    }
    bl(t) {
        this.activeTargetIds = this.activeTargetIds.delete(t);
    }
    /**
     * 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.
     */    pl() {
        const t = {
            activeTargetIds: this.activeTargetIds.W(),
            updateTimeMs: Date.now()
        };
        return JSON.stringify(t);
    }
}

/**
 * `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 Rn {
    constructor(t, e, s, i, n) {
        if (this.Tr = t, this.platform = e, this.persistenceKey = s, this.vl = i, this.ol = null, 
        this.g_ = null, this.ur = null, this.Sl = this.Dl.bind(this), this.Cl = new Ut(Ce), 
        this.ro = !1, 
        /**
         * Captures WebStorage events that occur before `start()` is called. These
         * events are replayed once `WebStorageSharedClientState` is started.
         */
        this.Fl = [], !Rn.Gh(this.platform)) throw new R(w.UNIMPLEMENTED, "LocalStorage is not available on this platform.");
        // Escape the special characters mentioned here:
        // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
                const r = s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
        this.storage = this.platform.window.localStorage, this.currentUser = n, this.Nl = _n(this.persistenceKey, this.vl), 
        this.$l = 
        /** Assembles the key for the current sequence number. */
        function(t) {
            return `firestore_sequence_number_${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.
 */ (this.persistenceKey), this.Cl = this.Cl.Ae(this.vl, new wn), this.kl = new RegExp(`^firestore_clients_${r}_([^_]*)$`), 
        this.Ll = new RegExp(`^firestore_mutations_${r}_(\\d+)(?:_(.*))?$`), this.Ml = new RegExp(`^firestore_targets_${r}_(\\d+)$`), 
        this.Ol = 
        /** Assembles the key for the online state of the primary tab. */
        function(t) {
            return `firestore_online_state_${t}`;
        }
        // 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.platform.window.addEventListener("storage", this.Sl);
    }
    /** Returns 'true' if WebStorage is available in the current environment. */    static Gh(t) {
        return !(!t.window || null == t.window.localStorage);
    }
    async start() {
        // Retrieve the list of existing clients to backfill the data in
        // SharedClientState.
        const t = await this.ol.bo();
        for (const e of t) {
            if (e === this.vl) continue;
            const t = this.getItem(_n(this.persistenceKey, e));
            if (t) {
                const s = En.gl(e, t);
                s && (this.Cl = this.Cl.Ae(s.clientId, s));
            }
        }
        this.xl();
        // Check if there is an existing online state and call the callback handler
        // if applicable.
        const e = this.storage.getItem(this.Ol);
        if (e) {
            const t = this.Bl(e);
            t && this.ql(t);
        }
        for (const t of this.Fl) this.Dl(t);
        this.Fl = [], 
        // Register a window unload hook to remove the client metadata entry from
        // WebStorage even if `shutdown()` was not called.
        this.platform.window.addEventListener("unload", () => this.mo()), this.ro = !0;
    }
    lr(t) {
        this.setItem(this.$l, JSON.stringify(t));
    }
    Ul() {
        return this.Ql(this.Cl);
    }
    Wl(t) {
        let e = !1;
        return this.Cl.forEach((s, i) => {
            i.activeTargetIds.has(t) && (e = !0);
        }), e;
    }
    jl(t) {
        this.Kl(t, "pending");
    }
    Gl(t, e, s) {
        this.Kl(t, e, s), 
        // 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.zl(t);
    }
    Hl(t) {
        let e = "not-current";
        // Lookup an existing query state if the target ID was already registered
        // by another tab
                if (this.Wl(t)) {
            const s = this.storage.getItem(dn(this.persistenceKey, t));
            if (s) {
                const i = Tn.gl(t, s);
                i && (e = i.state);
            }
        }
        return this.Yl.yl(t), this.xl(), e;
    }
    Jl(t) {
        this.Yl.bl(t), this.xl();
    }
    Xl(t) {
        return this.Yl.activeTargetIds.has(t);
    }
    Zl(t) {
        this.removeItem(dn(this.persistenceKey, t));
    }
    td(t, e, s) {
        this.ed(t, e, s);
    }
    Du(t, e, s) {
        e.forEach(t => {
            this.zl(t);
        }), this.currentUser = t, s.forEach(t => {
            this.jl(t);
        });
    }
    sd(t) {
        this.nd(t);
    }
    mo() {
        this.ro && (this.platform.window.removeEventListener("storage", this.Sl), this.removeItem(this.Nl), 
        this.ro = !1);
    }
    getItem(t) {
        const e = this.storage.getItem(t);
        return ge("SharedClientState", "READ", t, e), e;
    }
    setItem(t, e) {
        ge("SharedClientState", "SET", t, e), this.storage.setItem(t, e);
    }
    removeItem(t) {
        ge("SharedClientState", "REMOVE", t), this.storage.removeItem(t);
    }
    Dl(t) {
        if (t.storageArea === this.storage) {
            if (ge("SharedClientState", "EVENT", t.key, t.newValue), t.key === this.Nl) return void pe("Received WebStorage notification for local change. Another client might have garbage-collected our state");
            this.Tr.Ua(async () => {
                if (this.ro) {
                    if (null !== t.key) if (this.kl.test(t.key)) {
                        if (null == t.newValue) {
                            const e = this.rd(t.key);
                            return this.hd(e, null);
                        }
                        {
                            const e = this.od(t.key, t.newValue);
                            if (e) return this.hd(e.clientId, e);
                        }
                    } else if (this.Ll.test(t.key)) {
                        if (null !== t.newValue) {
                            const e = this.ad(t.key, t.newValue);
                            if (e) return this.ud(e);
                        }
                    } else if (this.Ml.test(t.key)) {
                        if (null !== t.newValue) {
                            const e = this._d(t.key, t.newValue);
                            if (e) return this.ld(e);
                        }
                    } else if (t.key === this.Ol) {
                        if (null !== t.newValue) {
                            const e = this.Bl(t.newValue);
                            if (e) return this.ql(e);
                        }
                    } else if (t.key === this.$l) {
                        const e = function(t) {
                            let e = je.dr;
                            if (null != t) try {
                                const s = JSON.parse(t);
                                ve("number" == typeof s), e = s;
                            } catch (t) {
                                pe("SharedClientState", "Failed to read sequence number from WebStorage", t);
                            }
                            return e;
                        }
                        /**
 * `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 !== je.dr && this.ur(e);
                    }
                } else this.Fl.push(t);
            });
        }
    }
    get Yl() {
        return this.Cl.get(this.vl);
    }
    xl() {
        this.setItem(this.Nl, this.Yl.pl());
    }
    Kl(t, e, s) {
        const i = new fn(this.currentUser, t, e, s), n = ln(this.persistenceKey, this.currentUser, t);
        this.setItem(n, i.pl());
    }
    zl(t) {
        const e = ln(this.persistenceKey, this.currentUser, t);
        this.removeItem(e);
    }
    nd(t) {
        const e = {
            clientId: this.vl,
            onlineState: t
        };
        this.storage.setItem(this.Ol, JSON.stringify(e));
    }
    ed(t, e, s) {
        const i = dn(this.persistenceKey, t), n = new Tn(t, e, s);
        this.setItem(i, n.pl());
    }
    /**
     * Parses a client state key in WebStorage. Returns null if the key does not
     * match the expected key format.
     */    rd(t) {
        const e = this.kl.exec(t);
        return e ? e[1] : null;
    }
    /**
     * Parses a client state in WebStorage. Returns 'null' if the value could not
     * be parsed.
     */    od(t, e) {
        const s = this.rd(t);
        return En.gl(s, e);
    }
    /**
     * Parses a mutation batch state in WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    ad(t, e) {
        const s = this.Ll.exec(t), i = Number(s[1]), n = void 0 !== s[2] ? s[2] : null;
        return fn.gl(new I(n), i, e);
    }
    /**
     * Parses a query target state from WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    _d(t, e) {
        const s = this.Ml.exec(t), i = Number(s[1]);
        return Tn.gl(i, e);
    }
    /**
     * Parses an online state from WebStorage. Returns 'null' if the value
     * could not be parsed.
     */    Bl(t) {
        return In.gl(t);
    }
    async ud(t) {
        if (t.user.uid === this.currentUser.uid) return this.ol.dd(t.batchId, t.state, t.error);
        ge("SharedClientState", `Ignoring mutation for non-active user ${t.user.uid}`);
    }
    ld(t) {
        return this.ol.fd(t.targetId, t.state, t.error);
    }
    hd(t, e) {
        const s = e ? this.Cl.Ae(t, e) : this.Cl.remove(t), i = this.Ql(this.Cl), n = this.Ql(s), r = [], h = [];
        return n.forEach(t => {
            i.has(t) || r.push(t);
        }), i.forEach(t => {
            n.has(t) || h.push(t);
        }), this.ol.Td(r, h).then(() => {
            this.Cl = s;
        });
    }
    ql(t) {
        // 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.Cl.get(t.clientId) && this.g_(t.onlineState);
    }
    Ql(t) {
        let e = ie();
        return t.forEach((t, s) => {
            e = e.He(s.activeTargetIds);
        }), e;
    }
}

class An {
    constructor() {
        this.Ed = new wn, this.Id = {}, this.ol = null, this.g_ = null, this.ur = null;
    }
    jl(t) {
        // No op.
    }
    Gl(t, e, s) {
        // No op.
    }
    Hl(t) {
        return this.Ed.yl(t), this.Id[t] || "not-current";
    }
    td(t, e, s) {
        this.Id[t] = e;
    }
    Jl(t) {
        this.Ed.bl(t);
    }
    Xl(t) {
        return this.Ed.activeTargetIds.has(t);
    }
    Zl(t) {
        delete this.Id[t];
    }
    Ul() {
        return this.Ed.activeTargetIds;
    }
    Wl(t) {
        return this.Ed.activeTargetIds.has(t);
    }
    start() {
        return this.Ed = new wn, Promise.resolve();
    }
    Du(t, e, s) {
        // No op.
    }
    sd(t) {
        // No op.
    }
    mo() {}
    lr(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 mn {
    constructor(t) {
        this.key = t;
    }
}

class Pn {
    constructor(t) {
        this.key = t;
    }
}

/**
 * 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 Vn {
    constructor(t, 
    /** Documents included in the remote target */
    e) {
        this.query = t, this.wd = e, this.Rd = null, 
        /**
         * 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.fs = !1, 
        /** Documents in the view but not in the remote target */
        this.Ad = ee(), 
        /** Document Keys that have local changes */
        this.ns = ee(), this.md = new ne(t.se.bind(t));
    }
    /**
     * The set of remote documents that the server has told us belongs to the target associated with
     * this view.
     */    get Pd() {
        return this.wd;
    }
    /**
     * 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.
     * @return a new set of docs, changes, and refill flag.
     */    Vd(t, e) {
        const s = e ? e.gd : new re, i = e ? e.md : this.md;
        let n = e ? e.ns : this.ns, r = i, h = !1;
        // Track the last doc in a (full) limit. This is necessary, because some
        // update (a delete, or an update moving a doc past the old limit) might
        // mean there is some other document in the local cache that either should
        // come (1) between the old last limit doc and the new last document, in the
        // case of updates, or (2) after the new last document, in the case of
        // deletes. So we keep this doc at the old limit to compare the updates to.
        // Note that this should never get used in a refill (when previousChanges is
        // set), because there will only be adds -- no deletes or updates.
        const o = this.query.oe() && i.size === this.query.limit ? i.last() : null, a = this.query.ae() && i.size === this.query.limit ? i.first() : null;
        // Drop documents out to meet limit/limitToLast requirement.
        if (t.pe((t, e) => {
            const u = i.get(t);
            let c = e instanceof Vt ? e : null;
            c && (c = this.query.matches(c) ? c : null);
            const _ = !!u && this.ns.has(u.key), l = !!c && (c.At || 
            // We only consider committed mutations for documents that were
            // mutated during the lifetime of the view.
            this.ns.has(c.key) && c.hasCommittedMutations);
            let d = !1;
            // Calculate change
                        if (u && c) {
                u.data().isEqual(c.data()) ? _ !== l && (s.track({
                    type: 3 /* Metadata */ ,
                    doc: c
                }), d = !0) : this.pd(u, c) || (s.track({
                    type: 2 /* Modified */ ,
                    doc: c
                }), d = !0, (o && this.query.se(c, o) > 0 || a && this.query.se(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.
                h = !0));
            } else !u && c ? (s.track({
                type: 0 /* Added */ ,
                doc: c
            }), d = !0) : u && !c && (s.track({
                type: 1 /* Removed */ ,
                doc: u
            }), d = !0, (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.
            h = !0));
            d && (c ? (r = r.add(c), n = l ? n.add(t) : n.delete(t)) : (r = r.delete(t), n = n.delete(t)));
        }), this.query.oe() || this.query.ae()) for (;r.size > this.query.limit; ) {
            const t = this.query.oe() ? r.last() : r.first();
            r = r.delete(t.key), n = n.delete(t.key), s.track({
                type: 1 /* Removed */ ,
                doc: t
            });
        }
        return {
            md: r,
            gd: s,
            yd: h,
            ns: n
        };
    }
    pd(t, e) {
        // 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 t.At && e.hasCommittedMutations && !e.At;
    }
    /**
     * 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 updateLimboDocuments Whether to update limbo documents based on this
     *        change.
     * @param targetChange A target change to apply for computing limbo docs and
     *        sync state.
     * @return A new ViewChange with the given docs, changes, and sync state.
     */
    // PORTING NOTE: The iOS/Android clients always compute limbo document changes.
    xn(t, e, s) {
        const i = this.md;
        this.md = t.md, this.ns = t.ns;
        // Sort changes based on type and query comparator
        const n = t.gd.es();
        n.sort((t, e) => function(t, e) {
            const s = t => {
                switch (t) {
                  case 0 /* Added */ :
                    return 1;

                  case 2 /* Modified */ :
                  case 3 /* 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 /* Removed */ :
                    return 0;

                  default:
                    return be();
                }
            };
            return s(t) - s(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.
 */ (t.type, e.type) || this.query.se(t.doc, e.doc)), this.bd(s);
        const r = e ? this.vd() : [], h = 0 === this.Ad.size && this.fs ? 1 /* Synced */ : 0 /* Local */ , o = h !== this.Rd;
        if (this.Rd = h, 0 !== n.length || o) {
            return {
                snapshot: new he(this.query, t.md, i, n, t.ns, 0 /* Local */ === h, o, 
                /* excludesMetadataChanges= */ !1),
                Sd: r
            };
        }
        // no changes
        return {
            Sd: r
        };
    }
    /**
     * Applies an OnlineState change to the view, potentially generating a
     * ViewChange if the view's syncState changes as a result.
     */    Dd(t) {
        return this.fs && "Offline" /* Offline */ === t ? (
        // 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.fs = !1, this.xn({
            md: this.md,
            gd: new re,
            ns: this.ns,
            yd: !1
        }, 
        /* updateLimboDocuments= */ !1)) : {
            Sd: []
        };
    }
    /**
     * Returns whether the doc for the given key should be in limbo.
     */    Cd(t) {
        // If the remote end says it's part of this query, it's not in limbo.
        return !this.wd.has(t) && (
        // The local store doesn't think it's a result, so it shouldn't be in limbo.
        !!this.md.has(t) && !this.md.get(t).At);
    }
    /**
     * Updates syncedDocuments, current, and limbo docs based on the given change.
     * Returns the list of changes to which docs are in limbo.
     */    bd(t) {
        t && (t.Ts.forEach(t => this.wd = this.wd.add(t)), t.Es.forEach(t => {}), t.Is.forEach(t => this.wd = this.wd.delete(t)), 
        this.fs = t.fs);
    }
    vd() {
        // We can only determine limbo documents when we're in-sync with the server.
        if (!this.fs) return [];
        // TODO(klimt): Do this incrementally so that it's not quadratic when
        // updating many documents.
                const t = this.Ad;
        this.Ad = ee(), this.md.forEach(t => {
            this.Cd(t.key) && (this.Ad = this.Ad.add(t.key));
        });
        // Diff the new limbo docs with the old limbo docs.
        const e = [];
        return t.forEach(t => {
            this.Ad.has(t) || e.push(new Pn(t));
        }), this.Ad.forEach(s => {
            t.has(s) || e.push(new mn(s));
        }), e;
    }
    /**
     * 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.
     *
     * @return The ViewChange that resulted from this synchronization.
     */
    // PORTING NOTE: Multi-tab only.
    Fd(t) {
        this.wd = t.Ku, this.Ad = ee();
        const e = this.Vd(t.documents);
        return this.xn(e, /*updateLimboDocuments=*/ !0);
    }
    /**
     * 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.
    Nd() {
        return he.os(this.query, this.md, this.ns, 0 /* Local */ === this.Rd);
    }
}

/**
 * TransactionRunner encapsulates the logic needed to run and retry transactions
 * with backoff.
 */
class gn {
    constructor(t, e, s, i) {
        this.Aa = t, this.$d = e, this.updateFunction = s, this.Va = i, this.kd = 5, this.$a = new Ge(this.Aa, "transaction_retry" /* TransactionRetry */);
    }
    /** Runs the transaction and sets the result on deferred. */    Ld() {
        this.Md();
    }
    Md() {
        this.$a.gr(async () => {
            const t = this.$d.ml(), e = this.Od(t);
            e && e.then(e => {
                this.Aa.uo(() => t.commit().then(() => {
                    this.Va.resolve(e);
                }).catch(t => {
                    this.xd(t);
                }));
            }).catch(t => {
                this.xd(t);
            });
        });
    }
    Od(t) {
        try {
            const e = this.updateFunction(t);
            return !L(e) && e.catch && e.then ? e : (this.Va.reject(Error("Transaction callback must return a Promise")), 
            null);
        } catch (t) {
            // Do not retry errors thrown by user provided updateFunction.
            return this.Va.reject(t), null;
        }
    }
    xd(t) {
        this.kd > 0 && this.Bd(t) ? (this.kd -= 1, this.Aa.uo(() => (this.Md(), Promise.resolve()))) : this.Va.reject(t);
    }
    Bd(t) {
        if ("FirebaseError" === t.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 e = t.code;
            return "aborted" === e || "failed-precondition" === e || !Bt(e);
        }
        return !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.
 */
/**
 * QueryView contains all of the data that SyncEngine needs to keep track of for
 * a particular query.
 */
class pn {
    constructor(
    /**
     * The query itself.
     */
    t, 
    /**
     * The target number created by the client that is used in the watch
     * stream to identify this query.
     */
    e, 
    /**
     * 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.
     */
    s) {
        this.query = t, this.targetId = e, this.view = s;
    }
}

/** Tracks a limbo resolution. */ class yn {
    constructor(t) {
        this.key = t, 
        /**
         * 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.qd = !1;
    }
}

/**
 * SyncEngine is the central controller in the client SDK architecture. It is
 * the glue code between the EventManager, LocalStore, and RemoteStore. Some of
 * SyncEngine's responsibilities include:
 * 1. Coordinating client requests and remote events between the EventManager
 *    and the local and remote data stores.
 * 2. Managing a View object for each query, providing the unified view between
 *    the local and remote data stores.
 * 3. Notifying the RemoteStore when the LocalStore has new mutations in its
 *    queue that need sending to the backend.
 *
 * The SyncEngine’s methods should only ever be called by methods running in the
 * global async queue.
 */ class bn {
    constructor(t, e, 
    // PORTING NOTE: Manages state synchronization in multi-tab environments.
    s, i, n) {
        this.N_ = t, this.$d = e, this.Ud = s, this.currentUser = i, this.Qd = n, this.Wd = null, 
        this.jd = new Le(t => t.canonicalId()), this.Kd = new Map, 
        /**
         * The keys of documents that are in limbo for which we haven't yet started a
         * limbo resolution query.
         */
        this.Gd = [], 
        /**
         * Keeps track of the target ID for each document that is in limbo with an
         * active target.
         */
        this.zd = new Ut(C.N), 
        /**
         * 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.Hd = new Map, this.Yd = new _i, 
        /** Stores user completion handlers, indexed by User and BatchId. */
        this.Jd = {}, 
        /** Stores user callbacks waiting for all pending writes to be acknowledged. */
        this.Xd = new Map, this.Zd = os.rh(), this.onlineState = "Unknown" /* Unknown */;
    }
    get tf() {
        return !0;
    }
    /** Subscribes to SyncEngine notifications. Has to be called exactly once. */    subscribe(t) {
        this.Wd = t;
    }
    /**
     * 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 listen(t) {
        let e, s;
        this.ef("listen()");
        const i = this.jd.get(t);
        if (i) 
        // 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.
        e = i.targetId, this.Ud.Hl(e), s = i.view.Nd(); else {
            const i = await this.N_.Qu(t.ee()), n = this.Ud.Hl(i.targetId);
            e = i.targetId, s = await this.sf(t, e, "current" === n), this.tf && this.$d.listen(i);
        }
        return s;
    }
    /**
     * Registers a view for a previously unknown query and computes its initial
     * snapshot.
     */    async sf(t, e, s) {
        const i = await this.N_.ju(t, 
        /* usePreviousResults= */ !0), n = new Vn(t, i.Ku), r = n.Vd(i.documents), h = ae.ds(e, s && "Offline" /* Offline */ !== this.onlineState), o = n.xn(r, 
        /* updateLimboDocuments= */ this.tf, h);
        this.if(e, o.Sd);
        const a = new pn(t, e, n);
        return this.jd.set(t, a), this.Kd.has(e) ? this.Kd.get(e).push(t) : this.Kd.set(e, [ t ]), 
        o.snapshot;
    }
    /** Stops listening to the query. */    async rl(t) {
        this.ef("unlisten()");
        const e = this.jd.get(t), s = this.Kd.get(e.targetId);
        // Only clean up the query view and target if this is the only query mapped
        // to the target.
                if (s.length > 1) return this.Kd.set(e.targetId, s.filter(e => !e.isEqual(t))), 
        void this.jd.delete(t);
        // No other queries are mapped to the target, clean up the query and the target.
                if (this.tf) {
            // We need to remove the local query target first to allow us to verify
            // whether any other client is still interested in this target.
            this.Ud.Jl(e.targetId), this.Ud.Wl(e.targetId) || await this.N_.Wu(e.targetId, /*keepPersistedTargetData=*/ !1).then(() => {
                this.Ud.Zl(e.targetId), this.$d.rl(e.targetId), this.nf(e.targetId);
            }).catch(ci);
        } else this.nf(e.targetId), await this.N_.Wu(e.targetId, 
        /*keepPersistedTargetData=*/ !0);
    }
    /**
     * 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 write(t, e) {
        this.ef("write()");
        try {
            const s = await this.N_.$u(t);
            this.Ud.jl(s.batchId), this.rf(s.batchId, e), await this.hf(s.Dn), await this.$d.el();
        } catch (t) {
            // 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 s = ei(t, "Failed to persist write");
            e.reject(s);
        }
    }
    /**
     * 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.
     *
     * The Deferred input is resolved when the transaction is fully committed.
     */    runTransaction(t, e, s) {
        new gn(t, this.$d, e, s).Ld();
    }
    async Mu(t) {
        this.ef("applyRemoteEvent()");
        try {
            const e = await this.N_.Mu(t);
            // Update `receivedDocument` as appropriate for any limbo targets.
                        t.as.forEach((t, e) => {
                const s = this.Hd.get(e);
                s && (
                // 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.
                ve(t.Ts.size + t.Es.size + t.Is.size <= 1), t.Ts.size > 0 ? s.qd = !0 : t.Es.size > 0 ? ve(s.qd) : t.Is.size > 0 && (ve(s.qd), 
                s.qd = !1));
            }), await this.hf(e, t);
        } catch (t) {
            await ci(t);
        }
    }
    /**
     * Applies an OnlineState change to the sync engine and notifies any views of
     * the change.
     */    Dd(t, e) {
        this.ef("applyOnlineStateChange()");
        const s = [];
        this.jd.forEach((e, i) => {
            const n = i.view.Dd(t);
            n.snapshot && s.push(n.snapshot);
        }), this.Wd.af(t), this.Wd.i_(s), this.onlineState = t;
    }
    async _l(t, e) {
        this.ef("rejectListens()"), 
        // PORTING NOTE: Multi-tab only.
        this.Ud.td(t, "rejected", e);
        const s = this.Hd.get(t), i = s && s.key;
        if (i) {
            // 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 Ut(C.N);
            e = e.Ae(i, new gt(i, y.min()));
            const s = ee().add(i), n = new oe(y.min(), 
            /* targetChanges= */ new Map, 
            /* targetMismatches= */ new jt(Ce), e, s);
            await this.Mu(n), 
            // 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.
            this.zd = this.zd.remove(i), this.Hd.delete(t), this.uf();
        } else await this.N_.Wu(t, /* keepPersistedTargetData */ !1).then(() => this.nf(t, e)).catch(ci);
    }
    async Il(t) {
        this.ef("applySuccessfulWrite()");
        const e = t.batch.batchId;
        // 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.
                this.cf(e, /*error=*/ null), this._f(e);
        try {
            const s = await this.N_.zo(t);
            this.Ud.Gl(e, "acknowledged"), await this.hf(s);
        } catch (t) {
            await ci(t);
        }
    }
    async Al(t, e) {
        this.ef("rejectFailedWrite()"), 
        // 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.
        this.cf(t, e), this._f(t);
        try {
            const s = await this.N_.Lu(t);
            this.Ud.Gl(t, "rejected", e), await this.hf(s);
        } catch (e) {
            await ci(e);
        }
    }
    /**
     * Registers a user callback that resolves when all pending mutations at the moment of calling
     * are acknowledged .
     */    async lf(t) {
        this.$d.q_() || ge("SyncEngine", "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.");
        try {
            const e = await this.N_.sa();
            if (-1 === e) 
            // Trigger the callback right away if there is no pending writes at the moment.
            return void t.resolve();
            const s = this.Xd.get(e) || [];
            s.push(t), this.Xd.set(e, s);
        } catch (e) {
            const s = ei(e, "Initialization of waitForPendingWrites() operation failed");
            t.reject(s);
        }
    }
    /**
     * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,
     * if there are any.
     */    _f(t) {
        (this.Xd.get(t) || []).forEach(t => {
            t.resolve();
        }), this.Xd.delete(t);
    }
    /** Reject all outstanding callbacks waiting for pending writes to complete. */    df(t) {
        this.Xd.forEach(e => {
            e.forEach(e => {
                e.reject(new R(w.CANCELLED, t));
            });
        }), this.Xd.clear();
    }
    rf(t, e) {
        let s = this.Jd[this.currentUser.s()];
        s || (s = new Ut(Ce)), s = s.Ae(t, e), this.Jd[this.currentUser.s()] = s;
    }
    /**
     * Resolves or rejects the user callback for the given batch and then discards
     * it.
     */    cf(t, e) {
        let s = this.Jd[this.currentUser.s()];
        // NOTE: Mutations restored from persistence won't have callbacks, so it's
        // okay for there to be no callback for this ID.
                if (s) {
            const i = s.get(t);
            i && (e ? i.reject(e) : i.resolve(), s = s.remove(t)), this.Jd[this.currentUser.s()] = s;
        }
    }
    nf(t, e = null) {
        this.Ud.Jl(t);
        for (const s of this.Kd.get(t)) this.jd.delete(s), e && this.Wd.ff(s, e);
        if (this.Kd.delete(t), this.tf) {
            this.Yd.nc(t).forEach(t => {
                this.Yd.Ch(t) || 
                // We removed the last reference for this key
                this.Tf(t);
            });
        }
    }
    Tf(t) {
        // 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 e = this.zd.get(t);
        null !== e && (this.$d.rl(e), this.zd = this.zd.remove(t), this.Hd.delete(e), this.uf());
    }
    if(t, e) {
        for (const s of e) if (s instanceof mn) this.Yd.yh(s.key, t), this.Ef(s); else if (s instanceof Pn) {
            ge("SyncEngine", "Document no longer in limbo: " + s.key), this.Yd.vh(s.key, t), 
            this.Yd.Ch(s.key) || 
            // We removed the last reference for this key
            this.Tf(s.key);
        } else be();
    }
    Ef(t) {
        const e = t.key;
        this.zd.get(e) || (ge("SyncEngine", "New document in limbo: " + e), this.Gd.push(e), 
        this.uf());
    }
    /**
     * 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.
     */    uf() {
        for (;this.Gd.length > 0 && this.zd.size < this.Qd; ) {
            const t = this.Gd.shift(), e = this.Zd.next();
            this.Hd.set(e, new yn(t)), this.zd = this.zd.Ae(t, e), this.$d.listen(new Lt(bt.Wt(t.path).ee(), e, 2 /* LimboResolution */ , je.dr));
        }
    }
    // Visible for testing
    If() {
        return this.zd;
    }
    // Visible for testing
    wf() {
        return this.Gd;
    }
    async hf(t, e) {
        const s = [], i = [], n = [];
        this.jd.forEach((r, h) => {
            n.push(Promise.resolve().then(() => {
                const e = h.view.Vd(t);
                return e.yd ? this.N_.ju(h.query, /* usePreviousResults= */ !1).then(({documents: t}) => h.view.Vd(t, e)) : e;
                // 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.
                        }).then(t => {
                const n = e && e.as.get(h.targetId), r = h.view.xn(t, 
                /* updateLimboDocuments= */ this.tf, n);
                if (this.if(h.targetId, r.Sd), r.snapshot) {
                    this.tf && this.Ud.td(h.targetId, r.snapshot.fromCache ? "not-current" : "current"), 
                    s.push(r.snapshot);
                    const t = We.ar(h.targetId, r.snapshot);
                    i.push(t);
                }
            }));
        }), await Promise.all(n), this.Wd.i_(s), await this.N_.Bu(i);
    }
    ef(t) {}
    async Pl(t) {
        if (!this.currentUser.isEqual(t)) {
            const e = await this.N_.Du(t);
            this.currentUser = t, 
            // Fails tasks waiting for pending writes requested by previous user.
            this.df("'waitForPendingWrites' promise is rejected due to a user change."), 
            // TODO(b/114226417): Consider calling this only in the primary tab.
            this.Ud.Du(t, e.Fu, e.Nu), await this.hf(e.Cu);
        }
        await this.$d.Pl();
    }
    enableNetwork() {
        return this.$d.enableNetwork();
    }
    disableNetwork() {
        return this.$d.disableNetwork();
    }
    ei(t) {
        const e = this.Hd.get(t);
        if (e && e.qd) return ee().add(e.key);
        {
            let e = ee();
            const s = this.Kd.get(t);
            if (!s) return e;
            for (const t of s) {
                const s = this.jd.get(t);
                e = e.He(s.view.Pd);
            }
            return e;
        }
    }
}

/**
 * An impplementation of SyncEngine that implement SharedClientStateSyncer for
 * Multi-Tab synchronization.
 */
// PORTING NOTE: Web only
class vn extends bn {
    constructor(t, e, s, i, n) {
        super(t, e, s, i, n), this.N_ = t, 
        // 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.Rf = void 0;
    }
    get tf() {
        return !0 === this.Rf;
    }
    enableNetwork() {
        return this.N_.ao(!0), super.enableNetwork();
    }
    disableNetwork() {
        return this.N_.ao(!1), super.disableNetwork();
    }
    /**
     * Reconcile the list of synced documents in an existing view with those
     * from persistence.
     */    async Af(t) {
        const e = await this.N_.ju(t.query, 
        /* usePreviousResults= */ !0), s = t.view.Fd(e);
        return this.Rf && this.if(t.targetId, s.Sd), s;
    }
    Dd(t, e) {
        // If we are the primary client, the online state of all clients only
        // depends on the online state of the local RemoteStore.
        this.tf && 0 /* RemoteStore */ === e && (super.Dd(t, e), this.Ud.sd(t)), 
        // 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.
        this.tf || 1 /* SharedClientState */ !== e || super.Dd(t, e);
    }
    async dd(t, e, s) {
        this.ef("applyBatchState()");
        const i = await this.N_.zu(t);
        null !== i ? ("pending" === e ? 
        // 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 this.$d.el() : "acknowledged" === e || "rejected" === e ? (
        // NOTE: Both these methods are no-ops for batches that originated from
        // other clients.
        this.cf(t, s || null), this.N_.Hu(t)) : be(), await this.hf(i)) : 
        // 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.
        ge("SyncEngine", "Cannot apply mutation batch with id: " + t);
    }
    async Vl(t) {
        if (!0 === t && !0 !== this.Rf) {
            // 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 t = this.Ud.Ul(), e = await this.mf(t.W(), 
            /*transitionToPrimary=*/ !0);
            this.Rf = !0, await this.$d.Vl(!0);
            for (const t of e) this.$d.listen(t);
        } else if (!1 === t && !1 !== this.Rf) {
            const t = [];
            let e = Promise.resolve();
            this.Kd.forEach((s, i) => {
                this.Ud.Xl(i) ? t.push(i) : e = e.then(() => (this.nf(i), this.N_.Wu(i, 
                /*keepPersistedTargetData=*/ !0))), this.$d.rl(i);
            }), await e, await this.mf(t, 
            /*transitionToPrimary=*/ !1), this.Pf(), this.Rf = !1, await this.$d.Vl(!1);
        }
    }
    Pf() {
        this.Hd.forEach((t, e) => {
            this.$d.rl(e);
        }), this.Yd.rc(), this.Hd = new Map, this.zd = new Ut(C.N);
    }
    /**
     * 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 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
     */    async mf(t, e) {
        const s = [], i = [];
        for (const e of t) {
            let t;
            const n = this.Kd.get(e);
            if (n && 0 !== n.length) {
                // For queries that have a local View, we need to update their state
                // in 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).
                await this.N_.Wu(e, 
                /*keepPersistedTargetData=*/ !0), t = await this.N_.Qu(n[0].ee());
                for (const t of n) {
                    const e = this.jd.get(t), s = await this.Af(e);
                    s.snapshot && i.push(s.snapshot);
                }
            } else {
                // For queries that never executed on this client, we need to
                // allocate the target in LocalStore and initialize a new View.
                const s = await this.N_.Yu(e);
                t = await this.N_.Qu(s), await this.sf(this.Vf(s), e, 
                /*current=*/ !1);
            }
            s.push(t);
        }
        return this.Wd.i_(i), s;
    }
    /**
     * 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.
     */    Vf(t) {
        return new bt(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, "F" /* First */ , t.startAt, t.endAt);
    }
    bo() {
        return this.N_.bo();
    }
    async fd(t, e, s) {
        if (this.Rf) 
        // If we receive a target state notification via WebStorage, we are
        // either already secondary or another tab has taken the primary lease.
        ge("SyncEngine", "Ignoring unexpected query state notification."); else if (this.Kd.has(t)) switch (e) {
          case "current":
          case "not-current":
            {
                const s = await this.N_.Kr(), i = oe.ls(t, "current" === e);
                await this.hf(s, i);
                break;
            }

          case "rejected":
            await this.N_.Wu(t, 
            /* keepPersistedTargetData */ !0), this.nf(t, s);
            break;

          default:
            be();
        }
    }
    async Td(t, e) {
        if (this.Rf) {
            for (const e of t) {
                if (this.Kd.has(e)) {
                    // A target might have been added in a previous attempt
                    ge("SyncEngine", "Adding an already active target " + e);
                    continue;
                }
                const t = await this.N_.Yu(e), s = await this.N_.Qu(t);
                await this.sf(this.Vf(t), s.targetId, 
                /*current=*/ !1), this.$d.listen(s);
            }
            for (const t of e) 
            // Check that the target is still active since the target might have been
            // removed if it has been rejected by the backend.
            this.Kd.has(t) && 
            // Release queries that are still active.
            await this.N_.Wu(t, /* keepPersistedTargetData */ !1).then(() => {
                this.$d.rl(t), this.nf(t);
            }).catch(ci);
        }
    }
}

/**
 * @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 Sn {
    constructor() {
        this.gf = void 0, this.pf = [];
    }
}

/**
 * EventManager is responsible for mapping queries to query event emitters.
 * It handles "fan-out". -- Identical queries will re-use the same watch on the
 * backend.
 */ class Dn {
    constructor(t) {
        this.ol = t, this.yf = new Le(t => t.canonicalId()), this.onlineState = "Unknown" /* Unknown */ , 
        this.bf = new Set, this.ol.subscribe(this);
    }
    async listen(t) {
        const e = t.query;
        let s = !1, i = this.yf.get(e);
        if (i || (s = !0, i = new Sn), s) try {
            i.gf = await this.ol.listen(e);
        } catch (e) {
            const s = ei(e, `Initialization of query '${t.query}' failed`);
            return void t.onError(s);
        }
        this.yf.set(e, i), i.pf.push(t);
        // Run global snapshot listeners if a consistent snapshot has been emitted.
        t.Dd(this.onlineState);
        if (i.gf) {
            t.vf(i.gf) && this.Sf();
        }
    }
    async rl(t) {
        const e = t.query;
        let s = !1;
        const i = this.yf.get(e);
        if (i) {
            const e = i.pf.indexOf(t);
            e >= 0 && (i.pf.splice(e, 1), s = 0 === i.pf.length);
        }
        if (s) return this.yf.delete(e), this.ol.rl(e);
    }
    i_(t) {
        let e = !1;
        for (const s of t) {
            const t = s.query, i = this.yf.get(t);
            if (i) {
                for (const t of i.pf) t.vf(s) && (e = !0);
                i.gf = s;
            }
        }
        e && this.Sf();
    }
    ff(t, e) {
        const s = this.yf.get(t);
        if (s) for (const t of s.pf) t.onError(e);
        // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()
        // after an error.
                this.yf.delete(t);
    }
    af(t) {
        this.onlineState = t;
        let e = !1;
        this.yf.forEach((s, i) => {
            for (const s of i.pf) 
            // Run global snapshot listeners if a consistent snapshot has been emitted.
            s.Dd(t) && (e = !0);
        }), e && this.Sf();
    }
    Df(t) {
        this.bf.add(t), 
        // Immediately fire an initial event, indicating all existing listeners
        // are in-sync.
        t.next();
    }
    Cf(t) {
        this.bf.delete(t);
    }
    // Call all global snapshot listeners that have been set.
    Sf() {
        this.bf.forEach(t => {
            t.next();
        });
    }
}

/**
 * QueryListener takes a series of internal view snapshots and determines
 * when to raise the event.
 *
 * It uses an Observer to dispatch events.
 */ class Cn {
    constructor(t, e, s) {
        this.query = t, this.Ff = e, 
        /**
         * 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.Nf = !1, this.$f = null, this.onlineState = "Unknown" /* Unknown */ , this.options = s || {};
    }
    /**
     * 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.
     */    vf(t) {
        if (!this.options.includeMetadataChanges) {
            // Remove the metadata only changes.
            const e = [];
            for (const s of t.docChanges) 3 /* Metadata */ !== s.type && e.push(s);
            t = new he(t.query, t.docs, t.ss, e, t.ns, t.fromCache, t.rs, 
            /* excludesMetadataChanges= */ !0);
        }
        let e = !1;
        return this.Nf ? this.kf(t) && (this.Ff.next(t), e = !0) : this.Lf(t, this.onlineState) && (this.Mf(t), 
        e = !0), this.$f = t, e;
    }
    onError(t) {
        this.Ff.error(t);
    }
    /** Returns whether a snapshot was raised. */    Dd(t) {
        this.onlineState = t;
        let e = !1;
        return this.$f && !this.Nf && this.Lf(this.$f, t) && (this.Mf(this.$f), e = !0), 
        e;
    }
    Lf(t, e) {
        // Always raise the first event when we're synced
        if (!t.fromCache) return !0;
        // NOTE: We consider OnlineState.Unknown as online (it should become Offline
        // or Online if we wait long enough).
                const s = "Offline" /* Offline */ !== e;
        // Don't raise the event if we're online, aren't synced yet (checked
        // above) and are waiting for a sync.
                return (!this.options.Of || !s) && (!t.docs.B() || "Offline" /* Offline */ === e);
        // Raise data from cache if we have any documents or we are offline
        }
    kf(t) {
        // 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 (t.docChanges.length > 0) return !0;
        const e = this.$f && this.$f.hasPendingWrites !== t.hasPendingWrites;
        return !(!t.rs && !e) && !0 === 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.
        }
    Mf(t) {
        t = he.os(t.query, t.docs, t.ns, t.fromCache), this.Nf = !0, this.Ff.next(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.
 */
// TOOD(b/140938512): Drop SimpleQueryEngine and rename IndexFreeQueryEngine.
/**
 * A query engine that takes advantage of the target document mapping in the
 * QueryCache. The IndexFreeQueryEngine optimizes query execution by only
 * reading the documents that previously matched a query plus any documents that were
 * edited after the query was last listened to.
 *
 * There are some cases where Index-Free queries are not guaranteed to produce
 * the same results as full collection scans. In these cases, the
 * IndexFreeQueryEngine falls back to full query processing. 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 Fn {
    Su(t) {
        this.xf = t;
    }
    Zn(t, e, i, n) {
        // Queries that match all documents don't benefit from using
        // IndexFreeQueries. It is more efficient to scan all documents in a
        // collection, rather than to perform individual lookups.
        return e.te() || i.isEqual(y.min()) ? this.Bf(t, e) : this.xf.Yn(t, n).next(r => {
            const h = this.qf(e, r);
            return (e.oe() || e.ae()) && this.yd(e.Bt, h, n, i) ? this.Bf(t, e) : (Pe() <= s.DEBUG && ge("IndexFreeQueryEngine", "Re-using previous result from %s to execute query: %s", i.toString(), e.toString()), 
            this.xf.Zn(t, e, i).next(t => (
            // We merge `previousResults` into `updateResults`, since
            // `updateResults` is already a DocumentMap. If a document is
            // contained in both lists, then its contents are the same.
            h.forEach(e => {
                t = t.Ae(e.key, e);
            }), t)));
        });
        // 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.  */    qf(t, e) {
        // Sort the documents and re-apply the query filter since previously
        // matching documents do not necessarily still match the query.
        let s = new jt((e, s) => t.se(e, s));
        return e.forEach((e, i) => {
            i instanceof Vt && t.matches(i) && (s = s.add(i));
        }), s;
    }
    /**
     * Determines if a limit query needs to be refilled from cache, making it
     * ineligible for index-free execution.
     *
     * @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.
     */    yd(t, e, s, i) {
        // The query needs to be refilled if a previously matching document no
        // longer matches.
        if (s.size !== e.size) return !0;
        // 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 n = "F" /* First */ === t ? e.last() : e.first();
        return !!n && (n.hasPendingWrites || n.version.S(i) > 0);
    }
    Bf(t, e) {
        return Pe() <= s.DEBUG && ge("IndexFreeQueryEngine", "Using full collection scan to execute query:", e.toString()), 
        this.xf.Zn(t, e, y.min());
    }
}

/**
 * @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 Nn {
    constructor(t, e) {
        this.jn = t, this.hh = e, 
        /**
         * The set of all mutations that have been sent but not yet been applied to
         * the backend.
         */
        this.Wn = [], 
        /** Next value to use when assigning sequential IDs to each mutation batch. */
        this.Uf = 1, 
        /** The last received stream token from the server, used to acknowledge which
         * responses the client has processed. Stream tokens are opaque checkpoint
         * markers whose only real value is their inclusion in the next request.
         */
        this.lastStreamToken = k.ht, 
        /** An ordered mapping between documents and the mutations batch IDs. */
        this.Qf = new jt(li.Xu);
    }
    Go(t) {
        return xe.resolve(0 === this.Wn.length);
    }
    zo(t, e, s) {
        const i = e.batchId, n = this.Wf(i, "acknowledged");
        ve(0 === n);
        // Verify that the batch in the queue is the one to be acknowledged.
        this.Wn[n];
        return this.lastStreamToken = s, xe.resolve();
    }
    Yo(t) {
        return xe.resolve(this.lastStreamToken);
    }
    Jo(t, e) {
        return this.lastStreamToken = e, xe.resolve();
    }
    Xo(t, e, s, i) {
        const n = this.Uf;
        if (this.Uf++, this.Wn.length > 0) {
            this.Wn[this.Wn.length - 1];
        }
        const r = new Me(n, e, s, i);
        this.Wn.push(r);
        // Track references by document key and index collection parents.
        for (const e of i) this.Qf = this.Qf.add(new li(e.key, n)), this.jn.Dr(t, e.key.path.L());
        return xe.resolve(r);
    }
    Zo(t, e) {
        return xe.resolve(this.jf(e));
    }
    ea(t, e) {
        const s = e + 1, i = this.Kf(s), n = i < 0 ? 0 : i;
        // The requested batchId may still be out of range so normalize it to the
        // start of the queue.
                return xe.resolve(this.Wn.length > n ? this.Wn[n] : null);
    }
    sa() {
        return xe.resolve(0 === this.Wn.length ? -1 : this.Uf - 1);
    }
    ia(t) {
        return xe.resolve(this.Wn.slice());
    }
    Gn(t, e) {
        const s = new li(e, 0), i = new li(e, Number.POSITIVE_INFINITY), n = [];
        return this.Qf.Ke([ s, i ], t => {
            const e = this.jf(t.oc);
            n.push(e);
        }), xe.resolve(n);
    }
    Xn(t, e) {
        let s = new jt(Ce);
        return e.forEach(t => {
            const e = new li(t, 0), i = new li(t, Number.POSITIVE_INFINITY);
            this.Qf.Ke([ e, i ], t => {
                s = s.add(t.oc);
            });
        }), xe.resolve(this.Gf(s));
    }
    nr(t, e) {
        // Use the query path as a prefix for testing if a document matches the
        // query.
        const s = e.path, i = s.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 n = s;
        C.et(n) || (n = n.child(""));
        const r = new li(new C(n), 0);
        // Find unique batchIDs referenced by all documents potentially matching the
        // query.
                let h = new jt(Ce);
        return this.Qf.Ge(t => {
            const e = t.key.path;
            return !!s.q(e) && (
            // 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.
            e.length === i && (h = h.add(t.oc)), !0);
        }, r), xe.resolve(this.Gf(h));
    }
    Gf(t) {
        // Construct an array of matching batches, sorted by batchID to ensure that
        // multiple mutations affecting the same document key are applied in order.
        const e = [];
        return t.forEach(t => {
            const s = this.jf(t);
            null !== s && e.push(s);
        }), e;
    }
    ra(t, e) {
        ve(0 === this.Wf(e.batchId, "removed")), this.Wn.shift();
        let s = this.Qf;
        return xe.forEach(e.mutations, i => {
            const n = new li(i.key, e.batchId);
            return s = s.delete(n), this.hh.Bo(t, i.key);
        }).next(() => {
            this.Qf = s;
        });
    }
    ha(t) {
        // No-op since the memory mutation queue does not maintain a separate cache.
    }
    Ch(t, e) {
        const s = new li(e, 0), i = this.Qf.ze(s);
        return xe.resolve(e.isEqual(i && i.key));
    }
    oa(t) {
        return this.Wn.length, xe.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).
     */    Wf(t, e) {
        return this.Kf(t);
    }
    /**
     * Finds the index of the given batchId in the mutation queue. This operation
     * is O(1).
     *
     * @return 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 remvoed from the queue or past the end of the
     * queue if the batchId is larger than the last added batch.
     */    Kf(t) {
        if (0 === this.Wn.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 t - this.Wn[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 efficent.
     */    jf(t) {
        const e = this.Kf(t);
        return e < 0 || e >= this.Wn.length ? null : this.Wn[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.
 */ class $n {
    /**
     * @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(t, e) {
        this.jn = t, this.zf = e, 
        /** Underlying cache of documents and their read times. */
        this.docs = new Ut(C.N), 
        /** Size of all cached documents. */
        this.size = 0;
    }
    /**
     * 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()`.
     */    Nn(t, e, s) {
        const i = e.key, n = this.docs.get(i), r = n ? n.size : 0, h = this.zf(e);
        return this.docs = this.docs.Ae(i, {
            Mr: e,
            size: h,
            readTime: s
        }), this.size += h - r, this.jn.Dr(t, i.path.L());
    }
    /**
     * 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()`.
     */    kn(t) {
        const e = this.docs.get(t);
        e && (this.docs = this.docs.remove(t), this.size -= e.size);
    }
    Ln(t, e) {
        const s = this.docs.get(e);
        return xe.resolve(s ? s.Mr : null);
    }
    getEntries(t, e) {
        let s = Ht();
        return e.forEach(t => {
            const e = this.docs.get(t);
            s = s.Ae(t, e ? e.Mr : null);
        }), xe.resolve(s);
    }
    Zn(t, e, s) {
        let i = Jt();
        // Documents are ordered by key, so we can use a prefix scan to narrow down
        // the documents we need to match the query against.
                const n = new C(e.path.child("")), r = this.docs.ve(n);
        for (;r.$e(); ) {
            const {key: t, value: {Mr: n, readTime: h}} = r.Ne();
            if (!e.path.q(t.path)) break;
            h.S(s) <= 0 || n instanceof Vt && e.matches(n) && (i = i.Ae(n.key, n));
        }
        return xe.resolve(i);
    }
    Hf(t, e) {
        return xe.forEach(this.docs, t => e(t));
    }
    Yr(t) {
        // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps
        // a separate changelog and does not need special handling for removals.
        return new $n.Jr(this);
    }
    Zr(t) {
        return xe.resolve(this.size);
    }
}

/**
 * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.
 */ $n.Jr = class extends Be {
    constructor(t) {
        super(), this.th = t;
    }
    xn(t) {
        const e = [];
        return this.Dn.forEach((s, i) => {
            i ? e.push(this.th.Nn(t, i, this.readTime)) : this.th.kn(s);
        }), xe.vn(e);
    }
    Mn(t, e) {
        return this.th.Ln(t, e);
    }
    On(t, e) {
        return this.th.getEntries(t, 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.
 */
class kn {
    constructor(t) {
        this.persistence = t, 
        /**
         * Maps a target to the data about that target
         */
        this.Yf = new Le(t => t.canonicalId()), 
        /** The last received snapshot version. */
        this.lastRemoteSnapshotVersion = y.min(), 
        /** The highest numbered target ID encountered. */
        this.highestTargetId = 0, 
        /** The highest sequence number encountered. */
        this.Jf = 0, 
        /**
         * A ordered bidirectional mapping between documents and the remote target
         * IDs.
         */
        this.Xf = new _i, this.targetCount = 0, this.Zf = os.nh();
    }
    js(t, e) {
        return this.Yf.forEach((t, s) => e(s)), xe.resolve();
    }
    _h(t) {
        return xe.resolve(this.lastRemoteSnapshotVersion);
    }
    lh(t) {
        return xe.resolve(this.Jf);
    }
    oh(t) {
        return this.highestTargetId = this.Zf.next(), xe.resolve(this.highestTargetId);
    }
    dh(t, e, s) {
        return s && (this.lastRemoteSnapshotVersion = s), e > this.Jf && (this.Jf = e), 
        xe.resolve();
    }
    Th(t) {
        this.Yf.set(t.target, t);
        const e = t.targetId;
        e > this.highestTargetId && (this.Zf = new os(e), this.highestTargetId = e), t.sequenceNumber > this.Jf && (this.Jf = t.sequenceNumber);
    }
    fh(t, e) {
        return this.Th(e), this.targetCount += 1, xe.resolve();
    }
    Ih(t, e) {
        return this.Th(e), xe.resolve();
    }
    wh(t, e) {
        return this.Yf.delete(e.target), this.Xf.nc(e.targetId), this.targetCount -= 1, 
        xe.resolve();
    }
    Ah(t, e, s) {
        let i = 0;
        const n = [];
        return this.Yf.forEach((r, h) => {
            h.sequenceNumber <= e && null === s.get(h.targetId) && (this.Yf.delete(r), n.push(this.Rh(t, h.targetId)), 
            i++);
        }), xe.vn(n).next(() => i);
    }
    Vh(t) {
        return xe.resolve(this.targetCount);
    }
    gh(t, e) {
        const s = this.Yf.get(e) || null;
        return xe.resolve(s);
    }
    ph(t, e, s) {
        return this.Xf.ec(e, s), xe.resolve();
    }
    bh(t, e, s) {
        this.Xf.ic(e, s);
        const i = this.persistence.hh, n = [];
        return i && e.forEach(e => {
            n.push(i.Bo(t, e));
        }), xe.vn(n);
    }
    Rh(t, e) {
        return this.Xf.nc(e), xe.resolve();
    }
    Sh(t, e) {
        const s = this.Xf.hc(e);
        return xe.resolve(s);
    }
    Ch(t, e) {
        return xe.resolve(this.Xf.Ch(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.
 */
/**
 * A memory-backed instance of Persistence. Data is stored only in RAM and
 * not persisted across sessions.
 */
class Ln {
    /**
     * 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(t) {
        this.tT = {}, this.Bh = new je(0), this.qh = !1, this.qh = !0, this.hh = t(this), 
        this.Yh = new kn(this);
        this.jn = new Xe, this.Qn = new $n(this.jn, t => this.hh.eT(t));
    }
    start() {
        return Promise.resolve();
    }
    mo() {
        // No durable state to ensure is closed on shutdown.
        return this.qh = !1, Promise.resolve();
    }
    get ro() {
        return this.qh;
    }
    ho() {
        // No op.
    }
    Fo() {
        return this.jn;
    }
    vo(t) {
        let e = this.tT[t.s()];
        return e || (e = new Nn(this.jn, this.hh), this.tT[t.s()] = e), e;
    }
    Do() {
        return this.Yh;
    }
    Co() {
        return this.Qn;
    }
    runTransaction(t, e, s) {
        ge("MemoryPersistence", "Starting transaction:", t);
        const i = new Mn(this.Bh.next());
        return this.hh.sT(), s(i).next(t => this.hh.iT(i).next(() => t)).yn().then(t => (i.Un(), 
        t));
    }
    nT(t, e) {
        return xe.Sn(Object.values(this.tT).map(s => () => s.Ch(t, e)));
    }
}

/**
 * Memory persistence is not actually transactional, but future implementations
 * may have transaction-scoped state.
 */ class Mn extends Ue {
    constructor(t) {
        super(), this.Oh = t;
    }
}

class On {
    constructor(t) {
        this.persistence = t, 
        /** Tracks all documents that are active in Query views. */
        this.rT = new _i, 
        /** The list of documents that are potentially GCed after each transaction. */
        this.hT = null;
    }
    static oT(t) {
        return new On(t);
    }
    get aT() {
        if (this.hT) return this.hT;
        throw be();
    }
    yh(t, e, s) {
        return this.rT.yh(s, e), this.aT.delete(s), xe.resolve();
    }
    vh(t, e, s) {
        return this.rT.vh(s, e), this.aT.add(s), xe.resolve();
    }
    Bo(t, e) {
        return this.aT.add(e), xe.resolve();
    }
    removeTarget(t, e) {
        this.rT.nc(e.targetId).forEach(t => this.aT.add(t));
        const s = this.persistence.Do();
        return s.Sh(t, e.targetId).next(t => {
            t.forEach(t => this.aT.add(t));
        }).next(() => s.wh(t, e));
    }
    sT() {
        this.hT = new Set;
    }
    iT(t) {
        // Remove newly orphaned documents.
        const e = this.persistence.Co().Yr();
        return xe.forEach(this.aT, s => this.uT(t, s).next(t => {
            t || e.kn(s);
        })).next(() => (this.hT = null, e.apply(t)));
    }
    Wo(t, e) {
        return this.uT(t, e).next(t => {
            t ? this.aT.delete(e) : this.aT.add(e);
        });
    }
    eT(t) {
        // For eager GC, we don't care about the document size, there are no size thresholds.
        return 0;
    }
    uT(t, e) {
        return xe.Sn([ () => xe.resolve(this.rT.Ch(e)), () => this.persistence.Do().Ch(t, e), () => this.persistence.nT(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.
 */
/**
 * Provides all components needed for Firestore with in-memory persistence.
 * Uses EagerGC garbage collection.
 */
class xn {
    async initialize(t) {
        this.Ud = this.cT(t), this.persistence = this._T(t), await this.persistence.start(), 
        this.lT = this.dT(t), this.N_ = this.fT(t), this.$d = this.TT(t), this.ol = this.ET(t), 
        this.IT = this.wT(t), this.Ud.g_ = t => this.ol.Dd(t, 1 /* SharedClientState */), 
        this.$d.ol = this.ol, await this.N_.start(), await this.Ud.start(), await this.$d.start(), 
        await this.$d.Vl(this.ol.tf);
    }
    wT(t) {
        return new Dn(this.ol);
    }
    dT(t) {
        return null;
    }
    fT(t) {
        return new ai(this.persistence, new Fn, t.RT);
    }
    _T(t) {
        return new Ln(On.oT);
    }
    TT(t) {
        return new cn(this.N_, t.T_, t.Aa, t => this.ol.Dd(t, 0 /* RemoteStore */), t.platform.AT());
    }
    cT(t) {
        return new An;
    }
    ET(t) {
        return new bn(this.N_, this.$d, this.Ud, t.RT, t.Qd);
    }
    clearPersistence(t) {
        throw new R(w.FAILED_PRECONDITION, "You are using the memory-only build of Firestore. Persistence support is only available via the @firebase/firestore bundle or the firebase-firestore.js build.");
    }
}

/**
 * Provides all components needed for Firestore with IndexedDB persistence.
 */ class Bn extends xn {
    async initialize(t) {
        await super.initialize(t), 
        // NOTE: This will immediately call the listener, so we make sure to
        // set it after localStore / remoteStore are started.
        await this.persistence.no(async t => {
            await this.ol.Vl(t), this.lT && (t && !this.lT.ro ? this.lT.start(this.N_) : t || this.lT.stop());
        });
    }
    fT(t) {
        return new ui(this.persistence, new Fn, t.RT);
    }
    ET(t) {
        const e = new vn(this.N_, this.$d, this.Ud, t.RT, t.Qd);
        return this.Ud instanceof Rn && (this.Ud.ol = e), e;
    }
    dT(t) {
        const e = this.persistence.hh.ko;
        return new hi(e, t.Aa);
    }
    _T(t) {
        const e = Ts.$o(t.mT), s = t.platform.bc(t.mT.ii);
        return new Ts(t.PT.synchronizeTabs, e, t.clientId, t.platform, ri.hu(t.PT.cacheSizeBytes), t.Aa, s, this.Ud);
    }
    cT(t) {
        if (t.PT.VT && t.PT.synchronizeTabs) {
            if (!Rn.Gh(t.platform)) throw new R(w.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage.");
            const e = Ts.$o(t.mT);
            return new Rn(t.Aa, t.platform, e, t.clientId, t.RT);
        }
        return new An;
    }
    clearPersistence(t) {
        const e = Ts.$o(t);
        return Ts.clearPersistence(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.
 */
/**
 * 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 qn {
    constructor(t, e, s, 
    /**
     * 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).
     */
    i) {
        this.platform = t, this.mT = e, this.credentials = s, this.Aa = i, this.clientId = De.cn();
    }
    /**
     * Starts up the FirestoreClient, returning only whether or not enabling
     * persistence succeeded.
     *
     * The intent here is to "do the right thing" as far as users are concerned.
     * Namely, in cases where offline persistence is requested and possible,
     * enable it, but otherwise fall back to persistence disabled. For the most
     * part we expect this to succeed one way or the other so we don't expect our
     * users to actually wait on the firestore.enablePersistence Promise since
     * they generally won't care.
     *
     * Of course some users actually do care about whether or not persistence
     * was successfully enabled, so the Promise returned from this method
     * indicates this outcome.
     *
     * This presents a problem though: even before enablePersistence resolves or
     * rejects, users may have made calls to e.g. firestore.collection() which
     * means that the FirestoreClient in there will be available and will be
     * enqueuing actions on the async queue.
     *
     * Meanwhile any failure of an operation on the async queue causes it to
     * panic and reject any further work, on the premise that unhandled errors
     * are fatal.
     *
     * Consequently the fallback is handled internally here in start, and if the
     * fallback succeeds we signal success to the async queue even though the
     * start() itself signals failure.
     *
     * @param componentProvider Provider that returns all core components.
     * @param persistenceSettings Settings object to configure offline
     *     persistence.
     * @returns A deferred result indicating the user-visible result of enabling
     *     offline persistence. This method will reject this if IndexedDB fails to
     *     start for any reason. If usePersistence is false this is
     *     unconditionally resolved.
     */    start(t, e) {
        this.gT();
        // We defer our initialization until we get the current user from
        // setChangeListener(). We block the async queue until we got the initial
        // user and the initialization is completed. This will prevent any scheduled
        // work from happening before initialization is completed.
        // If initializationDone resolved then the FirestoreClient is in a usable
        // state.
        const s = new Ke, i = new Ke;
        // If usePersistence is true, certain classes of errors while starting are
        // recoverable but only by falling back to persistence disabled.
        
        // If there's an error in the first case but not in recovery we cannot
        // reject the promise blocking the async queue because this will cause the
        // async queue to panic.
                let n = !1;
        // Return only the result of enabling persistence. Note that this does not
        // need to await the completion of initializationDone because the result of
        // this method should not reflect any other kind of failure to start.
        return this.credentials.l(r => {
            if (!n) return n = !0, ge("FirestoreClient", "Initializing. user=", r.uid), this.pT(t, e, r, i).then(s.resolve, s.reject);
            this.Aa.Ua(() => this.Pl(r));
        }), 
        // Block the async queue until initialization is done
        this.Aa.uo(() => s.promise), i.promise;
    }
    /** Enables the network connection and requeues all pending operations. */    enableNetwork() {
        return this.gT(), this.Aa.enqueue(() => this.ol.enableNetwork());
    }
    /**
     * Initializes persistent storage, attempting to use IndexedDB if
     * usePersistence is true or memory-only if false.
     *
     * If IndexedDB fails because it's already open in another tab or because the
     * platform can't possibly support our implementation then this method rejects
     * the persistenceResult and falls back on memory-only persistence.
     *
     * @param componentProvider The provider that provides all core componennts
     *     for IndexedDB or memory-backed persistence
     * @param persistenceSettings Settings object to configure offline persistence
     * @param user The initial user
     * @param persistenceResult A deferred result indicating the user-visible
     *     result of enabling offline persistence. This method will reject this if
     *     IndexedDB fails to start for any reason. If usePersistence is false
     *     this is unconditionally resolved.
     * @returns a Promise indicating whether or not initialization should
     *     continue, i.e. that one of the persistence implementations actually
     *     succeeded.
     */    async pT(t, e, s, i) {
        try {
            // TODO(mrschmidt): Ideally, ComponentProvider would also initialize
            // Datastore (without duplicating the initializing logic once per
            // provider).
            const n = await this.platform.yT(this.mT), r = this.platform.bc(this.mT.ii), h = function(t, e, s) {
                return new on(t, e, s);
            }(n, this.credentials, r);
            await t.initialize({
                Aa: this.Aa,
                mT: this.mT,
                platform: this.platform,
                T_: h,
                clientId: this.clientId,
                RT: s,
                Qd: 100,
                PT: e
            }), this.persistence = t.persistence, this.Ud = t.Ud, this.N_ = t.N_, this.$d = t.$d, 
            this.ol = t.ol, this.lT = t.lT, this.bT = t.IT, 
            // When a user calls clearPersistence() in one client, all other clients
            // need to be terminated to allow the delete to succeed.
            this.persistence.ho(async () => {
                await this.terminate();
            }), i.resolve();
        } catch (t) {
            // An unknown failure on the first stage shuts everything down.
            if (
            // Regardless of whether or not the retry succeeds, from an user
            // perspective, offline persistence has failed.
            i.reject(t), !this.vT(t)) throw t;
            return console.warn("Error enabling offline persistence. Falling back to persistence disabled: " + t), 
            this.pT(new xn, {
                VT: !1
            }, s, i);
        }
    }
    /**
     * Decides whether the provided error allows us to gracefully disable
     * persistence (as opposed to crashing the client).
     */    vT(t) {
        return "FirebaseError" === t.name ? t.code === w.FAILED_PRECONDITION || t.code === w.UNIMPLEMENTED : !("undefined" != typeof DOMException && t 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 === t.code || 20 === t.code || 
        // Firefox Private Browsing mode disables IndexedDb and returns
        // INVALID_STATE for any usage.
        11 === t.code);
    }
    /**
     * Checks that the client has not been terminated. Ensures that other methods on
     * this class cannot be called after the client is terminated.
     */    gT() {
        if (this.Aa.La) throw new R(w.FAILED_PRECONDITION, "The client has already been terminated.");
    }
    Pl(t) {
        return this.Aa.Wa(), ge("FirestoreClient", "Credential Changed. Current user: " + t.uid), 
        this.ol.Pl(t);
    }
    /** Disables the network connection. Pending operations will not complete. */    disableNetwork() {
        return this.gT(), this.Aa.enqueue(() => this.ol.disableNetwork());
    }
    terminate() {
        return this.Aa.qa(async () => {
            // PORTING NOTE: LocalStore does not need an explicit shutdown on web.
            this.lT && this.lT.stop(), await this.$d.mo(), await this.Ud.mo(), await this.persistence.mo(), 
            // `removeChangeListener` must be called after shutting down the
            // RemoteStore as it will prevent the RemoteStore from retrieving
            // auth tokens.
            this.credentials.T();
        });
    }
    /**
     * 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.
     */    waitForPendingWrites() {
        this.gT();
        const t = new Ke;
        return this.Aa.uo(() => this.ol.lf(t)), t.promise;
    }
    listen(t, e, s) {
        this.gT();
        const i = new Cn(t, e, s);
        return this.Aa.uo(() => this.bT.listen(i)), i;
    }
    rl(t) {
        // Checks for termination but does not raise error, allowing unlisten after
        // termination to be a no-op.
        this.ST || this.Aa.uo(() => this.bT.rl(t));
    }
    async DT(t) {
        this.gT();
        const e = new Ke;
        return await this.Aa.enqueue(async () => {
            try {
                const s = await this.N_.Uu(t);
                s instanceof Vt ? e.resolve(s) : s instanceof gt ? e.resolve(null) : e.reject(new R(w.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 (s) {
                const i = ei(s, `Failed to get document '${t} from cache`);
                e.reject(i);
            }
        }), e.promise;
    }
    async CT(t) {
        this.gT();
        const e = new Ke;
        return await this.Aa.enqueue(async () => {
            try {
                const s = await this.N_.ju(t, 
                /* usePreviousResults= */ !0), i = new Vn(t, s.Ku), n = i.Vd(s.documents), r = i.xn(n, 
                /* updateLimboDocuments= */ !1);
                e.resolve(r.snapshot);
            } catch (s) {
                const i = ei(s, `Failed to execute query '${t} against cache`);
                e.reject(i);
            }
        }), e.promise;
    }
    write(t) {
        this.gT();
        const e = new Ke;
        return this.Aa.uo(() => this.ol.write(t, e)), e.promise;
    }
    ii() {
        return this.mT.ii;
    }
    Df(t) {
        this.gT(), this.Aa.uo(() => (this.bT.Df(t), Promise.resolve()));
    }
    Cf(t) {
        // Checks for shutdown but does not raise error, allowing remove after
        // shutdown to be a no-op.
        this.ST || this.Aa.uo(() => (this.bT.Cf(t), Promise.resolve()));
    }
    get ST() {
        // Technically, the asyncQueue is still running, but only accepting operations
        // related to termination or supposed to be run after termination. It is effectively
        // terminated to the eyes of users.
        return this.Aa.La;
    }
    transaction(t) {
        this.gT();
        const e = new Ke;
        return this.Aa.uo(() => (this.ol.runTransaction(this.Aa, t, e), Promise.resolve())), 
        e.promise;
    }
}

/**
 * @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 Un {
    constructor(t) {
        this.observer = t, 
        /**
         * When set to true, will not raise future events. Necessary to deal with
         * async detachment of listener.
         */
        this.muted = !1;
    }
    next(t) {
        this.FT(this.observer.next, t);
    }
    error(t) {
        this.FT(this.observer.error, t);
    }
    NT() {
        this.muted = !0;
    }
    FT(t, e) {
        this.muted || setTimeout(() => {
            this.muted || t(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.
 */ function Qn(t) {
    /**
 * Returns true if obj is an object and contains at least one of the specified
 * methods.
 */
    return function(t, e) {
        if ("object" != typeof t || null === t) return !1;
        const s = t;
        for (const t of e) if (t in s && "function" == typeof s[t]) return !0;
        return !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.
 */
    /**
 * Converts Firestore's internal types to the JavaScript types that we expose
 * to the user.
 */ (t, [ "next", "error", "complete" ]);
}

class Wn {
    constructor(t, e, s, i) {
        this.firestore = t, this.timestampsInSnapshots = e, this.$T = s, this.converter = i;
    }
    kT(t) {
        switch (U(t)) {
          case 0 /* NullValue */ :
            return null;

          case 1 /* BooleanValue */ :
            return t.booleanValue;

          case 2 /* NumberValue */ :
            return Y(t.integerValue || t.doubleValue);

          case 3 /* TimestampValue */ :
            return this.LT(t.timestampValue);

          case 4 /* ServerTimestampValue */ :
            return this.MT(t);

          case 5 /* StringValue */ :
            return t.stringValue;

          case 6 /* BlobValue */ :
            return new $i(J(t.bytesValue));

          case 7 /* RefValue */ :
            return this.OT(t.referenceValue);

          case 8 /* GeoPointValue */ :
            return this.xT(t.geoPointValue);

          case 9 /* ArrayValue */ :
            return this.BT(t.arrayValue);

          case 10 /* ObjectValue */ :
            return this.qT(t.mapValue);

          default:
            throw be();
        }
    }
    qT(t) {
        const e = {};
        return N(t.fields || {}, (t, s) => {
            e[t] = this.kT(s);
        }), e;
    }
    xT(t) {
        return new Qi(Y(t.latitude), Y(t.longitude));
    }
    BT(t) {
        return (t.values || []).map(t => this.kT(t));
    }
    MT(t) {
        switch (this.$T) {
          case "previous":
            const e = function t(e) {
                const s = e.mapValue.fields.__previous_value__;
                return x(s) ? t(s) : s;
            }(t);
            return null == e ? null : this.kT(e);

          case "estimate":
            return this.LT(B(t));

          default:
            return null;
        }
    }
    LT(t) {
        const e = H(t), s = new p(e.seconds, e.nanos);
        return this.timestampsInSnapshots ? s : s.toDate();
    }
    OT(t) {
        const e = v.K(t);
        ve(Re(e));
        const s = new ke(e.get(1), e.get(3)), i = new C(e.k(5));
        return s.isEqual(this.firestore.$c) || 
        // TODO(b/64130202): Somehow support foreign references.
        pe(`Document ${i} contains a document ` + "reference within a different database (" + `${s.projectId}/${s.database}) which is not ` + "supported. It will be treated as a reference in the current " + `database (${this.firestore.$c.projectId}/${this.firestore.$c.database}) ` + "instead."), 
        new Yn(i, this.firestore, this.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.
 */
// settings() defaults:
const jn = ri.uu;

/**
 * A concrete type describing all the values that can be applied via a
 * user-supplied firestore.Settings object. This is a separate type so that
 * defaults can be supplied and the value can be checked for equality.
 */
class Kn {
    constructor(t) {
        var e, s, i, n;
        if (void 0 === t.host) {
            if (void 0 !== t.ssl) throw new R(w.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set");
            this.host = "firestore.googleapis.com", this.ssl = !0;
        } else Ri("settings", "non-empty string", "host", t.host), this.host = t.host, Ai("settings", "boolean", "ssl", t.ssl), 
        this.ssl = null === (e = t.ssl) || void 0 === e || e;
        if (bi("settings", t, [ "host", "ssl", "credentials", "timestampsInSnapshots", "cacheSizeBytes", "experimentalForceLongPolling", "ignoreUndefinedProperties" ]), 
        Ai("settings", "object", "credentials", t.credentials), this.credentials = t.credentials, 
        Ai("settings", "boolean", "timestampsInSnapshots", t.timestampsInSnapshots), Ai("settings", "boolean", "ignoreUndefinedProperties", t.ignoreUndefinedProperties), 
        // Nobody should set timestampsInSnapshots anymore, but the error depends on
        // whether they set it to true or false...
        !0 === t.timestampsInSnapshots ? pe("The setting 'timestampsInSnapshots: true' is no longer required and should be removed.") : !1 === t.timestampsInSnapshots && pe("Support for 'timestampsInSnapshots: false' will be removed soon. You must update your code to handle Timestamp objects."), 
        this.timestampsInSnapshots = null === (s = t.timestampsInSnapshots) || void 0 === s || s, 
        this.ignoreUndefinedProperties = null !== (i = t.ignoreUndefinedProperties) && void 0 !== i && i, 
        Ai("settings", "number", "cacheSizeBytes", t.cacheSizeBytes), void 0 === t.cacheSizeBytes) this.cacheSizeBytes = ri._u; else {
            if (t.cacheSizeBytes !== jn && t.cacheSizeBytes < ri.cu) throw new R(w.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${ri.cu}`);
            this.cacheSizeBytes = t.cacheSizeBytes;
        }
        Ai("settings", "boolean", "experimentalForceLongPolling", t.experimentalForceLongPolling), 
        this.forceLongPolling = null !== (n = t.experimentalForceLongPolling) && void 0 !== n && n;
    }
    isEqual(t) {
        return this.host === t.host && this.ssl === t.ssl && this.timestampsInSnapshots === t.timestampsInSnapshots && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.forceLongPolling === t.forceLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties;
    }
}

/**
 * The root reference to the database.
 */ class Gn {
    // Note: We are using `MemoryComponentProvider` as a default
    // ComponentProvider to ensure backwards compatibility with the format
    // expected by the console build.
    constructor(t, e, s = new xn) {
        if (this.UT = null, 
        // Public for use in tests.
        // TODO(mikelehen): Use modularized initialization instead.
        this.QT = new ti, this.INTERNAL = {
            delete: async () => {
                // The client must be initalized to ensure that all subsequent API usage
                // throws an exception.
                this.WT(), await this.jT.terminate();
            }
        }, "object" == typeof t.options) {
            // This is very likely a Firebase app object
            // TODO(b/34177605): Can we somehow use instanceof?
            const s = t;
            this.UT = s, this.$c = Gn.KT(s), this.GT = s.name, this.zT = new P(e);
        } else {
            const e = t;
            if (!e.projectId) throw new R(w.INVALID_ARGUMENT, "Must provide projectId");
            this.$c = new ke(e.projectId, e.database), 
            // Use a default persistenceKey that lines up with FirebaseApp.
            this.GT = "[DEFAULT]", this.zT = new m;
        }
        this.HT = s, this.YT = new Kn({});
    }
    get JT() {
        return this.XT || (
        // Lazy initialize UserDataReader once the settings are frozen
        this.XT = new Hi(this.$c, this.YT.ignoreUndefinedProperties)), this.XT;
    }
    settings(t) {
        fi("Firestore.settings", arguments, 1), Ii("Firestore.settings", "object", 1, t);
        const e = new Kn(t);
        if (this.jT && !this.YT.isEqual(e)) throw new R(w.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only call settings() before calling any other methods on a Firestore object.");
        this.YT = e, void 0 !== e.credentials && (this.zT = function(t) {
            if (!t) return new m;
            switch (t.type) {
              case "gapi":
                const e = t.ZT;
                // Make sure this really is a Gapi client.
                                return ve(!("object" != typeof e || null === e || !e.auth || !e.auth.getAuthHeaderValueForFirstParty)), 
                new g(e, t.V || "0");

              case "provider":
                return t.ZT;

              default:
                throw new R(w.INVALID_ARGUMENT, "makeCredentialsProvider failed due to invalid credential type");
            }
        }
        /**
 * @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 earlist date supported by Firestore timestamps (0001-01-01T00:00:00Z).
        (e.credentials));
    }
    enableNetwork() {
        return this.WT(), this.jT.enableNetwork();
    }
    disableNetwork() {
        return this.WT(), this.jT.disableNetwork();
    }
    enablePersistence(t) {
        var e, s;
        if (this.jT) throw new R(w.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only call enablePersistence() before calling any other methods on a Firestore object.");
        let i = !1;
        return t && (void 0 !== t.experimentalTabSynchronization && pe("The 'experimentalTabSynchronization' setting will be removed. Use 'synchronizeTabs' instead."), 
        i = null !== (s = null !== (e = t.synchronizeTabs) && void 0 !== e ? e : t.experimentalTabSynchronization) && void 0 !== s && s), 
        this.tE(this.HT, {
            VT: !0,
            cacheSizeBytes: this.YT.cacheSizeBytes,
            synchronizeTabs: i
        });
    }
    async clearPersistence() {
        if (void 0 !== this.jT && !this.jT.ST) throw new R(w.FAILED_PRECONDITION, "Persistence cannot be cleared after this Firestore instance is initialized.");
        const t = new Ke;
        return this.QT.Ma(async () => {
            try {
                const e = this.eE();
                await this.HT.clearPersistence(e), t.resolve();
            } catch (e) {
                t.reject(e);
            }
        }), t.promise;
    }
    terminate() {
        return this.app._removeServiceInstance("firestore"), this.INTERNAL.delete();
    }
    get sE() {
        return this.WT(), this.jT.ST;
    }
    waitForPendingWrites() {
        return this.WT(), this.jT.waitForPendingWrites();
    }
    onSnapshotsInSync(t) {
        if (this.WT(), Qn(t)) return this.iE(t);
        {
            Ii("Firestore.onSnapshotsInSync", "function", 1, t);
            const e = {
                next: t
            };
            return this.iE(e);
        }
    }
    iE(t) {
        const e = new Un({
            next: () => {
                t.next && t.next();
            },
            error: t => {
                throw be();
            }
        });
        return this.jT.Df(e), () => {
            e.NT(), this.jT.Cf(e);
        };
    }
    WT() {
        return this.jT || 
        // Kick off starting the client but don't actually wait for it.
        // eslint-disable-next-line @typescript-eslint/no-floating-promises
        this.tE(new xn, {
            VT: !1
        }), this.jT;
    }
    eE() {
        return new $e(this.$c, this.GT, this.YT.host, this.YT.ssl, this.YT.forceLongPolling);
    }
    tE(t, e) {
        const s = this.eE();
        return this.jT = new qn(Ae.nt(), s, this.zT, this.QT), this.jT.start(t, e);
    }
    static KT(t) {
        if (e = t.options, s = "projectId", !Object.prototype.hasOwnProperty.call(e, s)) throw new R(w.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.');
        var e, 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.
 */
        /**
 * Helper function to prevent instantiation through the constructor.
 *
 * This method creates a new constructor that throws when it's invoked.
 * The prototype of that constructor is then set to the prototype of the hidden
 * "class" to expose all the prototype methods and allow for instanceof
 * checks.
 *
 * To also make all the static methods available, all properties of the
 * original constructor are copied to the new constructor.
 */        const i = t.options.projectId;
        if (!i || "string" != typeof i) throw new R(w.INVALID_ARGUMENT, "projectId must be a string in FirebaseApp.options");
        return new ke(i);
    }
    get app() {
        if (!this.UT) throw new R(w.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available");
        return this.UT;
    }
    collection(t) {
        return fi("Firestore.collection", arguments, 1), Ii("Firestore.collection", "non-empty string", 1, t), 
        this.WT(), new sr(v.K(t), this);
    }
    doc(t) {
        return fi("Firestore.doc", arguments, 1), Ii("Firestore.doc", "non-empty string", 1, t), 
        this.WT(), Yn.nE(v.K(t), this);
    }
    collectionGroup(t) {
        if (fi("Firestore.collectionGroup", arguments, 1), Ii("Firestore.collectionGroup", "non-empty string", 1, t), 
        t.indexOf("/") >= 0) throw new R(w.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function ` + "Firestore.collectionGroup(). Collection IDs must not contain '/'.");
        return this.WT(), new tr(new bt(v.G, t), this);
    }
    runTransaction(t) {
        return fi("Firestore.runTransaction", arguments, 1), Ii("Firestore.runTransaction", "function", 1, t), 
        this.WT().transaction(e => t(new zn(this, e)));
    }
    batch() {
        return this.WT(), new Hn(this);
    }
    static get logLevel() {
        switch (Pe()) {
          case s.DEBUG:
            return "debug";

          case s.SILENT:
            return "silent";

          default:
            // The default log level is error
            return "error";
        }
    }
    static setLogLevel(t) {
        switch (fi("Firestore.setLogLevel", arguments, 1), Ii("Firestore.setLogLevel", "non-empty string", 1, t), 
        t) {
          case "debug":
            Ve(s.DEBUG);
            break;

          case "error":
            Ve(s.ERROR);
            break;

          case "silent":
            Ve(s.SILENT);
            break;

          default:
            throw new R(w.INVALID_ARGUMENT, "Invalid log level: " + t);
        }
    }
    // Note: this is not a property because the minifier can't work correctly with
    // the way TypeScript compiler outputs properties.
    rE() {
        return this.YT.timestampsInSnapshots;
    }
}

/**
 * A reference to a transaction.
 */ class zn {
    constructor(t, e) {
        this.hE = t, this.oE = e;
    }
    get(t) {
        fi("Transaction.get", arguments, 1);
        const e = hr("Transaction.get", t, this.hE);
        return this.oE.A_([ e.kc ]).then(t => {
            if (!t || 1 !== t.length) return be();
            const s = t[0];
            if (s instanceof gt) return new Xn(this.hE, e.kc, null, 
            /* fromCache= */ !1, 
            /* hasPendingWrites= */ !1, e.aE);
            if (s instanceof Vt) return new Xn(this.hE, e.kc, s, 
            /* fromCache= */ !1, 
            /* hasPendingWrites= */ !1, e.aE);
            throw be();
        });
    }
    set(t, e, s) {
        Ei("Transaction.set", arguments, 2, 3);
        const i = hr("Transaction.set", t, this.hE);
        s = ir("Transaction.set", s);
        const [n, r] = ar(i.aE, e, "Transaction.set"), h = s.merge || s.mergeFields ? this.hE.JT.Dc(r, n, s.mergeFields) : this.hE.JT.vc(r, n);
        return this.oE.set(i.kc, h), this;
    }
    update(t, e, s, ...i) {
        let n, r;
        return "string" == typeof e || e instanceof ki ? (Ti("Transaction.update", arguments, 3), 
        n = hr("Transaction.update", t, this.hE), r = this.hE.JT.Fc("Transaction.update", e, s, i)) : (fi("Transaction.update", arguments, 2), 
        n = hr("Transaction.update", t, this.hE), r = this.hE.JT.Cc("Transaction.update", e)), 
        this.oE.update(n.kc, r), this;
    }
    delete(t) {
        fi("Transaction.delete", arguments, 1);
        const e = hr("Transaction.delete", t, this.hE);
        return this.oE.delete(e.kc), this;
    }
}

class Hn {
    constructor(t) {
        this.hE = t, this.uE = [], this.cE = !1;
    }
    set(t, e, s) {
        Ei("WriteBatch.set", arguments, 2, 3), this._E();
        const i = hr("WriteBatch.set", t, this.hE);
        s = ir("WriteBatch.set", s);
        const [n, r] = ar(i.aE, e, "WriteBatch.set"), h = s.merge || s.mergeFields ? this.hE.JT.Dc(r, n, s.mergeFields) : this.hE.JT.vc(r, n);
        return this.uE = this.uE.concat(h.Ac(i.kc, lt.ft())), this;
    }
    update(t, e, s, ...i) {
        let n, r;
        return this._E(), "string" == typeof e || e instanceof ki ? (Ti("WriteBatch.update", arguments, 3), 
        n = hr("WriteBatch.update", t, this.hE), r = this.hE.JT.Fc("WriteBatch.update", e, s, i)) : (fi("WriteBatch.update", arguments, 2), 
        n = hr("WriteBatch.update", t, this.hE), r = this.hE.JT.Cc("WriteBatch.update", e)), 
        this.uE = this.uE.concat(r.Ac(n.kc, lt.exists(!0))), this;
    }
    delete(t) {
        fi("WriteBatch.delete", arguments, 1), this._E();
        const e = hr("WriteBatch.delete", t, this.hE);
        return this.uE = this.uE.concat(new It(e.kc, lt.ft())), this;
    }
    commit() {
        return this._E(), this.cE = !0, this.uE.length > 0 ? this.hE.WT().write(this.uE) : Promise.resolve();
    }
    _E() {
        if (this.cE) throw new R(w.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called.");
    }
}

/**
 * A reference to a particular document in a collection in the database.
 */ class Yn {
    constructor(t, e, s) {
        this.kc = t, this.firestore = e, this.aE = s, this.jT = this.firestore.WT();
    }
    static nE(t, e, s) {
        if (t.length % 2 != 0) throw new R(w.INVALID_ARGUMENT, "Invalid document reference. Document references must have an even number of segments, but " + `${t.j()} has ${t.length}`);
        return new Yn(new C(t), e, s);
    }
    get id() {
        return this.kc.path.O();
    }
    get parent() {
        return new sr(this.kc.path.L(), this.firestore, this.aE);
    }
    get path() {
        return this.kc.path.j();
    }
    collection(t) {
        if (fi("DocumentReference.collection", arguments, 1), Ii("DocumentReference.collection", "non-empty string", 1, t), 
        !t) throw new R(w.INVALID_ARGUMENT, "Must provide a non-empty collection name to collection()");
        const e = v.K(t);
        return new sr(this.kc.path.child(e), this.firestore);
    }
    isEqual(t) {
        if (!(t instanceof Yn)) throw vi("isEqual", "DocumentReference", 1, t);
        return this.firestore === t.firestore && this.kc.isEqual(t.kc) && this.aE === t.aE;
    }
    set(t, e) {
        Ei("DocumentReference.set", arguments, 1, 2), e = ir("DocumentReference.set", e);
        const [s, i] = ar(this.aE, t, "DocumentReference.set"), n = e.merge || e.mergeFields ? this.firestore.JT.Dc(i, s, e.mergeFields) : this.firestore.JT.vc(i, s);
        return this.jT.write(n.Ac(this.kc, lt.ft()));
    }
    update(t, e, ...s) {
        let i;
        return "string" == typeof t || t instanceof ki ? (Ti("DocumentReference.update", arguments, 2), 
        i = this.firestore.JT.Fc("DocumentReference.update", t, e, s)) : (fi("DocumentReference.update", arguments, 1), 
        i = this.firestore.JT.Cc("DocumentReference.update", t)), this.jT.write(i.Ac(this.kc, lt.exists(!0)));
    }
    delete() {
        return fi("DocumentReference.delete", arguments, 0), this.jT.write([ new It(this.kc, lt.ft()) ]);
    }
    onSnapshot(...t) {
        Ei("DocumentReference.onSnapshot", arguments, 1, 4);
        let e, s = {
            includeMetadataChanges: !1
        }, i = 0;
        "object" != typeof t[i] || Qn(t[i]) || (s = t[i], bi("DocumentReference.onSnapshot", s, [ "includeMetadataChanges" ]), 
        Ai("DocumentReference.onSnapshot", "boolean", "includeMetadataChanges", s.includeMetadataChanges), 
        i++);
        const n = {
            includeMetadataChanges: s.includeMetadataChanges
        };
        return Qn(t[i]) ? e = t[i] : (Ii("DocumentReference.onSnapshot", "function", i, t[i]), 
        wi("DocumentReference.onSnapshot", "function", i + 1, t[i + 1]), wi("DocumentReference.onSnapshot", "function", i + 2, t[i + 2]), 
        e = {
            next: t[i],
            error: t[i + 1],
            complete: t[i + 2]
        }), this.lE(n, e);
    }
    lE(t, e) {
        let s = t => {
            console.error("Uncaught Error in onSnapshot:", t);
        };
        e.error && (s = e.error.bind(e));
        const i = new Un({
            next: t => {
                if (e.next) {
                    const s = t.docs.get(this.kc);
                    e.next(new Xn(this.firestore, this.kc, s, t.fromCache, t.hasPendingWrites, this.aE));
                }
            },
            error: s
        }), n = this.jT.listen(bt.Wt(this.kc.path), i, t);
        return () => {
            i.NT(), this.jT.rl(n);
        };
    }
    get(t) {
        return Ei("DocumentReference.get", arguments, 0, 1), rr("DocumentReference.get", t), 
        new Promise((e, s) => {
            t && "cache" === t.source ? this.firestore.WT().DT(this.kc).then(t => {
                e(new Xn(this.firestore, this.kc, t, 
                /*fromCache=*/ !0, t instanceof Vt && t.At, this.aE));
            }, s) : this.dE(e, s, t);
        });
    }
    dE(t, e, s) {
        const i = this.lE({
            includeMetadataChanges: !0,
            Of: !0
        }, {
            next: n => {
                // Remove query first before passing event to user to avoid
                // user actions affecting the now stale query.
                i(), !n.exists && n.metadata.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.
                e(new R(w.UNAVAILABLE, "Failed to get document because the client is offline.")) : n.exists && n.metadata.fromCache && s && "server" === s.source ? e(new R(w.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.)')) : t(n);
            },
            error: e
        });
    }
    withConverter(t) {
        return new Yn(this.kc, this.firestore, t);
    }
}

class Jn {
    constructor(t, e) {
        this.hasPendingWrites = t, this.fromCache = e;
    }
    isEqual(t) {
        return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;
    }
}

class Xn {
    constructor(t, e, s, i, n, r) {
        this.hE = t, this.kc = e, this.fE = s, this.TE = i, this.EE = n, this.aE = r;
    }
    data(t) {
        if (Ei("DocumentSnapshot.data", arguments, 0, 1), t = nr("DocumentSnapshot.data", t), 
        this.fE) {
            // We only want to use the converter and create a new DocumentSnapshot
            // if a converter has been provided.
            if (this.aE) {
                const e = new Zn(this.hE, this.kc, this.fE, this.TE, this.EE);
                return this.aE.fromFirestore(e, t);
            }
            return new Wn(this.hE, this.hE.rE(), t.serverTimestamps, 
            /* converter= */ void 0).kT(this.fE.Lt());
        }
    }
    get(t, e) {
        if (Ei("DocumentSnapshot.get", arguments, 1, 2), e = nr("DocumentSnapshot.get", e), 
        this.fE) {
            const s = this.fE.data().field(tn("DocumentSnapshot.get", t));
            if (null !== s) {
                return new Wn(this.hE, this.hE.rE(), e.serverTimestamps, this.aE).kT(s);
            }
        }
    }
    get id() {
        return this.kc.path.O();
    }
    get ref() {
        return new Yn(this.kc, this.hE, this.aE);
    }
    get exists() {
        return null !== this.fE;
    }
    get metadata() {
        return new Jn(this.EE, this.TE);
    }
    isEqual(t) {
        if (!(t instanceof Xn)) throw vi("isEqual", "DocumentSnapshot", 1, t);
        return this.hE === t.hE && this.TE === t.TE && this.kc.isEqual(t.kc) && (null === this.fE ? null === t.fE : this.fE.isEqual(t.fE)) && this.aE === t.aE;
    }
}

class Zn extends Xn {
    data(t) {
        return super.data(t);
    }
}

class tr {
    constructor(t, e, s) {
        this.IE = t, this.firestore = e, this.aE = s;
    }
    where(t, e, s) {
        fi("Query.where", arguments, 3), yi("Query.where", 3, s);
        // Enumerated from the WhereFilterOp type in index.d.ts.
        const i = function(t, e, s, i) {
            if (!e.some(t => t === i)) throw new R(w.INVALID_ARGUMENT, `Invalid value ${pi(i)} provided to function ` + `${t}() for its ${Di(s)} argument. Acceptable ` + `values: ${e.join(", ")}`);
            return i;
        }("Query.where", [ "<" /* LESS_THAN */ , "<=" /* LESS_THAN_OR_EQUAL */ , "==" /* EQUAL */ , ">=" /* GREATER_THAN_OR_EQUAL */ , ">" /* GREATER_THAN */ , "array-contains" /* ARRAY_CONTAINS */ , "in" /* IN */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ ], 2, e);
        let n;
        const r = tn("Query.where", t);
        if (r.Y()) {
            if ("array-contains" /* ARRAY_CONTAINS */ === i || "array-contains-any" /* ARRAY_CONTAINS_ANY */ === i) throw new R(w.INVALID_ARGUMENT, `Invalid Query. You can't perform '${i}' ` + "queries on FieldPath.documentId().");
            if ("in" /* IN */ === i) {
                this.wE(s, i);
                const t = [];
                for (const e of s) t.push(this.RE(e));
                n = {
                    arrayValue: {
                        values: t
                    }
                };
            } else n = this.RE(s);
        } else "in" /* IN */ !== i && "array-contains-any" /* ARRAY_CONTAINS_ANY */ !== i || this.wE(s, i), 
        n = this.firestore.JT.Nc("Query.where", s, 
        // We only allow nested arrays for IN queries.
        /** allowArrays = */ "in" /* IN */ === i);
        const h = vt.create(r, i, n);
        return this.AE(h), new tr(this.IE.Gt(h), this.firestore, this.aE);
    }
    orderBy(t, e) {
        let s;
        if (Ei("Query.orderBy", arguments, 1, 2), wi("Query.orderBy", "non-empty string", 2, e), 
        void 0 === e || "asc" === e) s = "asc" /* ASCENDING */; else {
            if ("desc" !== e) throw new R(w.INVALID_ARGUMENT, `Function Query.orderBy() has unknown direction '${e}', ` + "expected 'asc' or 'desc'.");
            s = "desc" /* DESCENDING */;
        }
        if (null !== this.IE.startAt) throw new R(w.INVALID_ARGUMENT, "Invalid query. You must not call Query.startAt() or Query.startAfter() before calling Query.orderBy().");
        if (null !== this.IE.endAt) throw new R(w.INVALID_ARGUMENT, "Invalid query. You must not call Query.endAt() or Query.endBefore() before calling Query.orderBy().");
        const i = tn("Query.orderBy", t), n = new kt(i, s);
        return this.mE(n), new tr(this.IE.zt(n), this.firestore, this.aE);
    }
    limit(t) {
        return fi("Query.limit", arguments, 1), Ii("Query.limit", "number", 1, t), Si("Query.limit", 1, t), 
        new tr(this.IE.Ht(t), this.firestore, this.aE);
    }
    limitToLast(t) {
        return fi("Query.limitToLast", arguments, 1), Ii("Query.limitToLast", "number", 1, t), 
        Si("Query.limitToLast", 1, t), new tr(this.IE.Yt(t), this.firestore, this.aE);
    }
    startAt(t, ...e) {
        Ti("Query.startAt", arguments, 1);
        const s = this.PE("Query.startAt", t, e, 
        /*before=*/ !0);
        return new tr(this.IE.Jt(s), this.firestore, this.aE);
    }
    startAfter(t, ...e) {
        Ti("Query.startAfter", arguments, 1);
        const s = this.PE("Query.startAfter", t, e, 
        /*before=*/ !1);
        return new tr(this.IE.Jt(s), this.firestore, this.aE);
    }
    endBefore(t, ...e) {
        Ti("Query.endBefore", arguments, 1);
        const s = this.PE("Query.endBefore", t, e, 
        /*before=*/ !0);
        return new tr(this.IE.Xt(s), this.firestore, this.aE);
    }
    endAt(t, ...e) {
        Ti("Query.endAt", arguments, 1);
        const s = this.PE("Query.endAt", t, e, 
        /*before=*/ !1);
        return new tr(this.IE.Xt(s), this.firestore, this.aE);
    }
    isEqual(t) {
        if (!(t instanceof tr)) throw vi("isEqual", "Query", 1, t);
        return this.firestore === t.firestore && this.IE.isEqual(t.IE);
    }
    withConverter(t) {
        return new tr(this.IE, this.firestore, t);
    }
    /** Helper function to create a bound from a document or fields */    PE(t, e, s, i) {
        if (yi(t, 1, e), e instanceof Xn) {
            if (s.length > 0) throw new R(w.INVALID_ARGUMENT, `Too many arguments provided to ${t}().`);
            const n = e;
            if (!n.exists) throw new R(w.NOT_FOUND, "Can't use a DocumentSnapshot that doesn't exist for " + `${t}().`);
            return this.VE(n.fE, i);
        }
        {
            const n = [ e ].concat(s);
            return this.gE(t, n, i);
        }
    }
    /**
     * Create a Bound from a query and a document.
     *
     * Note that the Bound will always include the key of the document
     * and so only the provided document will compare equal to the returned
     * position.
     *
     * Will throw if the document does not contain all fields of the order by
     * of the query or if any of the fields in the order by are an uncommitted
     * server timestamp.
     */    VE(t, e) {
        const s = [];
        // Because people expect to continue/end a query at the exact document
        // provided, we need to use the implicit sort order rather than the explicit
        // sort order, because it's guaranteed to contain the document key. That way
        // the position becomes unambiguous and the query continues/ends exactly at
        // the provided document. Without the key (by using the explicit sort
        // orders), multiple documents could match the position, yielding duplicate
        // results.
                for (const e of this.IE.orderBy) if (e.field.Y()) s.push(X(this.firestore.$c, t.key)); else {
            const i = t.field(e.field);
            if (x(i)) throw new R(w.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + e.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');
            if (null === i) {
                const t = e.field.j();
                throw new R(w.INVALID_ARGUMENT, "Invalid query. You are trying to start or end a query using a " + `document for which the field '${t}' (used as the ` + "orderBy) does not exist.");
            }
            s.push(i);
        }
        return new $t(s, e);
    }
    /**
     * Converts a list of field values to a Bound for the given query.
     */    gE(t, e, s) {
        // Use explicit order by's because it has to match the query the user made
        const i = this.IE.xt;
        if (e.length > i.length) throw new R(w.INVALID_ARGUMENT, `Too many arguments provided to ${t}(). ` + "The number of arguments must be less than or equal to the number of Query.orderBy() clauses");
        const n = [];
        for (let s = 0; s < e.length; s++) {
            const r = e[s];
            if (i[s].field.Y()) {
                if ("string" != typeof r) throw new R(w.INVALID_ARGUMENT, "Invalid query. Expected a string for document ID in " + `${t}(), but got a ${typeof r}`);
                if (!this.IE._e() && -1 !== r.indexOf("/")) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying a collection and ordering by FieldPath.documentId(), " + `the value passed to ${t}() must be a plain document ID, but ` + `'${r}' contains a slash.`);
                const e = this.IE.path.child(v.K(r));
                if (!C.et(e)) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying a collection group and ordering by " + `FieldPath.documentId(), the value passed to ${t}() must result in a ` + `valid document path, but '${e}' is not because it contains an odd number ` + "of segments.");
                const s = new C(e);
                n.push(X(this.firestore.$c, s));
            } else {
                const e = this.firestore.JT.Nc(t, r);
                n.push(e);
            }
        }
        return new $t(n, s);
    }
    onSnapshot(...t) {
        Ei("Query.onSnapshot", arguments, 1, 4);
        let e, s = {}, i = 0;
        return "object" != typeof t[i] || Qn(t[i]) || (s = t[i], bi("Query.onSnapshot", s, [ "includeMetadataChanges" ]), 
        Ai("Query.onSnapshot", "boolean", "includeMetadataChanges", s.includeMetadataChanges), 
        i++), Qn(t[i]) ? e = t[i] : (Ii("Query.onSnapshot", "function", i, t[i]), wi("Query.onSnapshot", "function", i + 1, t[i + 1]), 
        wi("Query.onSnapshot", "function", i + 2, t[i + 2]), e = {
            next: t[i],
            error: t[i + 1],
            complete: t[i + 2]
        }), this.pE(this.IE), this.lE(s, e);
    }
    lE(t, e) {
        let s = t => {
            console.error("Uncaught Error in onSnapshot:", t);
        };
        e.error && (s = e.error.bind(e));
        const i = new Un({
            next: t => {
                e.next && e.next(new er(this.firestore, this.IE, t, this.aE));
            },
            error: s
        }), n = this.firestore.WT(), r = n.listen(this.IE, i, t);
        return () => {
            i.NT(), n.rl(r);
        };
    }
    pE(t) {
        if (t.ae() && 0 === t.xt.length) throw new R(w.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause");
    }
    get(t) {
        return Ei("Query.get", arguments, 0, 1), rr("Query.get", t), this.pE(this.IE), new Promise((e, s) => {
            t && "cache" === t.source ? this.firestore.WT().CT(this.IE).then(t => {
                e(new er(this.firestore, this.IE, t, this.aE));
            }, s) : this.dE(e, s, t);
        });
    }
    dE(t, e, s) {
        const i = this.lE({
            includeMetadataChanges: !0,
            Of: !0
        }, {
            next: n => {
                // Remove query first before passing event to user to avoid
                // user actions affecting the now stale query.
                i(), n.metadata.fromCache && s && "server" === s.source ? e(new R(w.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.)')) : t(n);
            },
            error: e
        });
    }
    /**
     * Parses the given documentIdValue into a ReferenceValue, throwing
     * appropriate errors if the value is anything other than a DocumentReference
     * or String, or if the string is malformed.
     */    RE(t) {
        if ("string" == typeof t) {
            if ("" === t) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying with FieldPath.documentId(), you must provide a valid document ID, but it was an empty string.");
            if (!this.IE._e() && -1 !== t.indexOf("/")) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying a collection by FieldPath.documentId(), you must provide a plain document ID, but " + `'${t}' contains a '/' character.`);
            const e = this.IE.path.child(v.K(t));
            if (!C.et(e)) throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying a collection group by FieldPath.documentId(), the value provided must result in a valid document path, " + `but '${e}' is not because it has an odd number of segments (${e.length}).`);
            return X(this.firestore.$c, new C(e));
        }
        if (t instanceof Yn) {
            const e = t;
            return X(this.firestore.$c, e.kc);
        }
        throw new R(w.INVALID_ARGUMENT, "Invalid query. When querying with FieldPath.documentId(), you must provide a valid string or a DocumentReference, but it was: " + `${pi(t)}.`);
    }
    /**
     * Validates that the value passed into a disjunctrive filter satisfies all
     * array requirements.
     */    wE(t, e) {
        if (!Array.isArray(t) || 0 === t.length) throw new R(w.INVALID_ARGUMENT, "Invalid Query. A non-empty array is required for " + `'${e.toString()}' filters.`);
        if (t.length > 10) throw new R(w.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters support a ` + "maximum of 10 elements in the value array.");
        if (t.indexOf(null) >= 0) throw new R(w.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters cannot contain 'null' ` + "in the value array.");
        if (t.filter(t => Number.isNaN(t)).length > 0) throw new R(w.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters cannot contain 'NaN' ` + "in the value array.");
    }
    AE(t) {
        if (t instanceof vt) {
            const e = [ "array-contains" /* ARRAY_CONTAINS */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ ], s = [ "in" /* IN */ , "array-contains-any" /* ARRAY_CONTAINS_ANY */ ], i = e.indexOf(t.op) >= 0, n = s.indexOf(t.op) >= 0;
            if (t.ue()) {
                const e = this.IE.jt();
                if (null !== e && !e.isEqual(t.field)) throw new R(w.INVALID_ARGUMENT, "Invalid query. All where filters with an inequality (<, <=, >, or >=) must be on the same field. But you have" + ` inequality filters on '${e.toString()}'` + ` and '${t.field.toString()}'`);
                const s = this.IE.Kt();
                null !== s && this.yE(t.field, s);
            } else if (n || i) {
                // You can have at most 1 disjunctive filter and 1 array filter. Check if
                // the new filter conflicts with an existing one.
                let r = null;
                if (n && (r = this.IE.ce(s)), null === r && i && (r = this.IE.ce(e)), null != r) 
                // We special case when it's a duplicate op to give a slightly clearer error message.
                throw r === t.op ? new R(w.INVALID_ARGUMENT, "Invalid query. You cannot use more than one " + `'${t.op.toString()}' filter.`) : new R(w.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters ` + `with '${r.toString()}' filters.`);
            }
        }
    }
    mE(t) {
        if (null === this.IE.Kt()) {
            // This is the first order by. It must match any inequality.
            const e = this.IE.jt();
            null !== e && this.yE(e, t.field);
        }
    }
    yE(t, e) {
        if (!e.isEqual(t)) throw new R(w.INVALID_ARGUMENT, "Invalid query. You have a where filter with an inequality " + `(<, <=, >, or >=) on field '${t.toString()}' ` + `and so you must also use '${t.toString()}' ` + "as your first Query.orderBy(), but your first Query.orderBy() " + `is on field '${e.toString()}' instead.`);
    }
}

class er {
    constructor(t, e, s, i) {
        this.hE = t, this.bE = e, this.vE = s, this.aE = i, this.SE = null, this.DE = null, 
        this.metadata = new Jn(s.hasPendingWrites, s.fromCache);
    }
    get docs() {
        const t = [];
        return this.forEach(e => t.push(e)), t;
    }
    get empty() {
        return this.vE.docs.B();
    }
    get size() {
        return this.vE.docs.size;
    }
    forEach(t, e) {
        Ei("QuerySnapshot.forEach", arguments, 1, 2), Ii("QuerySnapshot.forEach", "function", 1, t), 
        this.vE.docs.forEach(s => {
            t.call(e, this.CE(s));
        });
    }
    get query() {
        return new tr(this.bE, this.hE, this.aE);
    }
    docChanges(t) {
        t && (bi("QuerySnapshot.docChanges", t, [ "includeMetadataChanges" ]), Ai("QuerySnapshot.docChanges", "boolean", "includeMetadataChanges", t.includeMetadataChanges));
        const e = !(!t || !t.includeMetadataChanges);
        if (e && this.vE.hs) throw new R(w.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().");
        return this.SE && this.DE === e || (this.SE = 
        /**
 * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.
 *
 * Exported for testing.
 */
        function(t, e, s, i) {
            if (s.ss.B()) {
                // Special case the first snapshot because index calculation is easy and
                // fast
                let e, n = 0;
                return s.docChanges.map(r => {
                    const h = new Zn(t, r.doc.key, r.doc, s.fromCache, s.ns.has(r.doc.key), i);
                    return e = r.doc, {
                        type: "added",
                        doc: h,
                        oldIndex: -1,
                        newIndex: n++
                    };
                });
            }
            {
                // A DocumentSet that is updated incrementally as changes are applied to use
                // to lookup the index of a document.
                let n = s.ss;
                return s.docChanges.filter(t => e || 3 /* Metadata */ !== t.type).map(e => {
                    const r = new Zn(t, e.doc.key, e.doc, s.fromCache, s.ns.has(e.doc.key), i);
                    let h = -1, o = -1;
                    return 0 /* Added */ !== e.type && (h = n.indexOf(e.doc.key), n = n.delete(e.doc.key)), 
                    1 /* Removed */ !== e.type && (n = n.add(e.doc), o = n.indexOf(e.doc.key)), {
                        type: or(e.type),
                        doc: r,
                        oldIndex: h,
                        newIndex: o
                    };
                });
            }
        }(this.hE, e, this.vE, this.aE), this.DE = e), this.SE;
    }
    /** Check the equality. The call can be very expensive. */    isEqual(t) {
        if (!(t instanceof er)) throw vi("isEqual", "QuerySnapshot", 1, t);
        return this.hE === t.hE && this.bE.isEqual(t.bE) && this.vE.isEqual(t.vE) && this.aE === t.aE;
    }
    CE(t) {
        return new Zn(this.hE, t.key, t, this.metadata.fromCache, this.vE.ns.has(t.key), this.aE);
    }
}

class sr extends tr {
    constructor(t, e, s) {
        if (super(bt.Wt(t), e, s), this.FE = t, t.length % 2 != 1) throw new R(w.INVALID_ARGUMENT, "Invalid collection reference. Collection references must have an odd number of segments, but " + `${t.j()} has ${t.length}`);
    }
    get id() {
        return this.IE.path.O();
    }
    get parent() {
        const t = this.IE.path.L();
        return t.B() ? null : new Yn(new C(t), this.firestore);
    }
    get path() {
        return this.IE.path.j();
    }
    doc(t) {
        if (Ei("CollectionReference.doc", arguments, 0, 1), 
        // We allow omission of 'pathString' but explicitly prohibit passing in both
        // 'undefined' and 'null'.
        0 === arguments.length && (t = De.cn()), Ii("CollectionReference.doc", "non-empty string", 1, t), 
        "" === t) throw new R(w.INVALID_ARGUMENT, "Document path must be a non-empty string");
        const e = v.K(t);
        return Yn.nE(this.IE.path.child(e), this.firestore, this.aE);
    }
    add(t) {
        fi("CollectionReference.add", arguments, 1), Ii("CollectionReference.add", "object", 1, this.aE ? this.aE.toFirestore(t) : t);
        const e = this.doc();
        return e.set(t).then(() => e);
    }
    withConverter(t) {
        return new sr(this.FE, this.firestore, t);
    }
}

function ir(t, e) {
    if (void 0 === e) return {
        merge: !1
    };
    if (bi(t, e, [ "merge", "mergeFields" ]), Ai(t, "boolean", "merge", e.merge), mi(t, "mergeFields", "a string or a FieldPath", e.mergeFields, t => "string" == typeof t || t instanceof ki), 
    void 0 !== e.mergeFields && void 0 !== e.merge) throw new R(w.INVALID_ARGUMENT, `Invalid options passed to function ${t}(): You cannot specify both "merge" ` + 'and "mergeFields".');
    return e;
}

function nr(t, e) {
    return void 0 === e ? {} : (bi(t, e, [ "serverTimestamps" ]), Pi(t, 0, "serverTimestamps", e.serverTimestamps, [ "estimate", "previous", "none" ]), 
    e);
}

function rr(t, e) {
    wi(t, "object", 1, e), e && (bi(t, e, [ "source" ]), Pi(t, 0, "source", e.source, [ "default", "server", "cache" ]));
}

function hr(t, e, s) {
    if (e instanceof Yn) {
        if (e.firestore !== s) throw new R(w.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance.");
        return e;
    }
    throw vi(t, "DocumentReference", 1, e);
}

function or(t) {
    switch (t) {
      case 0 /* Added */ :
        return "added";

      case 2 /* Modified */ :
      case 3 /* Metadata */ :
        return "modified";

      case 1 /* Removed */ :
        return "removed";

      default:
        return be();
    }
}

/**
 * Converts custom model object of type T into DocumentData by applying the
 * converter if it exists.
 *
 * This function is used when converting user objects to DocumentData
 * because we want to provide the user with a more specific error message if
 * their set() or fails due to invalid data originating from a toFirestore()
 * call.
 */ function ar(t, e, s) {
    let i;
    return t ? (i = t.toFirestore(e), s = "toFirestore() in " + s) : i = e, [ i, s ];
}

function ur(t, e) {
    function s() {
        let t = "This constructor is private.";
        throw e && (t += " ", t += e), new R(w.INVALID_ARGUMENT, t);
    }
    // Make sure instanceof checks work and all methods are exposed on the public
    // constructor
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
    return s.prototype = t.prototype, 
    // Copy any static methods/members
    Object.assign(s, t), 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.
 */
// Public instance that disallows construction at runtime. Note that this still
// allows instanceof checks.
const cr = ur(Gn, "Use firebase.firestore() instead."), _r = ur(zn, "Use firebase.firestore().runTransaction() instead."), lr = ur(Hn, "Use firebase.firestore().batch() instead."), dr = ur(Yn, "Use firebase.firestore().doc() instead."), fr = ur(Xn), Tr = ur(Zn), Er = ur(tr), Ir = ur(er), wr = ur(sr, "Use firebase.firestore().collection() instead."), Rr = ur(class {
    static delete() {
        return di("FieldValue.delete", arguments), new Oi;
    }
    static serverTimestamp() {
        return di("FieldValue.serverTimestamp", arguments), new xi;
    }
    static arrayUnion(...t) {
        // NOTE: We don't actually parse the data until it's used in set() or
        // update() since we need access to the Firestore instance.
        return Ti("FieldValue.arrayUnion", arguments, 1), new Bi(t);
    }
    static arrayRemove(...t) {
        // NOTE: We don't actually parse the data until it's used in set() or
        // update() since we need access to the Firestore instance.
        return Ti("FieldValue.arrayRemove", arguments, 1), new qi(t);
    }
    static increment(t) {
        return Ii("FieldValue.increment", "number", 1, t), fi("FieldValue.increment", arguments, 1), 
        new Ui(t);
    }
    isEqual(t) {
        return this === t;
    }
}, "Use FieldValue.<field>() instead."), Ar = ur($i, "Use Blob.fromUint8Array() or Blob.fromBase64String() instead."), mr = {
    Firestore: cr,
    GeoPoint: Qi,
    Timestamp: p,
    Blob: Ar,
    Transaction: _r,
    WriteBatch: lr,
    DocumentReference: dr,
    DocumentSnapshot: fr,
    Query: Er,
    QueryDocumentSnapshot: Tr,
    QuerySnapshot: Ir,
    CollectionReference: wr,
    FieldPath: ki,
    FieldValue: Rr,
    setLogLevel: Gn.setLogLevel,
    CACHE_SIZE_UNLIMITED: jn
};

/**
 * @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 Pr {
    B_(t) {
        // No-op.
    }
    mo() {
        // 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 */
/**
 * Browser implementation of ConnectivityMonitor.
 */
class Vr {
    constructor() {
        this.NE = () => this.$E(), this.kE = () => this.LE(), this.ME = [], this.OE();
    }
    B_(t) {
        this.ME.push(t);
    }
    mo() {
        window.removeEventListener("online", this.NE), window.removeEventListener("offline", this.kE);
    }
    OE() {
        window.addEventListener("online", this.NE), window.addEventListener("offline", this.kE);
    }
    $E() {
        ge("ConnectivityMonitor", "Network connectivity changed: AVAILABLE");
        for (const t of this.ME) t(0 /* AVAILABLE */);
    }
    LE() {
        ge("ConnectivityMonitor", "Network connectivity changed: UNAVAILABLE");
        for (const t of this.ME) t(1 /* 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 Gh() {
        return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;
    }
}

/**
 * @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 gr {
    constructor(t) {
        this.xE = t.xE, this.BE = t.BE;
    }
    e_(t) {
        this.qE = t;
    }
    Yc(t) {
        this.UE = t;
    }
    onMessage(t) {
        this.QE = t;
    }
    close() {
        this.BE();
    }
    send(t) {
        this.xE(t);
    }
    WE() {
        this.qE();
    }
    jE(t) {
        this.UE(t);
    }
    KE(t) {
        this.QE(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.
 */ const pr = {
    BatchGetDocuments: "batchGet",
    Commit: "commit"
}, yr = "gl-js/ fire/" + E;

class br {
    constructor(t) {
        this.ii = t.ii;
        const e = t.ssl ? "https" : "http";
        this.GE = e + "://" + t.host, this.forceLongPolling = t.forceLongPolling;
    }
    /**
     * Modifies the headers for a request, adding any authorization token if
     * present and any additional headers for the request.
     */    zE(t, e) {
        if (e) for (const s in e.o) e.o.hasOwnProperty(s) && (t[s] = e.o[s]);
        t["X-Goog-Api-Client"] = yr;
    }
    d_(t, e, s) {
        const i = this.HE(t);
        return new Promise((n, r) => {
            const h = new _;
            h.listenOnce(l.COMPLETE, () => {
                try {
                    switch (h.getLastErrorCode()) {
                      case d.NO_ERROR:
                        const e = h.getResponseJson();
                        ge("Connection", "XHR received:", JSON.stringify(e)), n(e);
                        break;

                      case d.TIMEOUT:
                        ge("Connection", 'RPC "' + t + '" timed out'), r(new R(w.DEADLINE_EXCEEDED, "Request time out"));
                        break;

                      case d.HTTP_ERROR:
                        const s = h.getStatus();
                        if (ge("Connection", 'RPC "' + t + '" failed with status:', s, "response text:", h.getResponseText()), 
                        s > 0) {
                            const t = h.getResponseJson().error;
                            if (t && t.status && t.message) {
                                const e = function(t) {
                                    const e = t.toLowerCase().replace("_", "-");
                                    return Object.values(w).indexOf(e) >= 0 ? e : w.UNKNOWN;
                                }(t.status);
                                r(new R(e, t.message));
                            } else r(new R(w.UNKNOWN, "Server responded with status " + h.getStatus()));
                        } else 
                        // If we received an HTTP_ERROR but there's no status code,
                        // it's most probably a connection issue
                        ge("Connection", 'RPC "' + t + '" failed'), r(new R(w.UNAVAILABLE, "Connection failed."));
                        break;

                      default:
                        be();
                    }
                } finally {
                    ge("Connection", 'RPC "' + t + '" completed.');
                }
            });
            // The database field is already encoded in URL. Specifying it again in
            // the body is not necessary in production, and will cause duplicate field
            // errors in the Firestore Emulator. Let's remove it.
            const o = Object.assign({}, e);
            delete o.database;
            const a = JSON.stringify(o);
            ge("Connection", "XHR sending: ", i + " " + a);
            // 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.
            const u = {
                "Content-Type": "text/plain"
            };
            this.zE(u, s), h.send(i, "POST", a, u, 15);
        });
    }
    f_(t, e, s) {
        // The REST API automatically aggregates all of the streamed results, so we
        // can just use the normal invoke() method.
        return this.d_(t, e, s);
    }
    s_(t, e) {
        const s = [ this.GE, "/", "google.firestore.v1.Firestore", "/", t, "/channel" ], i = f(), c = {
            // 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.ii.projectId}/databases/${this.ii.database}`
            },
            sendRawJson: !0,
            supportsCrossDomainXhr: !0,
            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
        };
        this.zE(c.initMessageHeaders, e), 
        // 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 httpHeadersOverwriteParam option to specify that
        // the headers should instead be encoded into a special "$httpHeaders" query
        // parameter, which is recognized by the webchannel backend. This is
        // formally defined here:
        // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32
        // TODO(b/145624756): There is a backend bug where $httpHeaders isn't respected if the request
        // doesn't have an Origin header. So we have to exclude a few browser environments that are
        // known to (sometimes) not include an Origin. See
        // https://github.com/firebase/firebase-js-sdk/issues/1491.
        n() || r() || h() || o() || a() || u() || (c.httpHeadersOverwriteParam = "$httpHeaders");
        const _ = s.join("");
        ge("Connection", "Creating WebChannel: " + _ + " " + c);
        const l = i.createWebChannel(_, 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 d = !1, E = !1;
        // 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 I = new gr({
            xE: t => {
                E ? ge("Connection", "Not sending because WebChannel is closed:", t) : (d || (ge("Connection", "Opening WebChannel transport."), 
                l.open(), d = !0), ge("Connection", "WebChannel sending:", t), l.send(t));
            },
            BE: () => l.close()
        }), A = (t, e) => {
            // TODO(dimond): closure typing seems broken because WebChannel does
            // not implement goog.events.Listenable
            l.listen(t, t => {
                try {
                    e(t);
                } catch (t) {
                    setTimeout(() => {
                        throw t;
                    }, 0);
                }
            });
        };
        // Closure events are guarded and exceptions are swallowed, so catch any
        // exception and rethrow using a setTimeout so they become visible again.
        // Note that eventually this function could go away if we are confident
        // enough the code is exception free.
                return A(T.EventType.OPEN, () => {
            E || ge("Connection", "WebChannel transport opened.");
        }), A(T.EventType.CLOSE, () => {
            E || (E = !0, ge("Connection", "WebChannel transport closed"), I.jE());
        }), A(T.EventType.ERROR, t => {
            E || (E = !0, ge("Connection", "WebChannel transport errored:", t), I.jE(new R(w.UNAVAILABLE, "The operation could not be completed")));
        }), A(T.EventType.MESSAGE, t => {
            var e;
            if (!E) {
                const s = t.data[0];
                ve(!!s);
                // 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 = s, n = i.error || (null === (e = i[0]) || void 0 === e ? void 0 : e.error);
                if (n) {
                    ge("Connection", "WebChannel received error:", n);
                    // error.status will be a string like 'OK' or 'NOT_FOUND'.
                    const t = n.status;
                    let e = function(t) {
                        // lookup by string
                        // eslint-disable-next-line @typescript-eslint/no-explicit-any
                        const e = Ot[t];
                        if (void 0 !== e) return qt(e);
                    }(t), s = n.message;
                    void 0 === e && (e = w.INTERNAL, s = "Unknown error status: " + t + " with message " + n.message), 
                    // Mark closed so no further events are propagated
                    E = !0, I.jE(new R(e, s)), l.close();
                } else ge("Connection", "WebChannel received:", s), I.KE(s);
            }
        }), 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.
            I.WE();
        }, 0), I;
    }
    // visible for testing
    HE(t) {
        const e = pr[t];
        return this.GE + "/v1/projects/" + this.ii.projectId + "/databases/" + this.ii.database + "/documents:" + 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.
 */
// Implements the Platform API for browsers and some browser-like environments
// (including ReactNative).
/**
 * @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.
 */
/**
 * Registers the main Firestore build with the components framework.
 * Persistence can be enabled via `firebase.firestore().enablePersistence()`.
 */
function vr(t) {
    !
    /**
 * Configures Firestore as part of the Firebase SDK by calling registerService.
 *
 * @param firebase The FirebaseNamespace to register Firestore with
 * @param firestoreFactory A factory function that returns a new Firestore
 *    instance.
 */
    function(t, e) {
        t.INTERNAL.registerComponent(new c("firestore", t => {
            const s = t.getProvider("app").getImmediate();
            return e(s, t.getProvider("auth-internal"));
        }, "PUBLIC" /* PUBLIC */).setServiceProps(Object.assign({}, mr)));
    }(t, (t, e) => new Gn(t, e, new Bn)), t.registerVersion("@firebase/firestore", "1.14.6");
}

/**
 * @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.
 */
/**
 * This code needs to run before Firestore is used. This can be achieved in
 * several ways:
 *   1) Through the JSCompiler compiling this code and then (automatically)
 *      executing it before exporting the Firestore symbols.
 *   2) Through importing this module first in a Firestore main module
 */
Ae.an(new class {
    constructor() {
        this.ac = "undefined" != typeof atob;
    }
    get document() {
        // `document` is not always available, e.g. in ReactNative and WebWorkers.
        // eslint-disable-next-line no-restricted-globals
        return "undefined" != typeof document ? document : null;
    }
    get window() {
        // `window` is not always available, e.g. in ReactNative and WebWorkers.
        // eslint-disable-next-line no-restricted-globals
        return "undefined" != typeof window ? window : null;
    }
    yT(t) {
        return Promise.resolve(new br(t));
    }
    AT() {
        return Vr.Gh() ? new Vr : new Pr;
    }
    bc(t) {
        return new we(t, {
            hi: !0
        });
    }
    un(t) {
        return JSON.stringify(t);
    }
    atob(t) {
        return atob(t);
    }
    btoa(t) {
        return btoa(t);
    }
    _n(t) {
        // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
        const e = 
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        "undefined" != typeof self && (self.crypto || self.msCrypto), s = new Uint8Array(t);
        if (e) e.getRandomValues(s); else 
        // Falls back to Math.random
        for (let e = 0; e < t; e++) s[e] = Math.floor(256 * Math.random());
        return s;
    }
}), vr(t);

export { vr as __PRIVATE_registerFirestore };
//# sourceMappingURL=index.esm2017.js.map
