@firebase/firestore
Version:
The Cloud Firestore component of the Firebase JS SDK.
1,268 lines (1,215 loc) • 230 kB
JavaScript
import { __extends as t, __awaiter as e, __generator as n, __spreadArray as r } from "tslib";
import { _getProvider as i, getApp as o, _removeServiceInstance as a, SDK_VERSION as s, _registerComponent as u, registerVersion as c } from "@firebase/app";
import { Component as f } from "@firebase/component";
import { createMockUserToken as l, getModularInstance as h } from "@firebase/util";
import { Logger as d, LogLevel as p } from "@firebase/logger";
/**
* @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.
*/ var m = "8.6.7", y = /** @class */ function() {
function t(t) {
this.uid = t;
}
return t.prototype.isAuthenticated = function() {
return null != this.uid;
},
/**
* Returns a key representing this user, suitable for inclusion in a
* dictionary.
*/
t.prototype.toKey = function() {
return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user";
}, t.prototype.isEqual = function(t) {
return t.uid === this.uid;
}, 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.
*/
/**
* Simple wrapper around a nullable UID. Mostly exists to make code more
* readable.
*/
/** A user with a null UID. */ y.UNAUTHENTICATED = new y(null),
// TODO(mikelehen): Look into getting a proper uid-equivalent for
// non-FirebaseAuth providers.
y.GOOGLE_CREDENTIALS = new y("google-credentials-uid"), y.FIRST_PARTY = new y("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.
*/
var v = new d("@firebase/firestore");
/**
* Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
*
* @param logLevel - The verbosity you set for activity and error logging. Can
* be any of the following values:
*
* <ul>
* <li>`debug` for the most verbose logging level, primarily for
* debugging.</li>
* <li>`error` to log errors only.</li>
* <li><code>`silent` to turn off logging.</li>
* </ul>
*/ function g(t) {
v.setLogLevel(t);
}
function w(t) {
for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
if (v.logLevel <= p.DEBUG) {
var i = e.map(T);
v.debug.apply(v, r([ "Firestore (" + m + "): " + t ], i));
}
}
function b(t) {
for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
if (v.logLevel <= p.ERROR) {
var i = e.map(T);
v.error.apply(v, r([ "Firestore (" + m + "): " + t ], i));
}
}
function _(t) {
for (var e = [], n = 1; n < arguments.length; n++) e[n - 1] = arguments[n];
if (v.logLevel <= p.WARN) {
var i = e.map(T);
v.warn.apply(v, r([ "Firestore (" + m + "): " + t ], i));
}
}
/**
* Converts an additional log parameter to a string representation.
*/ function T(t) {
if ("string" == typeof t) return t;
try {
return e = t, JSON.stringify(e);
} catch (e) {
// Converting to JSON failed, just log the object directly
return t;
}
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** Formats an object as a JSON string, suitable for logging. */ var 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.
*/
/**
* 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 S(t) {
void 0 === t && (t = "Unexpected state");
// Log the failure in addition to throw an exception, just in case the
// exception is swallowed.
var e = "FIRESTORE (" + m + ") 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 b(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 E(t, e) {
t || S();
}
/**
* Casts `obj` to `T`. In non-production builds, verifies that `obj` is an
* instance of `T` before casting.
*/ function A(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.
*/ var I = "ok", V = "cancelled", P = "unknown", D = "invalid-argument", k = "deadline-exceeded", F = "not-found", N = "permission-denied", O = "unauthenticated", q = "resource-exhausted", L = "failed-precondition", R = "aborted", j = "out-of-range", C = "unimplemented", U = "internal", x = "unavailable", B = /** @class */ function(e) {
/** @hideconstructor */
function n(
/**
* The backend error code associated with this error.
*/
t,
/**
* A custom error description.
*/
n) {
var r = this;
return (r = e.call(this, n) || this).code = t, r.message = n,
/** The custom name for all FirestoreErrors. */
r.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.
r.toString = function() {
return r.name + ": [code=" + r.code + "]: " + r.message;
}, r;
}
return t(n, e), n;
}(Error), M = function() {
var t = this;
this.promise = new Promise((function(e, n) {
t.resolve = e, t.reject = n;
}));
}, G = function(t, e) {
this.user = e, this.type = "OAuth", this.authHeaders = {},
// Set the headers using Object Literal notation to avoid minification
this.authHeaders.Authorization = "Bearer " + t;
}, Q = /** @class */ function() {
function t() {
/**
* Stores the listener registered with setChangeListener()
* This isn't actually necessary since the UID never changes, but we use this
* to verify the listen contract is adhered to in tests.
*/
this.changeListener = null;
}
return t.prototype.getToken = function() {
return Promise.resolve(null);
}, t.prototype.invalidateToken = function() {}, t.prototype.setChangeListener = function(t, e) {
this.changeListener = e,
// Fire with initial user.
t.enqueueRetryable((function() {
return e(y.UNAUTHENTICATED);
}));
}, t.prototype.removeChangeListener = function() {
this.changeListener = null;
}, t;
}(), H = /** @class */ function() {
function t(t) {
this.token = t,
/**
* Stores the listener registered with setChangeListener()
* This isn't actually necessary since the UID never changes, but we use this
* to verify the listen contract is adhered to in tests.
*/
this.changeListener = null;
}
return t.prototype.getToken = function() {
return Promise.resolve(this.token);
}, t.prototype.invalidateToken = function() {}, t.prototype.setChangeListener = function(t, e) {
var n = this;
this.changeListener = e,
// Fire with initial user.
t.enqueueRetryable((function() {
return e(n.token.user);
}));
}, t.prototype.removeChangeListener = function() {
this.changeListener = null;
}, t;
}(), W = /** @class */ function() {
function t(t) {
var e = this;
/** Tracks the current User. */ this.currentUser = y.UNAUTHENTICATED,
/** Promise that allows blocking on the initialization of Firebase Auth. */
this.t = new M,
/**
* Counter used to detect if the token changed while a getToken request was
* outstanding.
*/
this.i = 0, this.forceRefresh = !1, this.auth = null, this.asyncQueue = null, this.o = function() {
e.i++, e.currentUser = e.u(), e.t.resolve(), e.changeListener && e.asyncQueue.enqueueRetryable((function() {
return e.changeListener(e.currentUser);
}));
};
var n = function(t) {
w("FirebaseCredentialsProvider", "Auth detected"), e.auth = t, e.auth.addAuthTokenListener(e.o);
};
t.onInit((function(t) {
return n(t);
})),
// Our users can initialize Auth right after Firestore, so we give it
// a chance to register itself with the component framework before we
// determine whether to start up in unauthenticated mode.
setTimeout((function() {
if (!e.auth) {
var r = t.getImmediate({
optional: !0
});
r ? n(r) : (
// If auth is still not available, proceed with `null` user
w("FirebaseCredentialsProvider", "Auth not yet detected"), e.t.resolve());
}
}), 0);
}
return t.prototype.getToken = function() {
var t = this, e = this.i, n = this.forceRefresh;
// 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.
return this.forceRefresh = !1, this.auth ? this.auth.getToken(n).then((function(n) {
// 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).
return t.i !== e ? (w("FirebaseCredentialsProvider", "getToken aborted due to token change."),
t.getToken()) : n ? (E("string" == typeof n.accessToken), new G(n.accessToken, t.currentUser)) : null;
})) : Promise.resolve(null);
}, t.prototype.invalidateToken = function() {
this.forceRefresh = !0;
}, t.prototype.setChangeListener = function(t, r) {
var i = this;
this.asyncQueue = t,
// Blocks the AsyncQueue until the next user is available.
this.asyncQueue.enqueueRetryable((function() {
return e(i, void 0, void 0, (function() {
return n(this, (function(t) {
switch (t.label) {
case 0:
return [ 4 /*yield*/ , this.t.promise ];
case 1:
return t.sent(), [ 4 /*yield*/ , r(this.currentUser) ];
case 2:
return t.sent(), this.changeListener = r, [ 2 /*return*/ ];
}
}));
}));
}));
}, t.prototype.removeChangeListener = function() {
this.auth && this.auth.removeAuthTokenListener(this.o), this.changeListener = function() {
return Promise.resolve();
};
},
// 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.
t.prototype.u = function() {
var t = this.auth && this.auth.getUid();
return E(null === t || "string" == typeof t), new y(t);
}, t;
}(), z = /** @class */ function() {
function t(t, e, n) {
this.h = t, this.l = e, this.m = n, this.type = "FirstParty", this.user = y.FIRST_PARTY;
}
return Object.defineProperty(t.prototype, "authHeaders", {
get: function() {
var t = {
"X-Goog-AuthUser": this.l
}, e = this.h.auth.getAuthHeaderValueForFirstParty([]);
// Use array notation to prevent minification
return e && (t.Authorization = e), this.m && (t["X-Goog-Iam-Authorization-Token"] = this.m),
t;
},
enumerable: !1,
configurable: !0
}), t;
}(), K = /** @class */ function() {
function t(t, e, n) {
this.h = t, this.l = e, this.m = n;
}
return t.prototype.getToken = function() {
return Promise.resolve(new z(this.h, this.l, this.m));
}, t.prototype.setChangeListener = function(t, e) {
// Fire with initial uid.
t.enqueueRetryable((function() {
return e(y.FIRST_PARTY);
}));
}, t.prototype.removeChangeListener = function() {}, t.prototype.invalidateToken = function() {},
t;
}(), Y =
/**
* Constructs a DatabaseInfo using the provided host, databaseId and
* persistenceKey.
*
* @param databaseId - The database to use.
* @param appId - The Firebase App Id.
* @param persistenceKey - A unique identifier for this Firestore's local
* storage (used in conjunction with the databaseId).
* @param host - The Firestore backend host to connect to.
* @param ssl - Whether to use SSL when connecting.
* @param forceLongPolling - Whether to use the forceLongPolling option
* when using WebChannel as the network transport.
* @param autoDetectLongPolling - Whether to use the detectBufferingProxy
* option when using WebChannel as the network transport.
* @param useFetchStreams Whether to use the Fetch API instead of
* XMLHTTPRequest
*/
function(t, e, n, r, i, o, a, s) {
this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = r, this.ssl = i,
this.forceLongPolling = o, this.autoDetectLongPolling = a, this.useFetchStreams = s;
}, X = /** @class */ function() {
function t(t, e) {
this.projectId = t, this.database = e || "(default)";
}
return Object.defineProperty(t.prototype, "isDefaultDatabase", {
get: function() {
return "(default)" === this.database;
},
enumerable: !1,
configurable: !0
}), t.prototype.isEqual = function(e) {
return e instanceof t && e.projectId === this.projectId && e.database === this.database;
}, t;
}(), J = /** @class */ function() {
function t(t, e, n) {
void 0 === e ? e = 0 : e > t.length && S(), void 0 === n ? n = t.length - e : n > t.length - e && S(),
this.segments = t, this.offset = e, this.len = n;
}
return Object.defineProperty(t.prototype, "length", {
get: function() {
return this.len;
},
enumerable: !1,
configurable: !0
}), t.prototype.isEqual = function(e) {
return 0 === t.comparator(this, e);
}, t.prototype.child = function(e) {
var n = this.segments.slice(this.offset, this.limit());
return e instanceof t ? e.forEach((function(t) {
n.push(t);
})) : n.push(e), this.construct(n);
},
/** The index of one past the last segment of the path. */ t.prototype.limit = function() {
return this.offset + this.length;
}, t.prototype.popFirst = function(t) {
return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);
}, t.prototype.popLast = function() {
return this.construct(this.segments, this.offset, this.length - 1);
}, t.prototype.firstSegment = function() {
return this.segments[this.offset];
}, t.prototype.lastSegment = function() {
return this.get(this.length - 1);
}, t.prototype.get = function(t) {
return this.segments[this.offset + t];
}, t.prototype.isEmpty = function() {
return 0 === this.length;
}, t.prototype.isPrefixOf = function(t) {
if (t.length < this.length) return !1;
for (var e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
return !0;
}, t.prototype.isImmediateParentOf = function(t) {
if (this.length + 1 !== t.length) return !1;
for (var e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;
return !0;
}, t.prototype.forEach = function(t) {
for (var e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);
}, t.prototype.toArray = function() {
return this.segments.slice(this.offset, this.limit());
}, t.comparator = function(t, e) {
for (var n = Math.min(t.length, e.length), r = 0; r < n; r++) {
var i = t.get(r), o = e.get(r);
if (i < o) return -1;
if (i > o) return 1;
}
return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;
}, t;
}(), Z = /** @class */ function(e) {
function n() {
return null !== e && e.apply(this, arguments) || this;
}
return t(n, e), n.prototype.construct = function(t, e, r) {
return new n(t, e, r);
}, n.prototype.canonicalString = function() {
// NOTE: The client is ignorant of any path segments containing escape
// sequences (e.g. __id123__) and just passes them through raw (they exist
// for legacy reasons and should not be used frequently).
return this.toArray().join("/");
}, n.prototype.toString = function() {
return this.canonicalString();
},
/**
* Creates a resource path from the given slash-delimited string. If multiple
* arguments are provided, all components are combined. Leading and trailing
* slashes from all components are ignored.
*/
n.fromString = function() {
for (var t = [], e = 0; e < arguments.length; e++) t[e] = arguments[e];
// NOTE: The client is ignorant of any path segments containing escape
// sequences (e.g. __id123__) and just passes them through raw (they exist
// for legacy reasons and should not be used frequently).
for (var r = [], i = 0, o = t; i < o.length; i++) {
var a = o[i];
if (a.indexOf("//") >= 0) throw new B(D, "Invalid segment (" + a + "). Paths must not contain // in them.");
// Strip leading and traling slashed.
r.push.apply(r, a.split("/").filter((function(t) {
return t.length > 0;
})));
}
return new n(r);
}, n.emptyPath = function() {
return new n([]);
}, n;
}(J), $ = /^[_a-zA-Z][_a-zA-Z0-9]*$/, tt = /** @class */ function(e) {
function n() {
return null !== e && e.apply(this, arguments) || this;
}
return t(n, e), n.prototype.construct = function(t, e, r) {
return new n(t, e, r);
},
/**
* Returns true if the string could be used as a segment in a field path
* without escaping.
*/
n.isValidIdentifier = function(t) {
return $.test(t);
}, n.prototype.canonicalString = function() {
return this.toArray().map((function(t) {
return t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), n.isValidIdentifier(t) || (t = "`" + t + "`"),
t;
})).join(".");
}, n.prototype.toString = function() {
return this.canonicalString();
},
/**
* Returns true if this field references the key of a document.
*/
n.prototype.isKeyField = function() {
return 1 === this.length && "__name__" === this.get(0);
},
/**
* The field designating the key of a document.
*/
n.keyField = function() {
return new n([ "__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.
*/
n.fromServerFormat = function(t) {
for (var e = [], r = "", i = 0, o = function() {
if (0 === r.length) throw new B(D, "Invalid field path (" + t + "). Paths must not be empty, begin with '.', end with '.', or contain '..'");
e.push(r), r = "";
}, a = !1; i < t.length; ) {
var s = t[i];
if ("\\" === s) {
if (i + 1 === t.length) throw new B(D, "Path has trailing escape character: " + t);
var u = t[i + 1];
if ("\\" !== u && "." !== u && "`" !== u) throw new B(D, "Path has invalid escape sequence: " + t);
r += u, i += 2;
} else "`" === s ? (a = !a, i++) : "." !== s || a ? (r += s, i++) : (o(), i++);
}
if (o(), a) throw new B(D, "Unterminated ` in path: " + t);
return new n(e);
}, n.emptyPath = function() {
return new n([]);
}, n;
}(J), et = /** @class */ function() {
function t(t) {
this.path = t;
}
return t.fromPath = function(e) {
return new t(Z.fromString(e));
}, t.fromName = function(e) {
return new t(Z.fromString(e).popFirst(5));
},
/** Returns true if the document is in the specified collectionId. */ t.prototype.hasCollectionId = function(t) {
return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;
}, t.prototype.isEqual = function(t) {
return null !== t && 0 === Z.comparator(this.path, t.path);
}, t.prototype.toString = function() {
return this.path.toString();
}, t.comparator = function(t, e) {
return Z.comparator(t.path, e.path);
}, t.isDocumentKey = function(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
* @returns A new instance of DocumentKey
*/
t.fromSegments = function(e) {
return new t(new Z(e.slice()));
}, t;
}();
/** An error returned by a Firestore operation. */
/**
* @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 nt(t, e, n) {
if (!n) throw new B(D, "Function " + t + "() cannot be called with an empty " + e + ".");
}
/**
* Validates that two boolean options are not set at the same time.
*/
/**
* Validates that `path` refers to a document (indicated by the fact it contains
* an even numbers of segments).
*/ function rt(t) {
if (!et.isDocumentKey(t)) throw new B(D, "Invalid document reference. Document references must have an even number of segments, but " + t + " has " + t.length + ".");
}
/**
* Validates that `path` refers to a collection (indicated by the fact it
* contains an odd numbers of segments).
*/ function it(t) {
if (et.isDocumentKey(t)) throw new B(D, "Invalid collection reference. Collection references must have an odd number of segments, but " + t + " has " + t.length + ".");
}
/**
* Returns true if it's a non-null object without a custom prototype
* (i.e. excludes Array, Date, etc.).
*/
/** Returns a string describing the type / value of the provided input. */ function ot(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";
var e =
/** Hacky method to try to get the constructor name for an object. */
function(t) {
if (t.constructor) {
var e = /function\s+([^\s(]+)\s*\(/.exec(t.constructor.toString());
if (e && e.length > 1) return e[1];
}
return null;
}(t);
return e ? "a custom " + e + " object" : "an object";
}
return "function" == typeof t ? "a function" : S();
}
function at(t,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
e) {
if ("_delegate" in t && (
// Unwrap Compat types
// eslint-disable-next-line @typescript-eslint/no-explicit-any
t = t._delegate), !(t instanceof e)) {
if (e.name === t.constructor.name) throw new B(D, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?");
var n = ot(t);
throw new B(D, "Expected type '" + e.name + "', but it was: " + n);
}
return t;
}
function st(t, e) {
if (e <= 0) throw new B(D, "Function " + t + "() requires a positive number, but it was: " + 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.
*/ function ut(t) {
return null == t;
}
/** Returns whether the value represents -0. */ function ct(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
*/
/**
* @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.
*/ var ft, lt, ht = {
BatchGetDocuments: "batchGet",
Commit: "commit",
RunQuery: "runQuery"
};
/**
* Maps RPC names to the corresponding REST endpoint name.
*
* We use array notation to avoid mangling.
*/
/**
* @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.
*/
/**
* Converts an HTTP Status Code to the equivalent error code.
*
* @param status - An HTTP Status Code, like 200, 404, 503, etc.
* @returns The equivalent Code. Unknown status codes are mapped to
* Code.UNKNOWN.
*/
function dt(t) {
if (void 0 === t) return b("RPC_ERROR", "HTTP error has no status"), P;
// The canonical error codes for Google APIs [1] specify mapping onto HTTP
// status codes but the mapping is not bijective. In each case of ambiguity
// this function chooses a primary error.
// [1]
// https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
switch (t) {
case 200:
// OK
return I;
case 400:
// Bad Request
return L;
// Other possibilities based on the forward mapping
// return Code.INVALID_ARGUMENT;
// return Code.OUT_OF_RANGE;
case 401:
// Unauthorized
return O;
case 403:
// Forbidden
return N;
case 404:
// Not Found
return F;
case 409:
// Conflict
return R;
// Other possibilities:
// return Code.ALREADY_EXISTS;
case 416:
// Range Not Satisfiable
return j;
case 429:
// Too Many Requests
return q;
case 499:
// Client Closed Request
return V;
case 500:
// Internal Server Error
return P;
// Other possibilities:
// return Code.INTERNAL;
// return Code.DATA_LOSS;
case 501:
// Unimplemented
return C;
case 503:
// Service Unavailable
return x;
case 504:
// Gateway Timeout
return k;
default:
return t >= 200 && t < 300 ? I : t >= 400 && t < 500 ? L : t >= 500 && t < 600 ? U : P;
}
}
/**
* @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 Rest-based connection that relies on the native HTTP stack
* (e.g. `fetch` or a polyfill).
*/ (lt = ft || (ft = {}))[lt.OK = 0] = "OK", lt[lt.CANCELLED = 1] = "CANCELLED",
lt[lt.UNKNOWN = 2] = "UNKNOWN", lt[lt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT",
lt[lt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", lt[lt.NOT_FOUND = 5] = "NOT_FOUND",
lt[lt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", lt[lt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED",
lt[lt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", lt[lt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED",
lt[lt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", lt[lt.ABORTED = 10] = "ABORTED",
lt[lt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", lt[lt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED",
lt[lt.INTERNAL = 13] = "INTERNAL", lt[lt.UNAVAILABLE = 14] = "UNAVAILABLE", lt[lt.DATA_LOSS = 15] = "DATA_LOSS";
var pt = /** @class */ function(r) {
/**
* @param databaseInfo - The connection info.
* @param fetchImpl - `fetch` or a Polyfill that implements the fetch API.
*/
function i(t, e) {
var n = this;
return (n = r.call(this, t) || this).R = e, n;
}
/**
* Base class for all Rest-based connections to the backend (WebChannel and
* HTTP).
*/
return t(i, r), i.prototype.V = function(t, e) {
throw new Error("Not supported by FetchConnection");
}, i.prototype.A = function(t, r, i, o) {
return e(this, void 0, void 0, (function() {
var t, e, a;
return n(this, (function(n) {
switch (n.label) {
case 0:
t = JSON.stringify(o), n.label = 1;
case 1:
return n.trys.push([ 1, 3, , 4 ]), [ 4 /*yield*/ , this.R(r, {
method: "POST",
headers: i,
body: t
}) ];
case 2:
return e = n.sent(), [ 3 /*break*/ , 4 ];
case 3:
throw a = n.sent(), new B(dt(a.status), "Request failed with error: " + a.statusText);
case 4:
if (!e.ok) throw new B(dt(e.status), "Request failed with error: " + e.statusText);
return [ 2 /*return*/ , e.json() ];
}
}));
}));
}, i;
}(/** @class */ function() {
function t(t) {
this.databaseInfo = t, this.databaseId = t.databaseId;
var e = t.ssl ? "https" : "http";
this.p = e + "://" + t.host, this.g = "projects/" + this.databaseId.projectId + "/databases/" + this.databaseId.database + "/documents";
}
return t.prototype.v = function(t, e, n, r) {
var i = this.T(t, e);
w("RestConnection", "Sending: ", i, n);
var o = {};
return this.I(o, r), this.A(t, i, o, n).then((function(t) {
return w("RestConnection", "Received: ", t), t;
}), (function(e) {
throw _("RestConnection", t + " failed with error: ", e, "url: ", i, "request:", n),
e;
}));
}, t.prototype.P = function(t, e, n, r) {
// The REST API automatically aggregates all of the streamed results, so we
// can just use the normal invoke() method.
return this.v(t, e, n, r);
},
/**
* Modifies the headers for a request, adding any authorization token if
* present and any additional headers for the request.
*/
t.prototype.I = function(t, e) {
if (t["X-Goog-Api-Client"] = "gl-js/ fire/" + m,
// 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.
t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId),
e) for (var n in e.authHeaders) e.authHeaders.hasOwnProperty(n) && (t[n] = e.authHeaders[n]);
}, t.prototype.T = function(t, e) {
var n = ht[t];
return this.p + "/v1/" + e + ":" + n;
}, t;
}());
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/** Initializes the HTTP connection for the REST API. */
/**
* @license
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Generates `nBytes` of random bytes.
*
* If `nBytes < 0` , an error will be thrown.
*/ function mt(t) {
// Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.
var e =
// eslint-disable-next-line @typescript-eslint/no-explicit-any
"undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);
if (e && "function" == typeof e.getRandomValues) e.getRandomValues(n); else
// Falls back to Math.random
for (var r = 0; r < t; r++) n[r] = Math.floor(256 * Math.random());
return n;
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ var yt = /** @class */ function() {
function t() {}
return t.N = function() {
for (
// Alphanumeric characters
var t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = Math.floor(256 / t.length) * t.length, n = ""
// The largest byte value that is a multiple of `char.length`.
; n.length < 20; ) for (var r = mt(40), i = 0; i < r.length; ++i)
// Only accept values that are [0, maxMultiple), this ensures they can
// be evenly mapped to indices of `chars` via a modulo operation.
n.length < 20 && r[i] < e && (n += t.charAt(r[i] % t.length));
return n;
}, t;
}();
function vt(t, e) {
return t < e ? -1 : t > e ? 1 : 0;
}
/** Helper to compare arrays using isEqual(). */ function gt(t, e, n) {
return t.length === e.length && t.every((function(t, r) {
return n(t, e[r]);
}));
}
/**
* @license
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).
/**
* A `Timestamp` represents a point in time independent of any time zone or
* calendar, represented as seconds and fractions of seconds at nanosecond
* resolution in UTC Epoch time.
*
* It is encoded using the Proleptic Gregorian Calendar which extends the
* Gregorian calendar backwards to year one. It is encoded assuming all minutes
* are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second
* table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59.999999999Z.
*
* For examples and further specifications, refer to the
* {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.
*/ var wt = /** @class */ function() {
/**
* Creates a new timestamp.
*
* @param seconds - The number of seconds of UTC time since Unix epoch
* 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to
* 9999-12-31T23:59:59Z inclusive.
* @param nanoseconds - The non-negative fractions of a second at nanosecond
* resolution. Negative second values with fractions must still have
* non-negative nanoseconds values that count forward in time. Must be
* from 0 to 999,999,999 inclusive.
*/
function t(
/**
* The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
*/
t,
/**
* The fractions of a second at nanosecond resolution.*
*/
e) {
if (this.seconds = t, this.nanoseconds = e, e < 0) throw new B(D, "Timestamp nanoseconds out of range: " + e);
if (e >= 1e9) throw new B(D, "Timestamp nanoseconds out of range: " + e);
if (t < -62135596800) throw new B(D, "Timestamp seconds out of range: " + t);
// This will break in the year 10,000.
if (t >= 253402300800) throw new B(D, "Timestamp seconds out of range: " + t);
}
/**
* Creates a new timestamp with the current date, with millisecond precision.
*
* @returns a new timestamp representing the current date.
*/ return t.now = function() {
return t.fromMillis(Date.now());
},
/**
* Creates a new timestamp from the given date.
*
* @param date - The date to initialize the `Timestamp` from.
* @returns A new `Timestamp` representing the same point in time as the given
* date.
*/
t.fromDate = function(e) {
return t.fromMillis(e.getTime());
},
/**
* Creates a new timestamp from the given number of milliseconds.
*
* @param milliseconds - Number of milliseconds since Unix epoch
* 1970-01-01T00:00:00Z.
* @returns A new `Timestamp` representing the same point in time as the given
* number of milliseconds.
*/
t.fromMillis = function(e) {
var n = Math.floor(e / 1e3);
return new t(n, Math.floor(1e6 * (e - 1e3 * n)));
},
/**
* Converts a `Timestamp` to a JavaScript `Date` object. This conversion
* causes a loss of precision since `Date` objects only support millisecond
* precision.
*
* @returns JavaScript `Date` object representing the same point in time as
* this `Timestamp`, with millisecond precision.
*/
t.prototype.toDate = function() {
return new Date(this.toMillis());
},
/**
* Converts a `Timestamp` to a numeric timestamp (in milliseconds since
* epoch). This operation causes a loss of precision.
*
* @returns The point in time corresponding to this timestamp, represented as
* the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
*/
t.prototype.toMillis = function() {
return 1e3 * this.seconds + this.nanoseconds / 1e6;
}, t.prototype._compareTo = function(t) {
return this.seconds === t.seconds ? vt(this.nanoseconds, t.nanoseconds) : vt(this.seconds, t.seconds);
},
/**
* Returns true if this `Timestamp` is equal to the provided one.
*
* @param other - The `Timestamp` to compare against.
* @returns true if this `Timestamp` is equal to the provided one.
*/
t.prototype.isEqual = function(t) {
return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;
},
/** Returns a textual representation of this Timestamp. */ t.prototype.toString = function() {
return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")";
},
/** Returns a JSON-serializable representation of this Timestamp. */ t.prototype.toJSON = function() {
return {
seconds: this.seconds,
nanoseconds: this.nanoseconds
};
},
/**
* Converts this object to a primitive string, which allows Timestamp objects
* to be compared using the `>`, `<=`, `>=` and `>` operators.
*/
t.prototype.valueOf = function() {
// 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.
var 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");
}, t;
}(), bt = /** @class */ function() {
function t(t) {
this.timestamp = t;
}
return t.fromTimestamp = function(e) {
return new t(e);
}, t.min = function() {
return new t(new wt(0, 0));
}, t.prototype.compareTo = function(t) {
return this.timestamp._compareTo(t.timestamp);
}, t.prototype.isEqual = function(t) {
return this.timestamp.isEqual(t.timestamp);
},
/** Returns a number representation of the version for use in spec tests. */ t.prototype.toMicroseconds = function() {
// Convert to microseconds.
return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;
}, t.prototype.toString = function() {
return "SnapshotVersion(" + this.timestamp.toString() + ")";
}, t.prototype.toTimestamp = function() {
return this.timestamp;
}, 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 version of a document in Firestore. This corresponds to the version
* timestamp, such as update_time or read_time.
*/
/**
* @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 governi