/**
* @license
* Copyright 2025 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This value is retrieved and hardcoded by the NPM postinstall script
const getDefaultsFromPostinstall = () => undefined;
/**
* @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 stringToByteArray$1 = function (str) {
// TODO(user): Use native implementations if/when available
const out = [];
let p = 0;
for (let i = 0; i < str.length; i++) {
let c = str.charCodeAt(i);
if (c < 128) {
out[p++] = c;
}
else if (c < 2048) {
out[p++] = (c >> 6) | 192;
out[p++] = (c & 63) | 128;
}
else if ((c & 0xfc00) === 0xd800 &&
i + 1 < str.length &&
(str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) {
// Surrogate Pair
c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);
out[p++] = (c >> 18) | 240;
out[p++] = ((c >> 12) & 63) | 128;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
}
else {
out[p++] = (c >> 12) | 224;
out[p++] = ((c >> 6) & 63) | 128;
out[p++] = (c & 63) | 128;
}
}
return out;
};
/**
* Turns an array of numbers into the string given by the concatenation of the
* characters to which the numbers correspond.
* @param bytes Array of numbers representing characters.
* @return Stringification of the array.
*/
const byteArrayToString = function (bytes) {
// TODO(user): Use native implementations if/when available
const out = [];
let pos = 0, c = 0;
while (pos < bytes.length) {
const c1 = bytes[pos++];
if (c1 < 128) {
out[c++] = String.fromCharCode(c1);
}
else if (c1 > 191 && c1 < 224) {
const c2 = bytes[pos++];
out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
}
else if (c1 > 239 && c1 < 365) {
// Surrogate Pair
const c2 = bytes[pos++];
const c3 = bytes[pos++];
const c4 = bytes[pos++];
const u = (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -
0x10000;
out[c++] = String.fromCharCode(0xd800 + (u >> 10));
out[c++] = String.fromCharCode(0xdc00 + (u & 1023));
}
else {
const c2 = bytes[pos++];
const c3 = bytes[pos++];
out[c++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
}
}
return out.join('');
};
// We define it as an object literal instead of a class because a class compiled down to es5 can't
// be treeshaked. https://github.com/rollup/rollup/issues/1691
// Static lookup maps, lazily populated by init_()
// TODO(dlarocque): Define this as a class, since we no longer target ES5.
const base64 = {
/**
* Maps bytes to characters.
*/
byteToCharMap_: null,
/**
* Maps characters to bytes.
*/
charToByteMap_: null,
/**
* Maps bytes to websafe characters.
* @private
*/
byteToCharMapWebSafe_: null,
/**
* Maps websafe characters to bytes.
* @private
*/
charToByteMapWebSafe_: null,
/**
* Our default alphabet, shared between
* ENCODED_VALS and ENCODED_VALS_WEBSAFE
*/
ENCODED_VALS_BASE: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',
/**
* Our default alphabet. Value 64 (=) is special; it means "nothing."
*/
get ENCODED_VALS() {
return this.ENCODED_VALS_BASE + '+/=';
},
/**
* Our websafe alphabet.
*/
get ENCODED_VALS_WEBSAFE() {
return this.ENCODED_VALS_BASE + '-_.';
},
/**
* Whether this browser supports the atob and btoa functions. This extension
* started at Mozilla but is now implemented by many browsers. We use the
* ASSUME_* variables to avoid pulling in the full useragent detection library
* but still allowing the standard per-browser compilations.
*
*/
HAS_NATIVE_SUPPORT: typeof atob === 'function',
/**
* Base64-encode an array of bytes.
*
* @param input An array of bytes (numbers with
* value in [0, 255]) to encode.
* @param webSafe Boolean indicating we should use the
* alternative alphabet.
* @return The base64 encoded string.
*/
encodeByteArray(input, webSafe) {
if (!Array.isArray(input)) {
throw Error('encodeByteArray takes an array as a parameter');
}
this.init_();
const byteToCharMap = webSafe
? this.byteToCharMapWebSafe_
: this.byteToCharMap_;
const output = [];
for (let i = 0; i < input.length; i += 3) {
const byte1 = input[i];
const haveByte2 = i + 1 < input.length;
const byte2 = haveByte2 ? input[i + 1] : 0;
const haveByte3 = i + 2 < input.length;
const byte3 = haveByte3 ? input[i + 2] : 0;
const outByte1 = byte1 >> 2;
const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);
let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);
let outByte4 = byte3 & 0x3f;
if (!haveByte3) {
outByte4 = 64;
if (!haveByte2) {
outByte3 = 64;
}
}
output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
}
return output.join(”);
},
/**
* Base64-encode a string.
*
* @param input A string to encode.
* @param webSafe If true, we should use the
* alternative alphabet.
* @return The base64 encoded string.
*/
encodeString(input, webSafe) {
// Shortcut for Mozilla browsers that implement
// a native base64 encoder in the form of “btoa/atob”
if (this.HAS_NATIVE_SUPPORT && !webSafe) {
return btoa(input);
}
return this.encodeByteArray(stringToByteArray$1(input), webSafe);
},
/**
* Base64-decode a string.
*
* @param input to decode.
* @param webSafe True if we should use the
* alternative alphabet.
* @return string representing the decoded value.
*/
decodeString(input, webSafe) {
// Shortcut for Mozilla browsers that implement
// a native base64 encoder in the form of “btoa/atob”
if (this.HAS_NATIVE_SUPPORT && !webSafe) {
return atob(input);
}
return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
},
/**
* Base64-decode a string.
*
* In base-64 decoding, groups of four characters are converted into three
* bytes. If the encoder did not apply padding, the input length may not
* be a multiple of 4.
*
* In this case, the last group will have fewer than 4 characters, and
* padding will be inferred. If the group has one or two characters, it decodes
* to one byte. If the group has three characters, it decodes to two bytes.
*
* @param input Input to decode.
* @param webSafe True if we should use the web-safe alphabet.
* @return bytes representing the decoded value.
*/
decodeStringToByteArray(input, webSafe) {
this.init_();
const charToByteMap = webSafe
? this.charToByteMapWebSafe_
: this.charToByteMap_;
const output = [];
for (let i = 0; i < input.length;) {
const byte1 = charToByteMap[input.charAt(i++)];
const haveByte2 = i < input.length;
const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;
++i;
const haveByte3 = i < input.length;
const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;
++i;
const haveByte4 = i < input.length;
const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;
++i;
if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
throw new DecodeBase64StringError();
}
const outByte1 = (byte1 << 2) | (byte2 >> 4);
output.push(outByte1);
if (byte3 !== 64) {
const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);
output.push(outByte2);
if (byte4 !== 64) {
const outByte3 = ((byte3 << 6) & 0xc0) | byte4;
output.push(outByte3);
}
}
}
return output;
},
/**
* Lazy static initialization function. Called before
* accessing any of the static map variables.
* @private
*/
init_() {
if (!this.byteToCharMap_) {
this.byteToCharMap_ = {};
this.charToByteMap_ = {};
this.byteToCharMapWebSafe_ = {};
this.charToByteMapWebSafe_ = {};
// We want quick mappings back and forth, so we precompute two maps.
for (let i = 0; i < this.ENCODED_VALS.length; i++) {
this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);
this.charToByteMap_[this.byteToCharMap_[i]] = i;
this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);
this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;
// Be forgiving when decoding and correctly decode both encodings.
if (i >= this.ENCODED_VALS_BASE.length) {
this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;
this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;
}
}
}
}
};
/**
* An error encountered while decoding base64 string.
*/
class DecodeBase64StringError extends Error {
constructor() {
super(…arguments);
this.name = ‘DecodeBase64StringError’;
}
}
/**
* URL-safe base64 encoding
*/
const base64Encode = function (str) {
const utf8Bytes = stringToByteArray$1(str);
return base64.encodeByteArray(utf8Bytes, true);
};
/**
* URL-safe base64 encoding (without “.” padding in the end).
* e.g. Used in JSON Web Token (JWT) parts.
*/
const base64urlEncodeWithoutPadding = function (str) {
// Use base64url encoding and remove padding in the end (dot characters).
return base64Encode(str).replace(/\./g, ”);
};
/**
* URL-safe base64 decoding
*
* NOTE: DO NOT use the global atob() function – it does NOT support the
* base64Url variant encoding.
*
* @param str To be decoded
* @return Decoded result, if possible
*/
const base64Decode = function (str) {
try {
return base64.decodeString(str, true);
}
catch (e) {
console.error(‘base64Decode failed: ‘, e);
}
return null;
};
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Polyfill for `globalThis` object.
* @returns the `globalThis` object for the given environment.
* @public
*/
function getGlobal() {
if (typeof self !== ‘undefined’) {
return self;
}
if (typeof window !== ‘undefined’) {
return window;
}
if (typeof global !== ‘undefined’) {
return global;
}
throw new Error(‘Unable to locate global object.’);
}
/**
* @license
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;
/**
* Attempt to read defaults from a JSON string provided to
* process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in
* process(.)env(.)__FIREBASE_DEFAULTS_PATH__
* The dots are in parens because certain compilers (Vite?) cannot
* handle seeing that variable in comments.
* See https://github.com/firebase/firebase-js-sdk/issues/6838
*/
const getDefaultsFromEnvVariable = () => {
if (typeof process === ‘undefined’ || typeof process.env === ‘undefined’) {
return;
}
const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;
if (defaultsJsonString) {
return JSON.parse(defaultsJsonString);
}
};
const getDefaultsFromCookie = () => {
if (typeof document === ‘undefined’) {
return;
}
let match;
try {
match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
}
catch (e) {
// Some environments such as Angular Universal SSR have a
// `document` object but error on accessing `document.cookie`.
return;
}
const decoded = match && base64Decode(match[1]);
return decoded && JSON.parse(decoded);
};
/**
* Get the __FIREBASE_DEFAULTS__ object. It checks in order:
* (1) if such an object exists as a property of `globalThis`
* (2) if such an object was provided on a shell environment variable
* (3) if such an object exists in a cookie
* @public
*/
const getDefaults = () => {
try {
return (getDefaultsFromPostinstall() ||
getDefaultsFromGlobal() ||
getDefaultsFromEnvVariable() ||
getDefaultsFromCookie());
}
catch (e) {
/**
* Catch-all for being unable to get __FIREBASE_DEFAULTS__ due
* to any environment case we have not accounted for. Log to
* info instead of swallowing so we can find these unknown cases
* and add paths for them if needed.
*/
console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);
return;
}
};
/**
* Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.
* @public
*/
const getDefaultAppConfig = () => { var _a; return (_a = getDefaults()) === null || _a === void 0 ? void 0 : _a.config; };
/**
* @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 Deferred {
constructor() {
this.reject = () => { };
this.resolve = () => { };
this.promise = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
}
/**
* Our API internals are not promisified and cannot because our callback APIs have subtle expectations around
* invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
* and returns a node-style callback which will resolve or reject the Deferred’s promise.
*/
wrapCallback(callback) {
return (error, value) => {
if (error) {
this.reject(error);
}
else {
this.resolve(value);
}
if (typeof callback === ‘function’) {
// Attaching noop handler just in case developer wasn’t expecting
// promises
this.promise.catch(() => { });
// Some of our callbacks don’t expect a value and our own tests
// assert that the parameter length is 1
if (callback.length === 1) {
callback(error);
}
else {
callback(error, value);
}
}
};
}
}
/**
* Detect Browser Environment.
* Note: This will return true for certain test frameworks that are incompletely
* mimicking a browser, and should not lead to assuming all browser APIs are
* available.
*/
function isBrowser() {
return typeof window !== ‘undefined’ || isWebWorker();
}
/**
* Detect Web Worker context.
*/
function isWebWorker() {
return (typeof WorkerGlobalScope !== ‘undefined’ &&
typeof self !== ‘undefined’ &&
self instanceof WorkerGlobalScope);
}
/**
* This method checks if indexedDB is supported by current browser/service worker context
* @return true if indexedDB is supported by current browser/service worker context
*/
function isIndexedDBAvailable() {
try {
return typeof indexedDB === ‘object’;
}
catch (e) {
return false;
}
}
/**
* This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject
* if errors occur during the database open operation.
*
* @throws exception if current browser/sw context can’t run idb.open (ex: Safari iframe, Firefox
* private browsing)
*/
function validateIndexedDBOpenable() {
return new Promise((resolve, reject) => {
try {
let preExist = true;
const DB_CHECK_NAME = ‘validate-browser-context-for-indexeddb-analytics-module’;
const request = self.indexedDB.open(DB_CHECK_NAME);
request.onsuccess = () => {
request.result.close();
// delete database only when it doesn’t pre-exist
if (!preExist) {
self.indexedDB.deleteDatabase(DB_CHECK_NAME);
}
resolve(true);
};
request.onupgradeneeded = () => {
preExist = false;
};
request.onerror = () => {
var _a;
reject(((_a = request.error) === null || _a === void 0 ? void 0 : _a.message) || ”);
};
}
catch (error) {
reject(error);
}
});
}
/**
* @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.
*/
/**
* @fileoverview Standardized Firebase Error.
*
* Usage:
*
* // TypeScript string literals for type-safe codes
* type Err =
* ‘unknown’ |
* ‘object-not-found’
* ;
*
* // Closure enum for type-safe error codes
* // at-enum {string}
* var Err = {
* UNKNOWN: ‘unknown’,
* OBJECT_NOT_FOUND: ‘object-not-found’,
* }
*
* let errors: Map = {
* ‘generic-error’: “Unknown error”,
* ‘file-not-found’: “Could not find file: {$file}”,
* };
*
* // Type-safe function – must pass a valid error code as param.
* let error = new ErrorFactory(‘service’, ‘Service’, errors);
*
* …
* throw error.create(Err.GENERIC);
* …
* throw error.create(Err.FILE_NOT_FOUND, {‘file’: fileName});
* …
* // Service: Could not file file: foo.txt (service/file-not-found).
*
* catch (e) {
* assert(e.message === “Could not find file: foo.txt.”);
* if ((e as FirebaseError)?.code === ‘service/file-not-found’) {
* console.log(“Could not read file: ” + e[‘file’]);
* }
* }
*/
const ERROR_NAME = ‘FirebaseError’;
// Based on code from:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types
class FirebaseError extends Error {
constructor(
/** The error code for this error. */
code, message,
/** Custom data for this error. */
customData) {
super(message);
this.code = code;
this.customData = customData;
/** The custom name for all FirebaseErrors. */
this.name = ERROR_NAME;
// Fix For ES5
// https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
// TODO(dlarocque): Replace this with `new.target`: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#support-for-newtarget
// which we can now use since we no longer target ES5.
Object.setPrototypeOf(this, FirebaseError.prototype);
// Maintains proper stack trace for where our error was thrown.
// Only available on V8.
if (Error.captureStackTrace) {
Error.captureStackTrace(this, ErrorFactory.prototype.create);
}
}
}
class ErrorFactory {
constructor(service, serviceName, errors) {
this.service = service;
this.serviceName = serviceName;
this.errors = errors;
}
create(code, …data) {
const customData = data[0] || {};
const fullCode = `${this.service}/${code}`;
const template = this.errors[code];
const message = template ? replaceTemplate(template, customData) : ‘Error’;
// Service Name: Error message (service/code).
const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
const error = new FirebaseError(fullCode, fullMessage, customData);
return error;
}
}
function replaceTemplate(template, data) {
return template.replace(PATTERN, (_, key) => {
const value = data[key];
return value != null ? String(value) : `<${key}?>`;
});
}
const PATTERN = /\{\$([^}]+)}/g;
/**
* Deep equal two objects. Support Arrays and Objects.
*/
function deepEqual(a, b) {
if (a === b) {
return true;
}
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
for (const k of aKeys) {
if (!bKeys.includes(k)) {
return false;
}
const aProp = a[k];
const bProp = b[k];
if (isObject(aProp) && isObject(bProp)) {
if (!deepEqual(aProp, bProp)) {
return false;
}
}
else if (aProp !== bProp) {
return false;
}
}
for (const k of bKeys) {
if (!aKeys.includes(k)) {
return false;
}
}
return true;
}
function isObject(thing) {
return thing !== null && typeof thing === ‘object’;
}
/**
* Component for service name T, e.g. `auth`, `auth-internal`
*/
class Component {
/**
*
* @param name The public service name, e.g. app, auth, firestore, database
* @param instanceFactory Service factory responsible for creating the public interface
* @param type whether the service provided by the component is public or private
*/
constructor(name, instanceFactory, type) {
this.name = name;
this.instanceFactory = instanceFactory;
this.type = type;
this.multipleInstances = false;
/**
* Properties to be added to the service namespace
*/
this.serviceProps = {};
this.instantiationMode = “LAZY” /* InstantiationMode.LAZY */;
this.onInstanceCreated = null;
}
setInstantiationMode(mode) {
this.instantiationMode = mode;
return this;
}
setMultipleInstances(multipleInstances) {
this.multipleInstances = multipleInstances;
return this;
}
setServiceProps(props) {
this.serviceProps = props;
return this;
}
setInstanceCreatedCallback(callback) {
this.onInstanceCreated = callback;
return this;
}
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DEFAULT_ENTRY_NAME$1 = ‘[DEFAULT]’;
/**
* @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.
*/
/**
* Provider for instance for service name T, e.g. ‘auth’, ‘auth-internal’
* NameServiceMapping[T] is an alias for the type of the instance
*/
class Provider {
constructor(name, container) {
this.name = name;
this.container = container;
this.component = null;
this.instances = new Map();
this.instancesDeferred = new Map();
this.instancesOptions = new Map();
this.onInitCallbacks = new Map();
}
/**
* @param identifier A provider can provide multiple instances of a service
* if this.component.multipleInstances is true.
*/
get(identifier) {
// if multipleInstances is not supported, use the default name
const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
if (!this.instancesDeferred.has(normalizedIdentifier)) {
const deferred = new Deferred();
this.instancesDeferred.set(normalizedIdentifier, deferred);
if (this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()) {
// initialize the service if it can be auto-initialized
try {
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
if (instance) {
deferred.resolve(instance);
}
}
catch (e) {
// when the instance factory throws an exception during get(), it should not cause
// a fatal error. We just return the unresolved promise in this case.
}
}
}
return this.instancesDeferred.get(normalizedIdentifier).promise;
}
getImmediate(options) {
var _a;
// if multipleInstances is not supported, use the default name
const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);
const optional = (_a = options === null || options === void 0 ? void 0 : options.optional) !== null && _a !== void 0 ? _a : false;
if (this.isInitialized(normalizedIdentifier) ||
this.shouldAutoInitialize()) {
try {
return this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
}
catch (e) {
if (optional) {
return null;
}
else {
throw e;
}
}
}
else {
// In case a component is not initialized and should/cannot be auto-initialized at the moment, return null if the optional flag is set, or throw
if (optional) {
return null;
}
else {
throw Error(`Service ${this.name} is not available`);
}
}
}
getComponent() {
return this.component;
}
setComponent(component) {
if (component.name !== this.name) {
throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);
}
if (this.component) {
throw Error(`Component for ${this.name} has already been provided`);
}
this.component = component;
// return early without attempting to initialize the component if the component requires explicit initialization (calling `Provider.initialize()`)
if (!this.shouldAutoInitialize()) {
return;
}
// if the service is eager, initialize the default instance
if (isComponentEager(component)) {
try {
this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME$1 });
}
catch (e) {
// when the instance factory for an eager Component throws an exception during the eager
// initialization, it should not cause a fatal error.
// TODO: Investigate if we need to make it configurable, because some component may want to cause
// a fatal error in this case?
}
}
// Create service instances for the pending promises and resolve them
// NOTE: if this.multipleInstances is false, only the default instance will be created
// and all promises with resolve with it regardless of the identifier.
for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
try {
// `getOrInitializeService()` should always return a valid instance since a component is guaranteed. use ! to make typescript happy.
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier
});
instanceDeferred.resolve(instance);
}
catch (e) {
// when the instance factory throws an exception, it should not cause
// a fatal error. We just leave the promise unresolved.
}
}
}
clearInstance(identifier = DEFAULT_ENTRY_NAME$1) {
this.instancesDeferred.delete(identifier);
this.instancesOptions.delete(identifier);
this.instances.delete(identifier);
}
// app.delete() will call this method on every provider to delete the services
// TODO: should we mark the provider as deleted?
async delete() {
const services = Array.from(this.instances.values());
await Promise.all([
…services
.filter(service => ‘INTERNAL’ in service) // legacy services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(service => service.INTERNAL.delete()),
…services
.filter(service => ‘_delete’ in service) // modularized services
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.map(service => service._delete())
]);
}
isComponentSet() {
return this.component != null;
}
isInitialized(identifier = DEFAULT_ENTRY_NAME$1) {
return this.instances.has(identifier);
}
getOptions(identifier = DEFAULT_ENTRY_NAME$1) {
return this.instancesOptions.get(identifier) || {};
}
initialize(opts = {}) {
const { options = {} } = opts;
const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);
if (this.isInitialized(normalizedIdentifier)) {
throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);
}
if (!this.isComponentSet()) {
throw Error(`Component ${this.name} has not been registered yet`);
}
const instance = this.getOrInitializeService({
instanceIdentifier: normalizedIdentifier,
options
});
// resolve any pending promise waiting for the service instance
for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
if (normalizedIdentifier === normalizedDeferredIdentifier) {
instanceDeferred.resolve(instance);
}
}
return instance;
}
/**
*
* @param callback – a function that will be invoked after the provider has been initialized by calling provider.initialize().
* The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
*
* @param identifier An optional instance identifier
* @returns a function to unregister the callback
*/
onInit(callback, identifier) {
var _a;
const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
const existingCallbacks = (_a = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a !== void 0 ? _a : new Set();
existingCallbacks.add(callback);
this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);
const existingInstance = this.instances.get(normalizedIdentifier);
if (existingInstance) {
callback(existingInstance, normalizedIdentifier);
}
return () => {
existingCallbacks.delete(callback);
};
}
/**
* Invoke onInit callbacks synchronously
* @param instance the service instance`
*/
invokeOnInitCallbacks(instance, identifier) {
const callbacks = this.onInitCallbacks.get(identifier);
if (!callbacks) {
return;
}
for (const callback of callbacks) {
try {
callback(instance, identifier);
}
catch (_a) {
// ignore errors in the onInit callback
}
}
}
getOrInitializeService({ instanceIdentifier, options = {} }) {
let instance = this.instances.get(instanceIdentifier);
if (!instance && this.component) {
instance = this.component.instanceFactory(this.container, {
instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
options
});
this.instances.set(instanceIdentifier, instance);
this.instancesOptions.set(instanceIdentifier, options);
/**
* Invoke onInit listeners.
* Note this.component.onInstanceCreated is different, which is used by the component creator,
* while onInit listeners are registered by consumers of the provider.
*/
this.invokeOnInitCallbacks(instance, instanceIdentifier);
/**
* Order is important
* onInstanceCreated() should be called after this.instances.set(instanceIdentifier, instance); which
* makes `isInitialized()` return true.
*/
if (this.component.onInstanceCreated) {
try {
this.component.onInstanceCreated(this.container, instanceIdentifier, instance);
}
catch (_a) {
// ignore errors in the onInstanceCreatedCallback
}
}
}
return instance || null;
}
normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME$1) {
if (this.component) {
return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME$1;
}
else {
return identifier; // assume multiple instances are supported before the component is provided.
}
}
shouldAutoInitialize() {
return (!!this.component &&
this.component.instantiationMode !== “EXPLICIT” /* InstantiationMode.EXPLICIT */);
}
}
// undefined should be passed to the service factory for the default instance
function normalizeIdentifierForFactory(identifier) {
return identifier === DEFAULT_ENTRY_NAME$1 ? undefined : identifier;
}
function isComponentEager(component) {
return component.instantiationMode === “EAGER” /* InstantiationMode.EAGER */;
}
/**
* @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.
*/
/**
* ComponentContainer that provides Providers for service name T, e.g. `auth`, `auth-internal`
*/
class ComponentContainer {
constructor(name) {
this.name = name;
this.providers = new Map();
}
/**
*
* @param component Component being added
* @param overwrite When a component with the same name has already been registered,
* if overwrite is true: overwrite the existing component with the new component and create a new
* provider with the new component. It can be useful in tests where you want to use different mocks
* for different tests.
* if overwrite is false: throw an exception
*/
addComponent(component) {
const provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
throw new Error(`Component ${component.name} has already been registered with ${this.name}`);
}
provider.setComponent(component);
}
addOrOverwriteComponent(component) {
const provider = this.getProvider(component.name);
if (provider.isComponentSet()) {
// delete the existing provider from the container, so we can register the new component
this.providers.delete(component.name);
}
this.addComponent(component);
}
/**
* getProvider provides a type safe interface where it can only be called with a field name
* present in NameServiceMapping interface.
*
* Firebase SDKs providing services should extend NameServiceMapping interface to register
* themselves.
*/
getProvider(name) {
if (this.providers.has(name)) {
return this.providers.get(name);
}
// create a Provider for a service that hasn’t registered with Firebase
const provider = new Provider(name, this);
this.providers.set(name, provider);
return provider;
}
getProviders() {
return Array.from(this.providers.values());
}
}
/**
* @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 container for all of the Logger instances
*/
const instances = [];
/**
* The JS SDK supports 5 log levels and also allows a user the ability to
* silence the logs altogether.
*
* The order is a follows:
* DEBUG < VERBOSE < INFO < WARN < ERROR
*
* All of the log types above the current log level will be captured (i.e. if
* you set the log level to `INFO`, errors will still be logged, but `DEBUG` and
* `VERBOSE` logs will not)
*/
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG";
LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE";
LogLevel[LogLevel["INFO"] = 2] = "INFO";
LogLevel[LogLevel["WARN"] = 3] = "WARN";
LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
LogLevel[LogLevel["SILENT"] = 5] = "SILENT";
})(LogLevel || (LogLevel = {}));
const levelStringToEnum = {
'debug': LogLevel.DEBUG,
'verbose': LogLevel.VERBOSE,
'info': LogLevel.INFO,
'warn': LogLevel.WARN,
'error': LogLevel.ERROR,
'silent': LogLevel.SILENT
};
/**
* The default log level
*/
const defaultLogLevel = LogLevel.INFO;
/**
* By default, `console.debug` is not displayed in the developer console (in
* chrome). To avoid forcing users to have to opt-in to these logs twice
* (i.e. once for firebase, and once in the console), we are sending `DEBUG`
* logs to the `console.log` function.
*/
const ConsoleMethod = {
[LogLevel.DEBUG]: 'log',
[LogLevel.VERBOSE]: 'log',
[LogLevel.INFO]: 'info',
[LogLevel.WARN]: 'warn',
[LogLevel.ERROR]: 'error'
};
/**
* The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR
* messages on to their corresponding console counterparts (if the log method
* is supported by the current log level)
*/
const defaultLogHandler = (instance, logType, ...args) => {
if (logType < instance.logLevel) {
return;
}
const now = new Date().toISOString();
const method = ConsoleMethod[logType];
if (method) {
console[method](`[${now}] ${instance.name}:`, ...args);
}
else {
throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);
}
};
class Logger {
/**
* Gives you an instance of a Logger to capture messages according to
* Firebase's logging scheme.
*
* @param name The name that the logs will be associated with
*/
constructor(name) {
this.name = name;
/**
* The log level of the given Logger instance.
*/
this._logLevel = defaultLogLevel;
/**
* The main (internal) log handler for the Logger instance.
* Can be set to a new function in internal package code but not by user.
*/
this._logHandler = defaultLogHandler;
/**
* The optional, additional, user-defined log handler for the Logger instance.
*/
this._userLogHandler = null;
/**
* Capture the current instance for later use
*/
instances.push(this);
}
get logLevel() {
return this._logLevel;
}
set logLevel(val) {
if (!(val in LogLevel)) {
throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``);
}
this._logLevel = val;
}
// Workaround for setter/getter having to be the same type.
setLogLevel(val) {
this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;
}
get logHandler() {
return this._logHandler;
}
set logHandler(val) {
if (typeof val !== 'function') {
throw new TypeError('Value assigned to `logHandler` must be a function');
}
this._logHandler = val;
}
get userLogHandler() {
return this._userLogHandler;
}
set userLogHandler(val) {
this._userLogHandler = val;
}
/**
* The functions below are all based on the `console` interface
*/
debug(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);
this._logHandler(this, LogLevel.DEBUG, ...args);
}
log(...args) {
this._userLogHandler &&
this._userLogHandler(this, LogLevel.VERBOSE, ...args);
this._logHandler(this, LogLevel.VERBOSE, ...args);
}
info(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);
this._logHandler(this, LogLevel.INFO, ...args);
}
warn(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);
this._logHandler(this, LogLevel.WARN, ...args);
}
error(...args) {
this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);
this._logHandler(this, LogLevel.ERROR, ...args);
}
}
function setLogLevel$1(level) {
instances.forEach(inst => {
inst.setLogLevel(level);
});
}
function setUserLogHandler(logCallback, options) {
for (const instance of instances) {
let customLogLevel = null;
if (options && options.level) {
customLogLevel = levelStringToEnum[options.level];
}
if (logCallback === null) {
instance.userLogHandler = null;
}
else {
instance.userLogHandler = (instance, level, …args) => {
const message = args
.map(arg => {
if (arg == null) {
return null;
}
else if (typeof arg === ‘string’) {
return arg;
}
else if (typeof arg === ‘number’ || typeof arg === ‘boolean’) {
return arg.toString();
}
else if (arg instanceof Error) {
return arg.message;
}
else {
try {
return JSON.stringify(arg);
}
catch (ignored) {
return null;
}
}
})
.filter(arg => arg)
.join(‘ ‘);
if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) {
logCallback({
level: LogLevel[level].toLowerCase(),
message,
args,
type: instance.name
});
}
};
}
}
}
const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c);
let idbProxyableTypes;
let cursorAdvanceMethods;
// This is a function to prevent it throwing up in node environments.
function getIdbProxyableTypes() {
return (idbProxyableTypes ||
(idbProxyableTypes = [
IDBDatabase,
IDBObjectStore,
IDBIndex,
IDBCursor,
IDBTransaction,
]));
}
// This is a function to prevent it throwing up in node environments.
function getCursorAdvanceMethods() {
return (cursorAdvanceMethods ||
(cursorAdvanceMethods = [
IDBCursor.prototype.advance,
IDBCursor.prototype.continue,
IDBCursor.prototype.continuePrimaryKey,
]));
}
const cursorRequestMap = new WeakMap();
const transactionDoneMap = new WeakMap();
const transactionStoreNamesMap = new WeakMap();
const transformCache = new WeakMap();
const reverseTransformCache = new WeakMap();
function promisifyRequest(request) {
const promise = new Promise((resolve, reject) => {
const unlisten = () => {
request.removeEventListener(‘success’, success);
request.removeEventListener(‘error’, error);
};
const success = () => {
resolve(wrap(request.result));
unlisten();
};
const error = () => {
reject(request.error);
unlisten();
};
request.addEventListener(‘success’, success);
request.addEventListener(‘error’, error);
});
promise
.then((value) => {
// Since cursoring reuses the IDBRequest (*sigh*), we cache it for later retrieval
// (see wrapFunction).
if (value instanceof IDBCursor) {
cursorRequestMap.set(value, request);
}
// Catching to avoid “Uncaught Promise exceptions”
})
.catch(() => { });
// This mapping exists in reverseTransformCache but doesn’t doesn’t exist in transformCache. This
// is because we create many promises from a single IDBRequest.
reverseTransformCache.set(promise, request);
return promise;
}
function cacheDonePromiseForTransaction(tx) {
// Early bail if we’ve already created a done promise for this transaction.
if (transactionDoneMap.has(tx))
return;
const done = new Promise((resolve, reject) => {
const unlisten = () => {
tx.removeEventListener(‘complete’, complete);
tx.removeEventListener(‘error’, error);
tx.removeEventListener(‘abort’, error);
};
const complete = () => {
resolve();
unlisten();
};
const error = () => {
reject(tx.error || new DOMException(‘AbortError’, ‘AbortError’));
unlisten();
};
tx.addEventListener(‘complete’, complete);
tx.addEventListener(‘error’, error);
tx.addEventListener(‘abort’, error);
});
// Cache it for later retrieval.
transactionDoneMap.set(tx, done);
}
let idbProxyTraps = {
get(target, prop, receiver) {
if (target instanceof IDBTransaction) {
// Special handling for transaction.done.
if (prop === ‘done’)
return transactionDoneMap.get(target);
// Polyfill for objectStoreNames because of Edge.
if (prop === ‘objectStoreNames’) {
return target.objectStoreNames || transactionStoreNamesMap.get(target);
}
// Make tx.store return the only store in the transaction, or undefined if there are many.
if (prop === ‘store’) {
return receiver.objectStoreNames[1]
? undefined
: receiver.objectStore(receiver.objectStoreNames[0]);
}
}
// Else transform whatever we get back.
return wrap(target[prop]);
},
set(target, prop, value) {
target[prop] = value;
return true;
},
has(target, prop) {
if (target instanceof IDBTransaction &&
(prop === ‘done’ || prop === ‘store’)) {
return true;
}
return prop in target;
},
};
function replaceTraps(callback) {
idbProxyTraps = callback(idbProxyTraps);
}
function wrapFunction(func) {
// Due to expected object equality (which is enforced by the caching in `wrap`), we
// only create one new func per func.
// Edge doesn’t support objectStoreNames (booo), so we polyfill it here.
if (func === IDBDatabase.prototype.transaction &&
!(‘objectStoreNames’ in IDBTransaction.prototype)) {
return function (storeNames, …args) {
const tx = func.call(unwrap(this), storeNames, …args);
transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
return wrap(tx);
};
}
// Cursor methods are special, as the behaviour is a little more different to standard IDB. In
// IDB, you advance the cursor and wait for a new ‘success’ on the IDBRequest that gave you the
// cursor. It’s kinda like a promise that can resolve with many values. That doesn’t make sense
// with real promises, so each advance methods returns a new promise for the cursor object, or
// undefined if the end of the cursor has been reached.
if (getCursorAdvanceMethods().includes(func)) {
return function (…args) {
// Calling the original function with the proxy as ‘this’ causes ILLEGAL INVOCATION, so we use
// the original object.
func.apply(unwrap(this), args);
return wrap(cursorRequestMap.get(this));
};
}
return function (…args) {
// Calling the original function with the proxy as ‘this’ causes ILLEGAL INVOCATION, so we use
// the original object.
return wrap(func.apply(unwrap(this), args));
};
}
function transformCachableValue(value) {
if (typeof value === ‘function’)
return wrapFunction(value);
// This doesn’t return, it just creates a ‘done’ promise for the transaction,
// which is later returned for transaction.done (see idbObjectHandler).
if (value instanceof IDBTransaction)
cacheDonePromiseForTransaction(value);
if (instanceOfAny(value, getIdbProxyableTypes()))
return new Proxy(value, idbProxyTraps);
// Return the same value back if we’re not going to transform it.
return value;
}
function wrap(value) {
// We sometimes generate multiple promises from a single IDBRequest (eg when cursoring), because
// IDB is weird and a single IDBRequest can yield many responses, so these can’t be cached.
if (value instanceof IDBRequest)
return promisifyRequest(value);
// If we’ve already transformed this value before, reuse the transformed value.
// This is faster, but it also provides object equality.
if (transformCache.has(value))
return transformCache.get(value);
const newValue = transformCachableValue(value);
// Not all types are transformed.
// These may be primitive types, so they can’t be WeakMap keys.
if (newValue !== value) {
transformCache.set(value, newValue);
reverseTransformCache.set(newValue, value);
}
return newValue;
}
const unwrap = (value) => reverseTransformCache.get(value);
/**
* Open a database.
*
* @param name Name of the database.
* @param version Schema version.
* @param callbacks Additional callbacks.
*/
function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) {
const request = indexedDB.open(name, version);
const openPromise = wrap(request);
if (upgrade) {
request.addEventListener(‘upgradeneeded’, (event) => {
upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
});
}
if (blocked) {
request.addEventListener(‘blocked’, (event) => blocked(
// Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
event.oldVersion, event.newVersion, event));
}
openPromise
.then((db) => {
if (terminated)
db.addEventListener(‘close’, () => terminated());
if (blocking) {
db.addEventListener(‘versionchange’, (event) => blocking(event.oldVersion, event.newVersion, event));
}
})
.catch(() => { });
return openPromise;
}
const readMethods = [‘get’, ‘getKey’, ‘getAll’, ‘getAllKeys’, ‘count’];
const writeMethods = [‘put’, ‘add’, ‘delete’, ‘clear’];
const cachedMethods = new Map();
function getMethod(target, prop) {
if (!(target instanceof IDBDatabase &&
!(prop in target) &&
typeof prop === ‘string’)) {
return;
}
if (cachedMethods.get(prop))
return cachedMethods.get(prop);
const targetFuncName = prop.replace(/FromIndex$/, ”);
const useIndex = prop !== targetFuncName;
const isWrite = writeMethods.includes(targetFuncName);
if (
// Bail if the target doesn’t exist on the target. Eg, getAll isn’t in Edge.
!(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) ||
!(isWrite || readMethods.includes(targetFuncName))) {
return;
}
const method = async function (storeName, …args) {
// isWrite ? ‘readwrite’ : undefined gzipps better, but fails in Edge 🙁
const tx = this.transaction(storeName, isWrite ? ‘readwrite’ : ‘readonly’);
let target = tx.store;
if (useIndex)
target = target.index(args.shift());
// Must reject if op rejects.
// If it’s a write operation, must reject if tx.done rejects.
// Must reject with op rejection first.
// Must resolve with op value.
// Must handle both promises (no unhandled rejections)
return (await Promise.all([
target[targetFuncName](…args),
isWrite && tx.done,
]))[0];
};
cachedMethods.set(prop, method);
return method;
}
replaceTraps((oldTraps) => (Object.assign(Object.assign({}, oldTraps), { get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop) })));
/**
* @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 PlatformLoggerServiceImpl {
constructor(container) {
this.container = container;
}
// In initial implementation, this will be called by installations on
// auth token refresh, and installations will send this string.
getPlatformInfoString() {
const providers = this.container.getProviders();
// Loop through providers and get library/version pairs from any that are
// version components.
return providers
.map(provider => {
if (isVersionServiceProvider(provider)) {
const service = provider.getImmediate();
return `${service.library}/${service.version}`;
}
else {
return null;
}
})
.filter(logString => logString)
.join(‘ ‘);
}
}
/**
*
* @param provider check if this provider provides a VersionService
*
* NOTE: Using Provider<'app-version'> is a hack to indicate that the provider
* provides VersionService. The provider is not necessarily a ‘app-version’
* provider.
*/
function isVersionServiceProvider(provider) {
const component = provider.getComponent();
return (component === null || component === void 0 ? void 0 : component.type) === “VERSION” /* ComponentType.VERSION */;
}
const name$q = “https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js”;
const version$1 = “0.11.5”;
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const logger = new Logger(‘https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js’);
const name$p = “@firebase/app-compat”;
const name$o = “@firebase/analytics-compat”;
const name$n = “@firebase/analytics”;
const name$m = “@firebase/app-check-compat”;
const name$l = “@firebase/app-check”;
const name$k = “@firebase/auth”;
const name$j = “@firebase/auth-compat”;
const name$i = “@firebase/database”;
const name$h = “@firebase/data-connect”;
const name$g = “@firebase/database-compat”;
const name$f = “@firebase/functions”;
const name$e = “@firebase/functions-compat”;
const name$d = “@firebase/installations”;
const name$c = “@firebase/installations-compat”;
const name$b = “@firebase/messaging”;
const name$a = “@firebase/messaging-compat”;
const name$9 = “@firebase/performance”;
const name$8 = “@firebase/performance-compat”;
const name$7 = “@firebase/remote-config”;
const name$6 = “@firebase/remote-config-compat”;
const name$5 = “@firebase/storage”;
const name$4 = “@firebase/storage-compat”;
const name$3 = “@firebase/firestore”;
const name$2 = “@firebase/vertexai”;
const name$1 = “@firebase/firestore-compat”;
const name$r = “firebase”;
const version$2 = “11.6.1”;
/**
* @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 default app name
*
* @internal
*/
const DEFAULT_ENTRY_NAME = ‘[DEFAULT]’;
const PLATFORM_LOG_STRING = {
[name$q]: ‘fire-core’,
[name$p]: ‘fire-core-compat’,
[name$n]: ‘fire-analytics’,
[name$o]: ‘fire-analytics-compat’,
[name$l]: ‘fire-app-check’,
[name$m]: ‘fire-app-check-compat’,
[name$k]: ‘fire-auth’,
[name$j]: ‘fire-auth-compat’,
[name$i]: ‘fire-rtdb’,
[name$h]: ‘fire-data-connect’,
[name$g]: ‘fire-rtdb-compat’,
[name$f]: ‘fire-fn’,
[name$e]: ‘fire-fn-compat’,
[name$d]: ‘fire-iid’,
[name$c]: ‘fire-iid-compat’,
[name$b]: ‘fire-fcm’,
[name$a]: ‘fire-fcm-compat’,
[name$9]: ‘fire-perf’,
[name$8]: ‘fire-perf-compat’,
[name$7]: ‘fire-rc’,
[name$6]: ‘fire-rc-compat’,
[name$5]: ‘fire-gcs’,
[name$4]: ‘fire-gcs-compat’,
[name$3]: ‘fire-fst’,
[name$1]: ‘fire-fst-compat’,
[name$2]: ‘fire-vertex’,
‘fire-js’: ‘fire-js’, // Platform identifier for JS SDK.
[name$r]: ‘fire-js-all’
};
/**
* @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.
*/
/**
* @internal
*/
const _apps = new Map();
/**
* @internal
*/
const _serverApps = new Map();
/**
* Registered components.
*
* @internal
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const _components = new Map();
/**
* @param component – the component being added to this app’s container
*
* @internal
*/
function _addComponent(app, component) {
try {
app.container.addComponent(component);
}
catch (e) {
logger.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e);
}
}
/**
*
* @internal
*/
function _addOrOverwriteComponent(app, component) {
app.container.addOrOverwriteComponent(component);
}
/**
*
* @param component – the component to register
* @returns whether or not the component is registered successfully
*
* @internal
*/
function _registerComponent(component) {
const componentName = component.name;
if (_components.has(componentName)) {
logger.debug(`There were multiple attempts to register component ${componentName}.`);
return false;
}
_components.set(componentName, component);
// add the component to existing app instances
for (const app of _apps.values()) {
_addComponent(app, component);
}
for (const serverApp of _serverApps.values()) {
_addComponent(serverApp, component);
}
return true;
}
/**
*
* @param app – FirebaseApp instance
* @param name – service name
*
* @returns the provider for the service with the matching name
*
* @internal
*/
function _getProvider(app, name) {
const heartbeatController = app.container
.getProvider(‘heartbeat’)
.getImmediate({ optional: true });
if (heartbeatController) {
void heartbeatController.triggerHeartbeat();
}
return app.container.getProvider(name);
}
/**
*
* @param app – FirebaseApp instance
* @param name – service name
* @param instanceIdentifier – service instance identifier in case the service supports multiple instances
*
* @internal
*/
function _removeServiceInstance(app, name, instanceIdentifier = DEFAULT_ENTRY_NAME) {
_getProvider(app, name).clearInstance(instanceIdentifier);
}
/**
*
* @param obj – an object of type FirebaseApp or FirebaseOptions.
*
* @returns true if the provide object is of type FirebaseApp.
*
* @internal
*/
function _isFirebaseApp(obj) {
return obj.options !== undefined;
}
/**
*
* @param obj – an object of type FirebaseApp.
*
* @returns true if the provided object is of type FirebaseServerAppImpl.
*
* @internal
*/
function _isFirebaseServerApp(obj) {
if (obj === null || obj === undefined) {
return false;
}
return obj.settings !== undefined;
}
/**
* Test only
*
* @internal
*/
function _clearComponents() {
_components.clear();
}
/**
* @license
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const ERRORS = {
[“no-app” /* AppError.NO_APP */]: “No Firebase App ‘{$appName}’ has been created – ” +
‘call initializeApp() first’,
[“bad-app-name” /* AppError.BAD_APP_NAME */]: “Illegal App name: ‘{$appName}'”,
[“duplicate-app” /* AppError.DUPLICATE_APP */]: “Firebase App named ‘{$appName}’ already exists with different options or config”,
[“app-deleted” /* AppError.APP_DELETED */]: “Firebase App named ‘{$appName}’ already deleted”,
[“server-app-deleted” /* AppError.SERVER_APP_DELETED */]: ‘Firebase Server App has been deleted’,
[“no-options” /* AppError.NO_OPTIONS */]: ‘Need to provide options, when not being deployed to hosting via source.’,
[“invalid-app-argument” /* AppError.INVALID_APP_ARGUMENT */]: ‘firebase.{$appName}() takes either no argument or a ‘ +
‘Firebase App instance.’,
[“invalid-log-argument” /* AppError.INVALID_LOG_ARGUMENT */]: ‘First argument to `onLog` must be null or a function.’,
[“idb-open” /* AppError.IDB_OPEN */]: ‘Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.’,
[“idb-get” /* AppError.IDB_GET */]: ‘Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.’,
[“idb-set” /* AppError.IDB_WRITE */]: ‘Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.’,
[“idb-delete” /* AppError.IDB_DELETE */]: ‘Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}.’,
[“finalization-registry-not-supported” /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */]: ‘FirebaseServerApp deleteOnDeref field defined but the JS runtime does not support FinalizationRegistry.’,
[“invalid-server-app-environment” /* AppError.INVALID_SERVER_APP_ENVIRONMENT */]: ‘FirebaseServerApp is not for use in browser environments.’
};
const ERROR_FACTORY = new ErrorFactory(‘app’, ‘Firebase’, ERRORS);
/**
* @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 FirebaseAppImpl {
constructor(options, config, container) {
this._isDeleted = false;
this._options = Object.assign({}, options);
this._config = Object.assign({}, config);
this._name = config.name;
this._automaticDataCollectionEnabled =
config.automaticDataCollectionEnabled;
this._container = container;
this.container.addComponent(new Component(‘app’, () => this, “PUBLIC” /* ComponentType.PUBLIC */));
}
get automaticDataCollectionEnabled() {
this.checkDestroyed();
return this._automaticDataCollectionEnabled;
}
set automaticDataCollectionEnabled(val) {
this.checkDestroyed();
this._automaticDataCollectionEnabled = val;
}
get name() {
this.checkDestroyed();
return this._name;
}
get options() {
this.checkDestroyed();
return this._options;
}
get config() {
this.checkDestroyed();
return this._config;
}
get container() {
return this._container;
}
get isDeleted() {
return this._isDeleted;
}
set isDeleted(val) {
this._isDeleted = val;
}
/**
* This function will throw an Error if the App has already been deleted –
* use before performing API actions on the App.
*/
checkDestroyed() {
if (this.isDeleted) {
throw ERROR_FACTORY.create(“app-deleted” /* AppError.APP_DELETED */, { appName: this._name });
}
}
}
/**
* @license
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Parse the token and check to see if the `exp` claim is in the future.
// Reports an error to the console if the token or claim could not be parsed, or if `exp` is in
// the past.
function validateTokenTTL(base64Token, tokenName) {
const secondPart = base64Decode(base64Token.split(‘.’)[1]);
if (secondPart === null) {
console.error(`FirebaseServerApp ${tokenName} is invalid: second part could not be parsed.`);
return;
}
const expClaim = JSON.parse(secondPart).exp;
if (expClaim === undefined) {
console.error(`FirebaseServerApp ${tokenName} is invalid: expiration claim could not be parsed`);
return;
}
const exp = JSON.parse(secondPart).exp * 1000;
const now = new Date().getTime();
const diff = exp – now;
if (diff <= 0) {
console.error(`FirebaseServerApp ${tokenName} is invalid: the token has expired.`);
}
}
class FirebaseServerAppImpl extends FirebaseAppImpl {
constructor(options, serverConfig, name, container) {
// Build configuration parameters for the FirebaseAppImpl base class.
const automaticDataCollectionEnabled = serverConfig.automaticDataCollectionEnabled !== undefined
? serverConfig.automaticDataCollectionEnabled
: false;
// Create the FirebaseAppSettings object for the FirebaseAppImp constructor.
const config = {
name,
automaticDataCollectionEnabled
};
if (options.apiKey !== undefined) {
// Construct the parent FirebaseAppImp object.
super(options, config, container);
}
else {
const appImpl = options;
super(appImpl.options, config, container);
}
// Now construct the data for the FirebaseServerAppImpl.
this._serverConfig = Object.assign({ automaticDataCollectionEnabled }, serverConfig);
// Ensure that the current time is within the `authIdtoken` window of validity.
if (this._serverConfig.authIdToken) {
validateTokenTTL(this._serverConfig.authIdToken, 'authIdToken');
}
// Ensure that the current time is within the `appCheckToken` window of validity.
if (this._serverConfig.appCheckToken) {
validateTokenTTL(this._serverConfig.appCheckToken, 'appCheckToken');
}
this._finalizationRegistry = null;
if (typeof FinalizationRegistry !== 'undefined') {
this._finalizationRegistry = new FinalizationRegistry(() => {
this.automaticCleanup();
});
}
this._refCount = 0;
this.incRefCount(this._serverConfig.releaseOnDeref);
// Do not retain a hard reference to the dref object, otherwise the FinalizationRegistry
// will never trigger.
this._serverConfig.releaseOnDeref = undefined;
serverConfig.releaseOnDeref = undefined;
registerVersion(name$q, version$1, ‘serverapp’);
}
toJSON() {
return undefined;
}
get refCount() {
return this._refCount;
}
// Increment the reference count of this server app. If an object is provided, register it
// with the finalization registry.
incRefCount(obj) {
if (this.isDeleted) {
return;
}
this._refCount++;
if (obj !== undefined && this._finalizationRegistry !== null) {
this._finalizationRegistry.register(obj, this);
}
}
// Decrement the reference count.
decRefCount() {
if (this.isDeleted) {
return 0;
}
return –this._refCount;
}
// Invoked by the FinalizationRegistry callback to note that this app should go through its
// reference counts and delete itself if no reference count remain. The coordinating logic that
// handles this is in deleteApp(…).
automaticCleanup() {
void deleteApp(this);
}
get settings() {
this.checkDestroyed();
return this._serverConfig;
}
/**
* This function will throw an Error if the App has already been deleted –
* use before performing API actions on the App.
*/
checkDestroyed() {
if (this.isDeleted) {
throw ERROR_FACTORY.create(“server-app-deleted” /* AppError.SERVER_APP_DELETED */);
}
}
}
/**
* @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 current SDK version.
*
* @public
*/
const SDK_VERSION = version$2;
function initializeApp(_options, rawConfig = {}) {
let options = _options;
if (typeof rawConfig !== ‘object’) {
const name = rawConfig;
rawConfig = { name };
}
const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);
const name = config.name;
if (typeof name !== ‘string’ || !name) {
throw ERROR_FACTORY.create(“bad-app-name” /* AppError.BAD_APP_NAME */, {
appName: String(name)
});
}
options || (options = getDefaultAppConfig());
if (!options) {
throw ERROR_FACTORY.create(“no-options” /* AppError.NO_OPTIONS */);
}
const existingApp = _apps.get(name);
if (existingApp) {
// return the existing app if options and config deep equal the ones in the existing app.
if (deepEqual(options, existingApp.options) &&
deepEqual(config, existingApp.config)) {
return existingApp;
}
else {
throw ERROR_FACTORY.create(“duplicate-app” /* AppError.DUPLICATE_APP */, { appName: name });
}
}
const container = new ComponentContainer(name);
for (const component of _components.values()) {
container.addComponent(component);
}
const newApp = new FirebaseAppImpl(options, config, container);
_apps.set(name, newApp);
return newApp;
}
function initializeServerApp(_options, _serverAppConfig) {
if (isBrowser() && !isWebWorker()) {
// FirebaseServerApp isn’t designed to be run in browsers.
throw ERROR_FACTORY.create(“invalid-server-app-environment” /* AppError.INVALID_SERVER_APP_ENVIRONMENT */);
}
if (_serverAppConfig.automaticDataCollectionEnabled === undefined) {
_serverAppConfig.automaticDataCollectionEnabled = false;
}
let appOptions;
if (_isFirebaseApp(_options)) {
appOptions = _options.options;
}
else {
appOptions = _options;
}
// Build an app name based on a hash of the configuration options.
const nameObj = Object.assign(Object.assign({}, _serverAppConfig), appOptions);
// However, Do not mangle the name based on releaseOnDeref, since it will vary between the
// construction of FirebaseServerApp instances. For example, if the object is the request headers.
if (nameObj.releaseOnDeref !== undefined) {
delete nameObj.releaseOnDeref;
}
const hashCode = (s) => {
return […s].reduce((hash, c) => (Math.imul(31, hash) + c.charCodeAt(0)) | 0, 0);
};
if (_serverAppConfig.releaseOnDeref !== undefined) {
if (typeof FinalizationRegistry === ‘undefined’) {
throw ERROR_FACTORY.create(“finalization-registry-not-supported” /* AppError.FINALIZATION_REGISTRY_NOT_SUPPORTED */, {});
}
}
const nameString = ” + hashCode(JSON.stringify(nameObj));
const existingApp = _serverApps.get(nameString);
if (existingApp) {
existingApp.incRefCount(_serverAppConfig.releaseOnDeref);
return existingApp;
}
const container = new ComponentContainer(nameString);
for (const component of _components.values()) {
container.addComponent(component);
}
const newApp = new FirebaseServerAppImpl(appOptions, _serverAppConfig, nameString, container);
_serverApps.set(nameString, newApp);
return newApp;
}
/**
* Retrieves a {@link @firebase/app#FirebaseApp} instance.
*
* When called with no arguments, the default app is returned. When an app name
* is provided, the app corresponding to that name is returned.
*
* An exception is thrown if the app being retrieved has not yet been
* initialized.
*
* @example
* “`javascript
* // Return the default app
* const app = getApp();
* “`
*
* @example
* “`javascript
* // Return a named app
* const otherApp = getApp(“otherApp”);
* “`
*
* @param name – Optional name of the app to return. If no name is
* provided, the default is `”[DEFAULT]”`.
*
* @returns The app corresponding to the provided app name.
* If no app name is provided, the default app is returned.
*
* @public
*/
function getApp(name = DEFAULT_ENTRY_NAME) {
const app = _apps.get(name);
if (!app && name === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
return initializeApp();
}
if (!app) {
throw ERROR_FACTORY.create(“no-app” /* AppError.NO_APP */, { appName: name });
}
return app;
}
/**
* A (read-only) array of all initialized apps.
* @public
*/
function getApps() {
return Array.from(_apps.values());
}
/**
* Renders this app unusable and frees the resources of all associated
* services.
*
* @example
* “`javascript
* deleteApp(app)
* .then(function() {
* console.log(“App deleted successfully”);
* })
* .catch(function(error) {
* console.log(“Error deleting app:”, error);
* });
* “`
*
* @public
*/
async function deleteApp(app) {
let cleanupProviders = false;
const name = app.name;
if (_apps.has(name)) {
cleanupProviders = true;
_apps.delete(name);
}
else if (_serverApps.has(name)) {
const firebaseServerApp = app;
if (firebaseServerApp.decRefCount() <= 0) {
_serverApps.delete(name);
cleanupProviders = true;
}
}
if (cleanupProviders) {
await Promise.all(app.container
.getProviders()
.map(provider => provider.delete()));
app.isDeleted = true;
}
}
/**
* Registers a library’s name and version for platform logging purposes.
* @param library – Name of 1p or 3p library (e.g. firestore, angularfire)
* @param version – Current version of that library.
* @param variant – Bundle variant, e.g., node, rn, etc.
*
* @public
*/
function registerVersion(libraryKeyOrName, version, variant) {
var _a;
// TODO: We can use this check to whitelist strings when/if we set up
// a good whitelist system.
let library = (_a = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a !== void 0 ? _a : libraryKeyOrName;
if (variant) {
library += `-${variant}`;
}
const libraryMismatch = library.match(/\s|\//);
const versionMismatch = version.match(/\s|\//);
if (libraryMismatch || versionMismatch) {
const warning = [
`Unable to register library “${library}” with version “${version}”:`
];
if (libraryMismatch) {
warning.push(`library name “${library}” contains illegal characters (whitespace or “/”)`);
}
if (libraryMismatch && versionMismatch) {
warning.push(‘and’);
}
if (versionMismatch) {
warning.push(`version name “${version}” contains illegal characters (whitespace or “/”)`);
}
logger.warn(warning.join(‘ ‘));
return;
}
_registerComponent(new Component(`${library}-version`, () => ({ library, version }), “VERSION” /* ComponentType.VERSION */));
}
/**
* Sets log handler for all Firebase SDKs.
* @param logCallback – An optional custom log handler that executes user code whenever
* the Firebase SDK makes a logging call.
*
* @public
*/
function onLog(logCallback, options) {
if (logCallback !== null && typeof logCallback !== ‘function’) {
throw ERROR_FACTORY.create(“invalid-log-argument” /* AppError.INVALID_LOG_ARGUMENT */);
}
setUserLogHandler(logCallback, options);
}
/**
* Sets log level for all Firebase SDKs.
*
* All of the log types above the current log level are captured (i.e. if
* you set the log level to `info`, errors are logged, but `debug` and
* `verbose` logs are not).
*
* @public
*/
function setLogLevel(logLevel) {
setLogLevel$1(logLevel);
}
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DB_NAME = ‘firebase-heartbeat-database’;
const DB_VERSION = 1;
const STORE_NAME = ‘firebase-heartbeat-store’;
let dbPromise = null;
function getDbPromise() {
if (!dbPromise) {
dbPromise = openDB(DB_NAME, DB_VERSION, {
upgrade: (db, oldVersion) => {
// We don’t use ‘break’ in this switch statement, the fall-through
// behavior is what we want, because if there are multiple versions between
// the old version and the current version, we want ALL the migrations
// that correspond to those versions to run, not only the last one.
// eslint-disable-next-line default-case
switch (oldVersion) {
case 0:
try {
db.createObjectStore(STORE_NAME);
}
catch (e) {
// Safari/iOS browsers throw occasional exceptions on
// db.createObjectStore() that may be a bug. Avoid blocking
// the rest of the app functionality.
console.warn(e);
}
}
}
}).catch(e => {
throw ERROR_FACTORY.create(“idb-open” /* AppError.IDB_OPEN */, {
originalErrorMessage: e.message
});
});
}
return dbPromise;
}
async function readHeartbeatsFromIndexedDB(app) {
try {
const db = await getDbPromise();
const tx = db.transaction(STORE_NAME);
const result = await tx.objectStore(STORE_NAME).get(computeKey(app));
// We already have the value but tx.done can throw,
// so we need to await it here to catch errors
await tx.done;
return result;
}
catch (e) {
if (e instanceof FirebaseError) {
logger.warn(e.message);
}
else {
const idbGetError = ERROR_FACTORY.create(“idb-get” /* AppError.IDB_GET */, {
originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
});
logger.warn(idbGetError.message);
}
}
}
async function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
try {
const db = await getDbPromise();
const tx = db.transaction(STORE_NAME, ‘readwrite’);
const objectStore = tx.objectStore(STORE_NAME);
await objectStore.put(heartbeatObject, computeKey(app));
await tx.done;
}
catch (e) {
if (e instanceof FirebaseError) {
logger.warn(e.message);
}
else {
const idbGetError = ERROR_FACTORY.create(“idb-set” /* AppError.IDB_WRITE */, {
originalErrorMessage: e === null || e === void 0 ? void 0 : e.message
});
logger.warn(idbGetError.message);
}
}
}
function computeKey(app) {
return `${app.name}!${app.options.appId}`;
}
/**
* @license
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the “License”);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an “AS IS” BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const MAX_HEADER_BYTES = 1024;
const MAX_NUM_STORED_HEARTBEATS = 30;
class HeartbeatServiceImpl {
constructor(container) {
this.container = container;
/**
* In-memory cache for heartbeats, used by getHeartbeatsHeader() to generate
* the header string.
* Stores one record per date. This will be consolidated into the standard
* format of one record per user agent string before being sent as a header.
* Populated from indexedDB when the controller is instantiated and should
* be kept in sync with indexedDB.
* Leave public for easier testing.
*/
this._heartbeatsCache = null;
const app = this.container.getProvider(‘app’).getImmediate();
this._storage = new HeartbeatStorageImpl(app);
this._heartbeatsCachePromise = this._storage.read().then(result => {
this._heartbeatsCache = result;
return result;
});
}
/**
* Called to report a heartbeat. The function will generate
* a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
* to IndexedDB.
* Note that we only store one heartbeat per day. So if a heartbeat for today is
* already logged, subsequent calls to this function in the same day will be ignored.
*/
async triggerHeartbeat() {
var _a, _b;
try {
const platformLogger = this.container
.getProvider(‘platform-logger’)
.getImmediate();
// This is the “Firebase user agent” string from the platform logger
// service, not the browser user agent.
const agent = platformLogger.getPlatformInfoString();
const date = getUTCDateString();
if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) {
this._heartbeatsCache = await this._heartbeatsCachePromise;
// If we failed to construct a heartbeats cache, then return immediately.
if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) {
return;
}
}
// Do not store a heartbeat if one is already stored for this day
// or if a header has already been sent today.
if (this._heartbeatsCache.lastSentHeartbeatDate === date ||
this._heartbeatsCache.heartbeats.some(singleDateHeartbeat => singleDateHeartbeat.date === date)) {
return;
}
else {
// There is no entry for this date. Create one.
this._heartbeatsCache.heartbeats.push({ date, agent });
// If the number of stored heartbeats exceeds the maximum number of stored heartbeats, remove the heartbeat with the earliest date.
// Since this is executed each time a heartbeat is pushed, the limit can only be exceeded by one, so only one needs to be removed.
if (this._heartbeatsCache.heartbeats.length > MAX_NUM_STORED_HEARTBEATS) {
const earliestHeartbeatIdx = getEarliestHeartbeatIdx(this._heartbeatsCache.heartbeats);
this._heartbeatsCache.heartbeats.splice(earliestHeartbeatIdx, 1);
}
}
return this._storage.overwrite(this._heartbeatsCache);
}
catch (e) {
logger.warn(e);
}
}
/**
* Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
* It also clears all heartbeats from memory as well as in IndexedDB.
*
* NOTE: Consuming product SDKs should not send the header if this method
* returns an empty string.
*/
async getHeartbeatsHeader() {
var _a;
try {
if (this._heartbeatsCache === null) {
await this._heartbeatsCachePromise;
}
// If it’s still null or the array is empty, there is no data to send.
if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null ||
this._heartbeatsCache.heartbeats.length === 0) {
return ”;
}
const date = getUTCDateString();
// Extract as many heartbeats from the cache as will fit under the size limit.
const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);
const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
// Store last sent date to prevent another being logged/sent for the same day.
this._heartbeatsCache.lastSentHeartbeatDate = date;
if (unsentEntries.length > 0) {
// Store any unsent entries if they exist.
this._heartbeatsCache.heartbeats = unsentEntries;
// This seems more likely than emptying the array (below) to lead to some odd state
// since the cache isn’t empty and this will be called again on the next request,
// and is probably safest if we await it.
await this._storage.overwrite(this._heartbeatsCache);
}
else {
this._heartbeatsCache.heartbeats = [];
// Do not wait for this, to reduce latency.
void this._storage.overwrite(this._heartbeatsCache);
}
return headerString;
}
catch (e) {
logger.warn(e);
return ”;
}
}
}
function getUTCDateString() {
const today = new Date();
// Returns date format ‘YYYY-MM-DD’
return today.toISOString().substring(0, 10);
}
function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {
// Heartbeats grouped by user agent in the standard format to be sent in
// the header.
const heartbeatsToSend = [];
// Single date format heartbeats that are not sent.
let unsentEntries = heartbeatsCache.slice();
for (const singleDateHeartbeat of heartbeatsCache) {
// Look for an existing entry with the same user agent.
const heartbeatEntry = heartbeatsToSend.find(hb => hb.agent === singleDateHeartbeat.agent);
if (!heartbeatEntry) {
// If no entry for this user agent exists, create one.
heartbeatsToSend.push({
agent: singleDateHeartbeat.agent,
dates: [singleDateHeartbeat.date]
});
if (countBytes(heartbeatsToSend) > maxSize) {
// If the header would exceed max size, remove the added heartbeat
// entry and stop adding to the header.
heartbeatsToSend.pop();
break;
}
}
else {
heartbeatEntry.dates.push(singleDateHeartbeat.date);
// If the header would exceed max size, remove the added date
// and stop adding to the header.
if (countBytes(heartbeatsToSend) > maxSize) {
heartbeatEntry.dates.pop();
break;
}
}
// Pop unsent entry from queue. (Skipped if adding the entry exceeded
// quota and the loop breaks early.)
unsentEntries = unsentEntries.slice(1);
}
return {
heartbeatsToSend,
unsentEntries
};
}
class HeartbeatStorageImpl {
constructor(app) {
this.app = app;
this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
}
async runIndexedDBEnvironmentCheck() {
if (!isIndexedDBAvailable()) {
return false;
}
else {
return validateIndexedDBOpenable()
.then(() => true)
.catch(() => false);
}
}
/**
* Read all heartbeats.
*/
async read() {
const canUseIndexedDB = await this._canUseIndexedDBPromise;
if (!canUseIndexedDB) {
return { heartbeats: [] };
}
else {
const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);
if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) {
return idbHeartbeatObject;
}
else {
return { heartbeats: [] };
}
}
}
// overwrite the storage with the provided heartbeats
async overwrite(heartbeatsObject) {
var _a;
const canUseIndexedDB = await this._canUseIndexedDBPromise;
if (!canUseIndexedDB) {
return;
}
else {
const existingHeartbeatsObject = await this.read();
return writeHeartbeatsToIndexedDB(this.app, {
lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
heartbeats: heartbeatsObject.heartbeats
});
}
}
// add heartbeats
async add(heartbeatsObject) {
var _a;
const canUseIndexedDB = await this._canUseIndexedDBPromise;
if (!canUseIndexedDB) {
return;
}
else {
const existingHeartbeatsObject = await this.read();
return writeHeartbeatsToIndexedDB(this.app, {
lastSentHeartbeatDate: (_a = heartbeatsObject.lastSentHeartbeatDate) !== null && _a !== void 0 ? _a : existingHeartbeatsObject.lastSentHeartbeatDate,
heartbeats: [
…existingHeartbeatsObject.heartbeats,
…heartbeatsObject.heartbeats
]
});
}
}
}
/**
* Calculate bytes of a HeartbeatsByUserAgent array after being wrapped
* in a platform logging header JSON object, stringified, and converted
* to base 64.
*/
function countBytes(heartbeatsCache) {
// base64 has a restricted set of characters, all of which should be 1 byte.
return base64urlEncodeWithoutPadding(
// heartbeatsCache wrapper properties
JSON.stringify({ version: 2, heartbeats: heartbeatsCache })).length;
}
/**
* Returns the index of the heartbeat with the earliest date.
* If the heartbeats array is empty, -1 is returned.
*/
function getEarliestHeartbeatIdx(heartbeats) {
if (heartbeats.length === 0) {
return -1;
}
let earliestHeartbeatIdx = 0;
let earliestHeartbeatDate = heartbeats[0].date;
for (let i = 1; i < heartbeats.length; i++) {
if (heartbeats[i].date < earliestHeartbeatDate) {
earliestHeartbeatDate = heartbeats[i].date;
earliestHeartbeatIdx = i;
}
}
return earliestHeartbeatIdx;
}
/**
* @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.
*/
function registerCoreComponents(variant) {
_registerComponent(new Component('platform-logger', container => new PlatformLoggerServiceImpl(container), “PRIVATE” /* ComponentType.PRIVATE */));
_registerComponent(new Component(‘heartbeat’, container => new HeartbeatServiceImpl(container), “PRIVATE” /* ComponentType.PRIVATE */));
// Register `app` package.
registerVersion(name$q, version$1, variant);
// BUILD_TARGET will be replaced by values like esm2017, cjs2017, etc during the compilation
registerVersion(name$q, version$1, ‘esm2017’);
// Register platform SDK identifier (no version).
registerVersion(‘fire-js’, ”);
}
/**
* Firebase App
*
* @remarks This package coordinates the communication between the different Firebase components
* @packageDocumentation
*/
registerCoreComponents(”);
var name = “firebase”;
var version = “11.6.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.
*/
registerVersion(name, version, ‘cdn’);
export { FirebaseError, SDK_VERSION, DEFAULT_ENTRY_NAME as _DEFAULT_ENTRY_NAME, _addComponent, _addOrOverwriteComponent, _apps, _clearComponents, _components, _getProvider, _isFirebaseApp, _isFirebaseServerApp, _registerComponent, _removeServiceInstance, _serverApps, deleteApp, getApp, getApps, initializeApp, initializeServerApp, onLog, registerVersion, setLogLevel };
//# sourceMappingURL=firebase-app.js.map
import{_getProvider,_isFirebaseServerApp as e,_registerComponent as t,registerVersion as r,getApp as n,SDK_VERSION as i}from”https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js”;const s={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″,get ENCODED_VALS(){return this.ENCODED_VALS_BASE+”+/=”},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+”-_.”},HAS_NATIVE_SUPPORT:”function”==typeof atob,encodeByteArray(e,t){if(!Array.isArray(e))throw Error(“encodeByteArray takes an array as a parameter”);this.init_();const r=t?this.byteToCharMapWebSafe_:this.byteToCharMap_,n=[];for(let t=0;t>2,d=(3&i)<<4|o>>4;let l=(15&o)<<2|c>>6,h=63&c;a||(h=64,s||(l=64)),n.push(r[u],r[d],r[l],r[h])}return n.join(“”)},encodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?btoa(e):this.encodeByteArray(function(e){const t=[];let r=0;for(let n=0;n>6|192,t[r++]=63&i|128):55296==(64512&i)&&n+1>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t}(e),t)},decodeString(e,t){return this.HAS_NATIVE_SUPPORT&&!t?atob(e):function(e){const t=[];let r=0,n=0;for(;r191&&i<224){const s=e[r++];t[n++]=String.fromCharCode((31&i)<<6|63&s)}else if(i>239&&i<365){const s=((7&i)<<18|(63&e[r++])<<12|(63&e[r++])<<6|63&e[r++])-65536;t[n++]=String.fromCharCode(55296+(s>>10)),t[n++]=String.fromCharCode(56320+(1023&s))}else{const s=e[r++],o=e[r++];t[n++]=String.fromCharCode((15&i)<<12|(63&s)<<6|63&o)}}return t.join("")}(this.decodeStringToByteArray(e,t))},decodeStringToByteArray(e,t){this.init_();const r=t?this.charToByteMapWebSafe_:this.charToByteMap_,n=[];for(let t=0;t>4;if(n.push(c),64!==o){const e=s<<4&240|o>>2;if(n.push(e),64!==a){const e=o<<6&192|a;n.push(e)}}}return n},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(…arguments),this.name=”DecodeBase64StringError”}}const base64Decode=function(e){try{return s.decodeString(e,!0)}catch(e){console.error(“base64Decode failed: “,e)}return null};const getDefaultsFromGlobal=()=>function getGlobal(){if(“undefined”!=typeof self)return self;if(“undefined”!=typeof window)return window;if(“undefined”!=typeof global)return global;throw new Error(“Unable to locate global object.”)}().__FIREBASE_DEFAULTS__,getDefaults=()=>{try{return getDefaultsFromGlobal()||(()=>{if(“undefined”==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||(()=>{if(“undefined”==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const t=e&&base64Decode(e[1]);return t&&JSON.parse(t)})()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getExperimentalSetting=e=>{var t;return null===(t=getDefaults())||void 0===t?void 0:t[`_${e}`]};function getUA(){return”undefined”!=typeof navigator&&”string”==typeof navigator.userAgent?navigator.userAgent:””}class FirebaseError extends Error{constructor(e,t,r){super(t),this.code=e,this.customData=r,this.name=”FirebaseError”,Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,t,r){this.service=e,this.serviceName=t,this.errors=r}create(e,…t){const r=t[0]||{},n=`${this.service}/${e}`,i=this.errors[e],s=i?function replaceTemplate(e,t){return e.replace(o,((e,r)=>{const n=t[r];return null!=n?String(n):`<${r}?>`}))}(i,r):”Error”,a=`${this.serviceName}: ${s} (${n}).`;return new FirebaseError(n,a,r)}}const o=/\{\$([^}]+)}/g;function deepEqual(e,t){if(e===t)return!0;const r=Object.keys(e),n=Object.keys(t);for(const i of r){if(!n.includes(i))return!1;const r=e[i],s=t[i];if(isObject(r)&&isObject(s)){if(!deepEqual(r,s))return!1}else if(r!==s)return!1}for(const e of n)if(!r.includes(e))return!1;return!0}function isObject(e){return null!==e&&”object”==typeof e}function querystring(e){const t=[];for(const[r,n]of Object.entries(e))Array.isArray(n)?n.forEach((e=>{t.push(encodeURIComponent(r)+”=”+encodeURIComponent(e))})):t.push(encodeURIComponent(r)+”=”+encodeURIComponent(n));return t.length?”&”+t.join(“&”):””}function querystringDecode(e){const t={};return e.replace(/^\?/,””).split(“&”).forEach((e=>{if(e){const[r,n]=e.split(“=”);t[decodeURIComponent(r)]=decodeURIComponent(n)}})),t}function extractQuerystring(e){const t=e.indexOf(“?”);if(!t)return””;const r=e.indexOf(“#”,t);return e.substring(t,r>0?r:void 0)}class ObserverProxy{constructor(e,t){this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=t,this.task.then((()=>{e(this)})).catch((e=>{this.error(e)}))}next(e){this.forEachObserver((t=>{t.next(e)}))}error(e){this.forEachObserver((t=>{t.error(e)})),this.close(e)}complete(){this.forEachObserver((e=>{e.complete()})),this.close()}subscribe(e,t,r){let n;if(void 0===e&&void 0===t&&void 0===r)throw new Error(“Missing Observer.”);n=function implementsAnyMethods(e,t){if(“object”!=typeof e||null===e)return!1;for(const r of t)if(r in e&&”function”==typeof e[r])return!0;return!1}(e,[“next”,”error”,”complete”])?e:{next:e,error:t,complete:r},void 0===n.next&&(n.next=noop),void 0===n.error&&(n.error=noop),void 0===n.complete&&(n.complete=noop);const i=this.unsubscribeOne.bind(this,this.observers.length);return this.finalized&&this.task.then((()=>{try{this.finalError?n.error(this.finalError):n.complete()}catch(e){}})),this.observers.push(n),i}unsubscribeOne(e){void 0!==this.observers&&void 0!==this.observers[e]&&(delete this.observers[e],this.observerCount-=1,0===this.observerCount&&void 0!==this.onNoObservers&&this.onNoObservers(this))}forEachObserver(e){if(!this.finalized)for(let t=0;t{if(void 0!==this.observers&&void 0!==this.observers[e])try{t(this.observers[e])}catch(e){“undefined”!=typeof console&&console.error&&console.error(e)}}))}close(e){this.finalized||(this.finalized=!0,void 0!==e&&(this.finalError=e),this.task.then((()=>{this.observers=void 0,this.onNoObservers=void 0})))}}function noop(){}function getModularInstance(e){return e&&e._delegate?e._delegate:e}var a;!function(e){e[e.DEBUG=0]=”DEBUG”,e[e.VERBOSE=1]=”VERBOSE”,e[e.INFO=2]=”INFO”,e[e.WARN=3]=”WARN”,e[e.ERROR=4]=”ERROR”,e[e.SILENT=5]=”SILENT”}(a||(a={}));const c={debug:a.DEBUG,verbose:a.VERBOSE,info:a.INFO,warn:a.WARN,error:a.ERROR,silent:a.SILENT},u=a.INFO,d={[a.DEBUG]:”log”,[a.VERBOSE]:”log”,[a.INFO]:”info”,[a.WARN]:”warn”,[a.ERROR]:”error”},defaultLogHandler=(e,t,…r)=>{if(te,”Short delay should be less than long delay!”),this.isMobile=function isMobileCordova(){return”undefined”!=typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())}()||function isReactNative(){return”object”==typeof navigator&&”ReactNative”===navigator.product}()}get(){return _isOnline()?this.isMobile?this.longDelay:this.shortDelay:Math.min(5e3,this.shortDelay)}}function _emulatorUrl(e,t){debugAssert(e.emulator,”Emulator should always be set here”);const{url:r}=e.emulator;return t?`${r}${t.startsWith(“/”)?t.slice(1):t}`:r}class FetchProvider{static initialize(e,t,r){this.fetchImpl=e,t&&(this.headersImpl=t),r&&(this.responseImpl=r)}static fetch(){return this.fetchImpl?this.fetchImpl:”undefined”!=typeof self&&”fetch”in self?self.fetch:”undefined”!=typeof globalThis&&globalThis.fetch?globalThis.fetch:”undefined”!=typeof fetch?fetch:void debugFail(“Could not find fetch implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill”)}static headers(){return this.headersImpl?this.headersImpl:”undefined”!=typeof self&&”Headers”in self?self.Headers:”undefined”!=typeof globalThis&&globalThis.Headers?globalThis.Headers:”undefined”!=typeof Headers?Headers:void debugFail(“Could not find Headers implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill”)}static response(){return this.responseImpl?this.responseImpl:”undefined”!=typeof self&&”Response”in self?self.Response:”undefined”!=typeof globalThis&&globalThis.Response?globalThis.Response:”undefined”!=typeof Response?Response:void debugFail(“Could not find Response implementation, make sure you call FetchProvider.initialize() with an appropriate polyfill”)}}const T={CREDENTIAL_MISMATCH:”custom-token-mismatch”,MISSING_CUSTOM_TOKEN:”internal-error”,INVALID_IDENTIFIER:”invalid-email”,MISSING_CONTINUE_URI:”internal-error”,INVALID_PASSWORD:”wrong-password”,MISSING_PASSWORD:”missing-password”,INVALID_LOGIN_CREDENTIALS:”invalid-credential”,EMAIL_EXISTS:”email-already-in-use”,PASSWORD_LOGIN_DISABLED:”operation-not-allowed”,INVALID_IDP_RESPONSE:”invalid-credential”,INVALID_PENDING_TOKEN:”invalid-credential”,FEDERATED_USER_ID_ALREADY_LINKED:”credential-already-in-use”,MISSING_REQ_TYPE:”internal-error”,EMAIL_NOT_FOUND:”user-not-found”,RESET_PASSWORD_EXCEED_LIMIT:”too-many-requests”,EXPIRED_OOB_CODE:”expired-action-code”,INVALID_OOB_CODE:”invalid-action-code”,MISSING_OOB_CODE:”internal-error”,CREDENTIAL_TOO_OLD_LOGIN_AGAIN:”requires-recent-login”,INVALID_ID_TOKEN:”invalid-user-token”,TOKEN_EXPIRED:”user-token-expired”,USER_NOT_FOUND:”user-token-expired”,TOO_MANY_ATTEMPTS_TRY_LATER:”too-many-requests”,PASSWORD_DOES_NOT_MEET_REQUIREMENTS:”password-does-not-meet-requirements”,INVALID_CODE:”invalid-verification-code”,INVALID_SESSION_INFO:”invalid-verification-id”,INVALID_TEMPORARY_PROOF:”invalid-credential”,MISSING_SESSION_INFO:”missing-verification-id”,SESSION_EXPIRED:”code-expired”,MISSING_ANDROID_PACKAGE_NAME:”missing-android-pkg-name”,UNAUTHORIZED_DOMAIN:”unauthorized-continue-uri”,INVALID_OAUTH_CLIENT_ID:”invalid-oauth-client-id”,ADMIN_ONLY_OPERATION:”admin-restricted-operation”,INVALID_MFA_PENDING_CREDENTIAL:”invalid-multi-factor-session”,MFA_ENROLLMENT_NOT_FOUND:”multi-factor-info-not-found”,MISSING_MFA_ENROLLMENT_ID:”missing-multi-factor-info”,MISSING_MFA_PENDING_CREDENTIAL:”missing-multi-factor-session”,SECOND_FACTOR_EXISTS:”second-factor-already-in-use”,SECOND_FACTOR_LIMIT_EXCEEDED:”maximum-second-factor-count-exceeded”,BLOCKING_FUNCTION_ERROR_RESPONSE:”internal-error”,RECAPTCHA_NOT_ENABLED:”recaptcha-not-enabled”,MISSING_RECAPTCHA_TOKEN:”missing-recaptcha-token”,INVALID_RECAPTCHA_TOKEN:”invalid-recaptcha-token”,INVALID_RECAPTCHA_ACTION:”invalid-recaptcha-action”,MISSING_CLIENT_TYPE:”missing-client-type”,MISSING_RECAPTCHA_VERSION:”missing-recaptcha-version”,INVALID_RECAPTCHA_VERSION:”invalid-recaptcha-version”,INVALID_REQ_TYPE:”invalid-req-type”},A=[“/v1/accounts:signInWithCustomToken”,”/v1/accounts:signInWithEmailLink”,”/v1/accounts:signInWithIdp”,”/v1/accounts:signInWithPassword”,”/v1/accounts:signInWithPhoneNumber”,”/v1/token”],y=new Delay(3e4,6e4);function _addTidIfNecessary(e,t){return e.tenantId&&!t.tenantId?Object.assign(Object.assign({},t),{tenantId:e.tenantId}):t}async function _performApiRequest(e,t,r,n,i={}){return _performFetchWithErrorHandling(e,i,(async()=>{let i={},s={};n&&(“GET”===t?s=n:i={body:JSON.stringify(n)});const o=querystring(Object.assign({key:e.config.apiKey},s)).slice(1),a=await e._getAdditionalHeaders();a[“Content-Type”]=”application/json”,e.languageCode&&(a[“X-Firebase-Locale”]=e.languageCode);const c=Object.assign({method:t,headers:a},i);return function isCloudflareWorker(){return”undefined”!=typeof navigator&&”Cloudflare-Workers”===navigator.userAgent}()||(c.referrerPolicy=”no-referrer”),FetchProvider.fetch()(await _getFinalTarget(e,e.config.apiHost,r,o),c)}))}async function _performFetchWithErrorHandling(e,t,r){e._canInitEmulator=!1;const n=Object.assign(Object.assign({},T),t);try{const t=new NetworkTimeout(e),i=await Promise.race([r(),t.promise]);t.clearNetworkTimeout();const s=await i.json();if(“needConfirmation”in s)throw _makeTaggedError(e,”account-exists-with-different-credential”,s);if(i.ok&&!(“errorMessage”in s))return s;{const t=i.ok?s.errorMessage:s.error.message,[r,o]=t.split(” : “);if(“FEDERATED_USER_ID_ALREADY_LINKED”===r)throw _makeTaggedError(e,”credential-already-in-use”,s);if(“EMAIL_EXISTS”===r)throw _makeTaggedError(e,”email-already-in-use”,s);if(“USER_DISABLED”===r)throw _makeTaggedError(e,”user-disabled”,s);const a=n[r]||r.toLowerCase().replace(/[_\s]+/g,”-“);if(o)throw _errorWithCustomMessage(e,a,o);_fail(e,a)}}catch(t){if(t instanceof FirebaseError)throw t;_fail(e,”network-request-failed”,{message:String(t)})}}async function _performSignInRequest(e,t,r,n,i={}){const s=await _performApiRequest(e,t,r,n,i);return”mfaPendingCredential”in s&&_fail(e,”multi-factor-auth-required”,{_serverResponse:s}),s}async function _getFinalTarget(e,t,r,n){const i=`${t}${r}?${n}`,s=e,o=s.config.emulator?_emulatorUrl(e.config,i):`${e.config.apiScheme}://${i}`;if(A.includes(r)&&(await s._persistenceManagerAvailable,”COOKIE”===s._getPersistenceType())){return s._getPersistence()._getFinalTarget(o).toString()}return o}function _parseEnforcementState(e){switch(e){case”ENFORCE”:return”ENFORCE”;case”AUDIT”:return”AUDIT”;case”OFF”:return”OFF”;default:return”ENFORCEMENT_STATE_UNSPECIFIED”}}class NetworkTimeout{clearNetworkTimeout(){clearTimeout(this.timer)}constructor(e){this.auth=e,this.timer=null,this.promise=new Promise(((e,t)=>{this.timer=setTimeout((()=>t(_createError(this.auth,”network-request-failed”))),y.get())}))}}function _makeTaggedError(e,t,r){const n={appName:e.name};r.email&&(n.email=r.email),r.phoneNumber&&(n.phoneNumber=r.phoneNumber);const i=_createError(e,t,n);return i.customData._tokenResponse=r,i}function isV2(e){return void 0!==e&&void 0!==e.getResponse}function isEnterprise(e){return void 0!==e&&void 0!==e.enterprise}class RecaptchaConfig{constructor(e){if(this.siteKey=””,this.recaptchaEnforcementState=[],void 0===e.recaptchaKey)throw new Error(“recaptchaKey undefined”);this.siteKey=e.recaptchaKey.split(“/”)[3],this.recaptchaEnforcementState=e.recaptchaEnforcementState}getProviderEnforcementState(e){if(!this.recaptchaEnforcementState||0===this.recaptchaEnforcementState.length)return null;for(const t of this.recaptchaEnforcementState)if(t.provider&&t.provider===e)return _parseEnforcementState(t.enforcementState);return null}isProviderEnabled(e){return”ENFORCE”===this.getProviderEnforcementState(e)||”AUDIT”===this.getProviderEnforcementState(e)}isAnyProviderEnabled(){return this.isProviderEnabled(“EMAIL_PASSWORD_PROVIDER”)||this.isProviderEnabled(“PHONE_PROVIDER”)}}async function getRecaptchaConfig(e,t){return _performApiRequest(e,”GET”,”/v2/recaptchaConfig”,_addTidIfNecessary(e,t))}async function getAccountInfo(e,t){return _performApiRequest(e,”POST”,”/v1/accounts:lookup”,t)}function utcTimestampToDateString(e){if(e)try{const t=new Date(Number(e));if(!isNaN(t.getTime()))return t.toUTCString()}catch(e){}}function getIdToken(e,t=!1){return getModularInstance(e).getIdToken(t)}async function getIdTokenResult(e,t=!1){const r=getModularInstance(e),n=await r.getIdToken(t),i=_parseToken(n);_assert(i&&i.exp&&i.auth_time&&i.iat,r.auth,”internal-error”);const s=”object”==typeof i.firebase?i.firebase:void 0,o=null==s?void 0:s.sign_in_provider;return{claims:i,token:n,authTime:utcTimestampToDateString(secondsStringToMilliseconds(i.auth_time)),issuedAtTime:utcTimestampToDateString(secondsStringToMilliseconds(i.iat)),expirationTime:utcTimestampToDateString(secondsStringToMilliseconds(i.exp)),signInProvider:o||null,signInSecondFactor:(null==s?void 0:s.sign_in_second_factor)||null}}function secondsStringToMilliseconds(e){return 1e3*Number(e)}function _parseToken(e){const[t,r,n]=e.split(“.”);if(void 0===t||void 0===r||void 0===n)return _logError(“JWT malformed, contained fewer than 3 sections”),null;try{const e=base64Decode(r);return e?JSON.parse(e):(_logError(“Failed to decode base64 JWT payload”),null)}catch(e){return _logError(“Caught error parsing JWT payload as JSON”,null==e?void 0:e.toString()),null}}function _tokenExpiresIn(e){const t=_parseToken(e);return _assert(t,”internal-error”),_assert(void 0!==t.exp,”internal-error”),_assert(void 0!==t.iat,”internal-error”),Number(t.exp)-Number(t.iat)}async function _logoutIfInvalidated(e,t,r=!1){if(r)return t;try{return await t}catch(t){throw t instanceof FirebaseError&&function isUserInvalidated({code:e}){return”auth/user-disabled”===e||”auth/user-token-expired”===e}(t)&&e.auth.currentUser===e&&await e.auth.signOut(),t}}class ProactiveRefresh{constructor(e){this.user=e,this.isRunning=!1,this.timerId=null,this.errorBackoff=3e4}_start(){this.isRunning||(this.isRunning=!0,this.schedule())}_stop(){this.isRunning&&(this.isRunning=!1,null!==this.timerId&&clearTimeout(this.timerId))}getInterval(e){var t;if(e){const e=this.errorBackoff;return this.errorBackoff=Math.min(2*this.errorBackoff,96e4),e}{this.errorBackoff=3e4;const e=(null!==(t=this.user.stsTokenManager.expirationTime)&&void 0!==t?t:0)-Date.now()-3e5;return Math.max(0,e)}}schedule(e=!1){if(!this.isRunning)return;const t=this.getInterval(e);this.timerId=setTimeout((async()=>{await this.iteration()}),t)}async iteration(){try{await this.user.getIdToken(!0)}catch(e){return void(“auth/network-request-failed”===(null==e?void 0:e.code)&&this.schedule(!0))}this.schedule()}}class UserMetadata{constructor(e,t){this.createdAt=e,this.lastLoginAt=t,this._initializeTime()}_initializeTime(){this.lastSignInTime=utcTimestampToDateString(this.lastLoginAt),this.creationTime=utcTimestampToDateString(this.createdAt)}_copy(e){this.createdAt=e.createdAt,this.lastLoginAt=e.lastLoginAt,this._initializeTime()}toJSON(){return{createdAt:this.createdAt,lastLoginAt:this.lastLoginAt}}}async function _reloadWithoutSaving(e){var t;const r=e.auth,n=await e.getIdToken(),i=await _logoutIfInvalidated(e,getAccountInfo(r,{idToken:n}));_assert(null==i?void 0:i.users.length,r,”internal-error”);const s=i.users[0];e._notifyReloadListener(s);const o=(null===(t=s.providerUserInfo)||void 0===t?void 0:t.length)?extractProviderData(s.providerUserInfo):[],a=function mergeProviderData(e,t){return[…e.filter((e=>!t.some((t=>t.providerId===e.providerId)))),…t]}(e.providerData,o),c=e.isAnonymous,u=!(e.email&&s.passwordHash||(null==a?void 0:a.length)),d=!!c&&u,l={uid:s.localId,displayName:s.displayName||null,photoURL:s.photoUrl||null,email:s.email||null,emailVerified:s.emailVerified||!1,phoneNumber:s.phoneNumber||null,tenantId:s.tenantId||null,providerData:a,metadata:new UserMetadata(s.createdAt,s.lastLoginAt),isAnonymous:d};Object.assign(e,l)}async function reload(e){const t=getModularInstance(e);await _reloadWithoutSaving(t),await t.auth._persistUserIfCurrent(t),t.auth._notifyListenersIfCurrent(t)}function extractProviderData(e){return e.map((e=>{var{providerId:t}=e,r=__rest(e,[“providerId”]);return{providerId:t,uid:r.rawId||””,displayName:r.displayName||null,email:r.email||null,phoneNumber:r.phoneNumber||null,photoURL:r.photoUrl||null}}))}class StsTokenManager{constructor(){this.refreshToken=null,this.accessToken=null,this.expirationTime=null}get isExpired(){return!this.expirationTime||Date.now()>this.expirationTime-3e4}updateFromServerResponse(e){_assert(e.idToken,”internal-error”),_assert(void 0!==e.idToken,”internal-error”),_assert(void 0!==e.refreshToken,”internal-error”);const t=”expiresIn”in e&&void 0!==e.expiresIn?Number(e.expiresIn):_tokenExpiresIn(e.idToken);this.updateTokensAndExpiration(e.idToken,e.refreshToken,t)}updateFromIdToken(e){_assert(0!==e.length,”internal-error”);const t=_tokenExpiresIn(e);this.updateTokensAndExpiration(e,null,t)}async getToken(e,t=!1){return t||!this.accessToken||this.isExpired?(_assert(this.refreshToken,e,”user-token-expired”),this.refreshToken?(await this.refresh(e,this.refreshToken),this.accessToken):null):this.accessToken}clearRefreshToken(){this.refreshToken=null}async refresh(e,t){const{accessToken:r,refreshToken:n,expiresIn:i}=await async function requestStsToken(e,t){const r=await _performFetchWithErrorHandling(e,{},(async()=>{const r=querystring({grant_type:”refresh_token”,refresh_token:t}).slice(1),{tokenApiHost:n,apiKey:i}=e.config,s=await _getFinalTarget(e,n,”/v1/token”,`key=${i}`),o=await e._getAdditionalHeaders();return o[“Content-Type”]=”application/x-www-form-urlencoded”,FetchProvider.fetch()(s,{method:”POST”,headers:o,body:r})}));return{accessToken:r.access_token,expiresIn:r.expires_in,refreshToken:r.refresh_token}}(e,t);this.updateTokensAndExpiration(r,n,Number(i))}updateTokensAndExpiration(e,t,r){this.refreshToken=t||null,this.accessToken=e||null,this.expirationTime=Date.now()+1e3*r}static fromJSON(e,t){const{refreshToken:r,accessToken:n,expirationTime:i}=t,s=new StsTokenManager;return r&&(_assert(“string”==typeof r,”internal-error”,{appName:e}),s.refreshToken=r),n&&(_assert(“string”==typeof n,”internal-error”,{appName:e}),s.accessToken=n),i&&(_assert(“number”==typeof i,”internal-error”,{appName:e}),s.expirationTime=i),s}toJSON(){return{refreshToken:this.refreshToken,accessToken:this.accessToken,expirationTime:this.expirationTime}}_assign(e){this.accessToken=e.accessToken,this.refreshToken=e.refreshToken,this.expirationTime=e.expirationTime}_clone(){return Object.assign(new StsTokenManager,this.toJSON())}_performRefresh(){return debugFail(“not implemented”)}}function assertStringOrUndefined(e,t){_assert(“string”==typeof e||void 0===e,”internal-error”,{appName:t})}class UserImpl{constructor(e){var{uid:t,auth:r,stsTokenManager:n}=e,i=__rest(e,[“uid”,”auth”,”stsTokenManager”]);this.providerId=”firebase”,this.proactiveRefresh=new ProactiveRefresh(this),this.reloadUserInfo=null,this.reloadListener=null,this.uid=t,this.auth=r,this.stsTokenManager=n,this.accessToken=n.accessToken,this.displayName=i.displayName||null,this.email=i.email||null,this.emailVerified=i.emailVerified||!1,this.phoneNumber=i.phoneNumber||null,this.photoURL=i.photoURL||null,this.isAnonymous=i.isAnonymous||!1,this.tenantId=i.tenantId||null,this.providerData=i.providerData?[…i.providerData]:[],this.metadata=new UserMetadata(i.createdAt||void 0,i.lastLoginAt||void 0)}async getIdToken(e){const t=await _logoutIfInvalidated(this,this.stsTokenManager.getToken(this.auth,e));return _assert(t,this.auth,”internal-error”),this.accessToken!==t&&(this.accessToken=t,await this.auth._persistUserIfCurrent(this),this.auth._notifyListenersIfCurrent(this)),t}getIdTokenResult(e){return getIdTokenResult(this,e)}reload(){return reload(this)}_assign(e){this!==e&&(_assert(this.uid===e.uid,this.auth,”internal-error”),this.displayName=e.displayName,this.photoURL=e.photoURL,this.email=e.email,this.emailVerified=e.emailVerified,this.phoneNumber=e.phoneNumber,this.isAnonymous=e.isAnonymous,this.tenantId=e.tenantId,this.providerData=e.providerData.map((e=>Object.assign({},e))),this.metadata._copy(e.metadata),this.stsTokenManager._assign(e.stsTokenManager))}_clone(e){const t=new UserImpl(Object.assign(Object.assign({},this),{auth:e,stsTokenManager:this.stsTokenManager._clone()}));return t.metadata._copy(this.metadata),t}_onReload(e){_assert(!this.reloadListener,this.auth,”internal-error”),this.reloadListener=e,this.reloadUserInfo&&(this._notifyReloadListener(this.reloadUserInfo),this.reloadUserInfo=null)}_notifyReloadListener(e){this.reloadListener?this.reloadListener(e):this.reloadUserInfo=e}_startProactiveRefresh(){this.proactiveRefresh._start()}_stopProactiveRefresh(){this.proactiveRefresh._stop()}async _updateTokensIfNecessary(e,t=!1){let r=!1;e.idToken&&e.idToken!==this.stsTokenManager.accessToken&&(this.stsTokenManager.updateFromServerResponse(e),r=!0),t&&await _reloadWithoutSaving(this),await this.auth._persistUserIfCurrent(this),r&&this.auth._notifyListenersIfCurrent(this)}async delete(){if(e(this.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this.auth));const t=await this.getIdToken();return await _logoutIfInvalidated(this,async function deleteAccount(e,t){return _performApiRequest(e,”POST”,”/v1/accounts:delete”,t)}(this.auth,{idToken:t})),this.stsTokenManager.clearRefreshToken(),this.auth.signOut()}toJSON(){return Object.assign(Object.assign({uid:this.uid,email:this.email||void 0,emailVerified:this.emailVerified,displayName:this.displayName||void 0,isAnonymous:this.isAnonymous,photoURL:this.photoURL||void 0,phoneNumber:this.phoneNumber||void 0,tenantId:this.tenantId||void 0,providerData:this.providerData.map((e=>Object.assign({},e))),stsTokenManager:this.stsTokenManager.toJSON(),_redirectEventId:this._redirectEventId},this.metadata.toJSON()),{apiKey:this.auth.config.apiKey,appName:this.auth.name})}get refreshToken(){return this.stsTokenManager.refreshToken||””}static _fromJSON(e,t){var r,n,i,s,o,a,c,u;const d=null!==(r=t.displayName)&&void 0!==r?r:void 0,l=null!==(n=t.email)&&void 0!==n?n:void 0,h=null!==(i=t.phoneNumber)&&void 0!==i?i:void 0,p=null!==(s=t.photoURL)&&void 0!==s?s:void 0,f=null!==(o=t.tenantId)&&void 0!==o?o:void 0,m=null!==(a=t._redirectEventId)&&void 0!==a?a:void 0,g=null!==(c=t.createdAt)&&void 0!==c?c:void 0,_=null!==(u=t.lastLoginAt)&&void 0!==u?u:void 0,{uid:I,emailVerified:v,isAnonymous:E,providerData:T,stsTokenManager:A}=t;_assert(I&&A,e,”internal-error”);const y=StsTokenManager.fromJSON(this.name,A);_assert(“string”==typeof I,e,”internal-error”),assertStringOrUndefined(d,e.name),assertStringOrUndefined(l,e.name),_assert(“boolean”==typeof v,e,”internal-error”),_assert(“boolean”==typeof E,e,”internal-error”),assertStringOrUndefined(h,e.name),assertStringOrUndefined(p,e.name),assertStringOrUndefined(f,e.name),assertStringOrUndefined(m,e.name),assertStringOrUndefined(g,e.name),assertStringOrUndefined(_,e.name);const w=new UserImpl({uid:I,auth:e,email:l,emailVerified:v,displayName:d,isAnonymous:E,photoURL:p,phoneNumber:h,tenantId:f,stsTokenManager:y,createdAt:g,lastLoginAt:_});return T&&Array.isArray(T)&&(w.providerData=T.map((e=>Object.assign({},e)))),m&&(w._redirectEventId=m),w}static async _fromIdTokenResponse(e,t,r=!1){const n=new StsTokenManager;n.updateFromServerResponse(t);const i=new UserImpl({uid:t.localId,auth:e,stsTokenManager:n,isAnonymous:r});return await _reloadWithoutSaving(i),i}static async _fromGetAccountInfoResponse(e,t,r){const n=t.users[0];_assert(void 0!==n.localId,”internal-error”);const i=void 0!==n.providerUserInfo?extractProviderData(n.providerUserInfo):[],s=!(n.email&&n.passwordHash||(null==i?void 0:i.length)),o=new StsTokenManager;o.updateFromIdToken(r);const a=new UserImpl({uid:n.localId,auth:e,stsTokenManager:o,isAnonymous:s}),c={uid:n.localId,displayName:n.displayName||null,photoURL:n.photoUrl||null,email:n.email||null,emailVerified:n.emailVerified||!1,phoneNumber:n.phoneNumber||null,tenantId:n.tenantId||null,providerData:i,metadata:new UserMetadata(n.createdAt,n.lastLoginAt),isAnonymous:!(n.email&&n.passwordHash||(null==i?void 0:i.length))};return Object.assign(a,c),a}}const w=new Map;function _getInstance(e){debugAssert(e instanceof Function,”Expected a class definition”);let t=w.get(e);return t?(debugAssert(t instanceof e,”Instance stored in cache mismatched with class”),t):(t=new e,w.set(e,t),t)}class InMemoryPersistence{constructor(){this.type=”NONE”,this.storage={}}async _isAvailable(){return!0}async _set(e,t){this.storage[e]=t}async _get(e){const t=this.storage[e];return void 0===t?null:t}async _remove(e){delete this.storage[e]}_addListener(e,t){}_removeListener(e,t){}}InMemoryPersistence.type=”NONE”;const S=InMemoryPersistence;function _persistenceKeyName(e,t,r){return`firebase:${e}:${t}:${r}`}class PersistenceUserManager{constructor(e,t,r){this.persistence=e,this.auth=t,this.userKey=r;const{config:n,name:i}=this.auth;this.fullUserKey=_persistenceKeyName(this.userKey,n.apiKey,i),this.fullPersistenceKey=_persistenceKeyName(“persistence”,n.apiKey,i),this.boundEventHandler=t._onStorageEvent.bind(t),this.persistence._addListener(this.fullUserKey,this.boundEventHandler)}setCurrentUser(e){return this.persistence._set(this.fullUserKey,e.toJSON())}async getCurrentUser(){const e=await this.persistence._get(this.fullUserKey);if(!e)return null;if(“string”==typeof e){const t=await getAccountInfo(this.auth,{idToken:e}).catch((()=>{}));return t?UserImpl._fromGetAccountInfoResponse(this.auth,t,e):null}return UserImpl._fromJSON(this.auth,e)}removeCurrentUser(){return this.persistence._remove(this.fullUserKey)}savePersistenceForRedirect(){return this.persistence._set(this.fullPersistenceKey,this.persistence.type)}async setPersistence(e){if(this.persistence===e)return;const t=await this.getCurrentUser();return await this.removeCurrentUser(),this.persistence=e,t?this.setCurrentUser(t):void 0}delete(){this.persistence._removeListener(this.fullUserKey,this.boundEventHandler)}static async create(e,t,r=”authUser”){if(!t.length)return new PersistenceUserManager(_getInstance(S),e,r);const n=(await Promise.all(t.map((async e=>{if(await e._isAvailable())return e})))).filter((e=>e));let i=n[0]||_getInstance(S);const s=_persistenceKeyName(r,e.config.apiKey,e.name);let o=null;for(const r of t)try{const t=await r._get(s);if(t){let n;if(“string”==typeof t){const r=await getAccountInfo(e,{idToken:t}).catch((()=>{}));if(!r)break;n=await UserImpl._fromGetAccountInfoResponse(e,r,t)}else n=UserImpl._fromJSON(e,t);r!==i&&(o=n),i=r;break}}catch(e){}const a=n.filter((e=>e._shouldAllowMigration));return i._shouldAllowMigration&&a.length?(i=a[0],o&&await i._set(s,o.toJSON()),await Promise.all(t.map((async e=>{if(e!==i)try{await e._remove(s)}catch(e){}}))),new PersistenceUserManager(i,e,r)):new PersistenceUserManager(i,e,r)}}function _getBrowserName(e){const t=e.toLowerCase();if(t.includes(“opera/”)||t.includes(“opr/”)||t.includes(“opios/”))return”Opera”;if(_isIEMobile(t))return”IEMobile”;if(t.includes(“msie”)||t.includes(“trident/”))return”IE”;if(t.includes(“edge/”))return”Edge”;if(_isFirefox(t))return”Firefox”;if(t.includes(“silk/”))return”Silk”;if(_isBlackBerry(t))return”Blackberry”;if(_isWebOS(t))return”Webos”;if(_isSafari(t))return”Safari”;if((t.includes(“chrome/”)||_isChromeIOS(t))&&!t.includes(“edge/”))return”Chrome”;if(_isAndroid(t))return”Android”;{const t=/([a-zA-Z\d\.]+)\/[a-zA-Z\d\.]*$/,r=e.match(t);if(2===(null==r?void 0:r.length))return r[1]}return”Other”}function _isFirefox(e=getUA()){return/firefox\//i.test(e)}function _isSafari(e=getUA()){const t=e.toLowerCase();return t.includes(“safari/”)&&!t.includes(“chrome/”)&&!t.includes(“crios/”)&&!t.includes(“android”)}function _isChromeIOS(e=getUA()){return/crios\//i.test(e)}function _isIEMobile(e=getUA()){return/iemobile/i.test(e)}function _isAndroid(e=getUA()){return/android/i.test(e)}function _isBlackBerry(e=getUA()){return/blackberry/i.test(e)}function _isWebOS(e=getUA()){return/webos/i.test(e)}function _isIOS(e=getUA()){return/iphone|ipad|ipod/i.test(e)||/macintosh/i.test(e)&&/mobile/i.test(e)}function _isIE10(){return function isIE(){const e=getUA();return e.indexOf(“MSIE “)>=0||e.indexOf(“Trident/”)>=0}()&&10===document.documentMode}function _isMobileBrowser(e=getUA()){return _isIOS(e)||_isAndroid(e)||_isWebOS(e)||_isBlackBerry(e)||/windows phone/i.test(e)||_isIEMobile(e)}function _getClientVersion(e,t=[]){let r;switch(e){case”Browser”:r=_getBrowserName(getUA());break;case”Worker”:r=`${_getBrowserName(getUA())}-${e}`;break;default:r=e}const n=t.length?t.join(“,”):”FirebaseCore-web”;return`${r}/JsCore/${i}/${n}`}class AuthMiddlewareQueue{constructor(e){this.auth=e,this.queue=[]}pushCallback(e,t){const wrappedCallback=t=>new Promise(((r,n)=>{try{r(e(t))}catch(e){n(e)}}));wrappedCallback.onAbort=t,this.queue.push(wrappedCallback);const r=this.queue.length-1;return()=>{this.queue[r]=()=>Promise.resolve()}}async runMiddleware(e){if(this.auth.currentUser===e)return;const t=[];try{for(const r of this.queue)await r(e),r.onAbort&&t.push(r.onAbort)}catch(e){t.reverse();for(const e of t)try{e()}catch(e){}throw this.auth._errorFactory.create(“login-blocked”,{originalMessage:null==e?void 0:e.message})}}}class PasswordPolicyImpl{constructor(e){var t,r,n,i;const s=e.customStrengthOptions;this.customStrengthOptions={},this.customStrengthOptions.minPasswordLength=null!==(t=s.minPasswordLength)&&void 0!==t?t:6,s.maxPasswordLength&&(this.customStrengthOptions.maxPasswordLength=s.maxPasswordLength),void 0!==s.containsLowercaseCharacter&&(this.customStrengthOptions.containsLowercaseLetter=s.containsLowercaseCharacter),void 0!==s.containsUppercaseCharacter&&(this.customStrengthOptions.containsUppercaseLetter=s.containsUppercaseCharacter),void 0!==s.containsNumericCharacter&&(this.customStrengthOptions.containsNumericCharacter=s.containsNumericCharacter),void 0!==s.containsNonAlphanumericCharacter&&(this.customStrengthOptions.containsNonAlphanumericCharacter=s.containsNonAlphanumericCharacter),this.enforcementState=e.enforcementState,”ENFORCEMENT_STATE_UNSPECIFIED”===this.enforcementState&&(this.enforcementState=”OFF”),this.allowedNonAlphanumericCharacters=null!==(n=null===(r=e.allowedNonAlphanumericCharacters)||void 0===r?void 0:r.join(“”))&&void 0!==n?n:””,this.forceUpgradeOnSignin=null!==(i=e.forceUpgradeOnSignin)&&void 0!==i&&i,this.schemaVersion=e.schemaVersion}validatePassword(e){var t,r,n,i,s,o;const a={isValid:!0,passwordPolicy:this};return this.validatePasswordLengthOptions(e,a),this.validatePasswordCharacterOptions(e,a),a.isValid&&(a.isValid=null===(t=a.meetsMinPasswordLength)||void 0===t||t),a.isValid&&(a.isValid=null===(r=a.meetsMaxPasswordLength)||void 0===r||r),a.isValid&&(a.isValid=null===(n=a.containsLowercaseLetter)||void 0===n||n),a.isValid&&(a.isValid=null===(i=a.containsUppercaseLetter)||void 0===i||i),a.isValid&&(a.isValid=null===(s=a.containsNumericCharacter)||void 0===s||s),a.isValid&&(a.isValid=null===(o=a.containsNonAlphanumericCharacter)||void 0===o||o),a}validatePasswordLengthOptions(e,t){const r=this.customStrengthOptions.minPasswordLength,n=this.customStrengthOptions.maxPasswordLength;r&&(t.meetsMinPasswordLength=e.length>=r),n&&(t.meetsMaxPasswordLength=e.length<=n)}validatePasswordCharacterOptions(e,t){let r;this.updatePasswordCharacterOptionsStatuses(t,!1,!1,!1,!1);for(let n=0;n=”a”&&r<="z",r>=”A”&&r<="Z",r>=”0″&&r<="9",this.allowedNonAlphanumericCharacters.includes(r))}updatePasswordCharacterOptionsStatuses(e,t,r,n,i){this.customStrengthOptions.containsLowercaseLetter&&(e.containsLowercaseLetter||(e.containsLowercaseLetter=t)),this.customStrengthOptions.containsUppercaseLetter&&(e.containsUppercaseLetter||(e.containsUppercaseLetter=r)),this.customStrengthOptions.containsNumericCharacter&&(e.containsNumericCharacter||(e.containsNumericCharacter=n)),this.customStrengthOptions.containsNonAlphanumericCharacter&&(e.containsNonAlphanumericCharacter||(e.containsNonAlphanumericCharacter=i))}}class AuthImpl{constructor(e,t,r,n){this.app=e,this.heartbeatServiceProvider=t,this.appCheckServiceProvider=r,this.config=n,this.currentUser=null,this.emulatorConfig=null,this.operations=Promise.resolve(),this.authStateSubscription=new Subscription(this),this.idTokenSubscription=new Subscription(this),this.beforeStateQueue=new AuthMiddlewareQueue(this),this.redirectUser=null,this.isProactiveRefreshEnabled=!1,this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION=1,this._canInitEmulator=!0,this._isInitialized=!1,this._deleted=!1,this._initializationPromise=null,this._popupRedirectResolver=null,this._errorFactory=I,this._agentRecaptchaConfig=null,this._tenantRecaptchaConfigs={},this._projectPasswordPolicy=null,this._tenantPasswordPolicies={},this._resolvePersistenceManagerAvailable=void 0,this.lastNotifiedUid=void 0,this.languageCode=null,this.tenantId=null,this.settings={appVerificationDisabledForTesting:!1},this.frameworks=[],this.name=e.name,this.clientVersion=n.sdkClientVersion,this._persistenceManagerAvailable=new Promise((e=>this._resolvePersistenceManagerAvailable=e))}_initializeWithPersistence(e,t){return t&&(this._popupRedirectResolver=_getInstance(t)),this._initializationPromise=this.queue((async()=>{var r,n,i;if(!this._deleted&&(this.persistenceManager=await PersistenceUserManager.create(this,e),null===(r=this._resolvePersistenceManagerAvailable)||void 0===r||r.call(this),!this._deleted)){if(null===(n=this._popupRedirectResolver)||void 0===n?void 0:n._shouldInitProactively)try{await this._popupRedirectResolver._initialize(this)}catch(e){}await this.initializeCurrentUser(t),this.lastNotifiedUid=(null===(i=this.currentUser)||void 0===i?void 0:i.uid)||null,this._deleted||(this._isInitialized=!0)}})),this._initializationPromise}async _onStorageEvent(){if(this._deleted)return;const e=await this.assertedPersistence.getCurrentUser();return this.currentUser||e?this.currentUser&&e&&this.currentUser.uid===e.uid?(this._currentUser._assign(e),void await this.currentUser.getIdToken()):void await this._updateCurrentUser(e,!0):void 0}async initializeCurrentUserFromIdToken(e){try{const t=await getAccountInfo(this,{idToken:e}),r=await UserImpl._fromGetAccountInfoResponse(this,t,e);await this.directlySetCurrentUser(r)}catch(e){console.warn(“FirebaseServerApp could not login user with provided authIdToken: “,e),await this.directlySetCurrentUser(null)}}async initializeCurrentUser(t){var r;if(e(this.app)){const e=this.app.settings.authIdToken;return e?new Promise((t=>{setTimeout((()=>this.initializeCurrentUserFromIdToken(e).then(t,t)))})):this.directlySetCurrentUser(null)}const n=await this.assertedPersistence.getCurrentUser();let i=n,s=!1;if(t&&this.config.authDomain){await this.getOrInitRedirectPersistenceManager();const e=null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId,n=null==i?void 0:i._redirectEventId,o=await this.tryRedirectSignIn(t);e&&e!==n||!(null==o?void 0:o.user)||(i=o.user,s=!0)}if(!i)return this.directlySetCurrentUser(null);if(!i._redirectEventId){if(s)try{await this.beforeStateQueue.runMiddleware(i)}catch(e){i=n,this._popupRedirectResolver._overrideRedirectResult(this,(()=>Promise.reject(e)))}return i?this.reloadAndSetCurrentUserOrClear(i):this.directlySetCurrentUser(null)}return _assert(this._popupRedirectResolver,this,”argument-error”),await this.getOrInitRedirectPersistenceManager(),this.redirectUser&&this.redirectUser._redirectEventId===i._redirectEventId?this.directlySetCurrentUser(i):this.reloadAndSetCurrentUserOrClear(i)}async tryRedirectSignIn(e){let t=null;try{t=await this._popupRedirectResolver._completeRedirectFn(this,e,!0)}catch(e){await this._setRedirectUser(null)}return t}async reloadAndSetCurrentUserOrClear(e){try{await _reloadWithoutSaving(e)}catch(e){if(“auth/network-request-failed”!==(null==e?void 0:e.code))return this.directlySetCurrentUser(null)}return this.directlySetCurrentUser(e)}useDeviceLanguage(){this.languageCode=function _getUserLanguage(){if(“undefined”==typeof navigator)return null;const e=navigator;return e.languages&&e.languages[0]||e.language||null}()}async _delete(){this._deleted=!0}async updateCurrentUser(t){if(e(this.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this));const r=t?getModularInstance(t):null;return r&&_assert(r.auth.config.apiKey===this.config.apiKey,this,”invalid-user-token”),this._updateCurrentUser(r&&r._clone(this))}async _updateCurrentUser(e,t=!1){if(!this._deleted)return e&&_assert(this.tenantId===e.tenantId,this,”tenant-id-mismatch”),t||await this.beforeStateQueue.runMiddleware(e),this.queue((async()=>{await this.directlySetCurrentUser(e),this.notifyAuthListeners()}))}async signOut(){return e(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):(await this.beforeStateQueue.runMiddleware(null),(this.redirectPersistenceManager||this._popupRedirectResolver)&&await this._setRedirectUser(null),this._updateCurrentUser(null,!0))}setPersistence(t){return e(this.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(this)):this.queue((async()=>{await this.assertedPersistence.setPersistence(_getInstance(t))}))}_getRecaptchaConfig(){return null==this.tenantId?this._agentRecaptchaConfig:this._tenantRecaptchaConfigs[this.tenantId]}async validatePassword(e){this._getPasswordPolicyInternal()||await this._updatePasswordPolicy();const t=this._getPasswordPolicyInternal();return t.schemaVersion!==this.EXPECTED_PASSWORD_POLICY_SCHEMA_VERSION?Promise.reject(this._errorFactory.create(“unsupported-password-policy-schema-version”,{})):t.validatePassword(e)}_getPasswordPolicyInternal(){return null===this.tenantId?this._projectPasswordPolicy:this._tenantPasswordPolicies[this.tenantId]}async _updatePasswordPolicy(){const e=await async function _getPasswordPolicy(e,t={}){return _performApiRequest(e,”GET”,”/v2/passwordPolicy”,_addTidIfNecessary(e,t))}(this),t=new PasswordPolicyImpl(e);null===this.tenantId?this._projectPasswordPolicy=t:this._tenantPasswordPolicies[this.tenantId]=t}_getPersistenceType(){return this.assertedPersistence.persistence.type}_getPersistence(){return this.assertedPersistence.persistence}_updateErrorMap(e){this._errorFactory=new ErrorFactory(“auth”,”Firebase”,e())}onAuthStateChanged(e,t,r){return this.registerStateListener(this.authStateSubscription,e,t,r)}beforeAuthStateChanged(e,t){return this.beforeStateQueue.pushCallback(e,t)}onIdTokenChanged(e,t,r){return this.registerStateListener(this.idTokenSubscription,e,t,r)}authStateReady(){return new Promise(((e,t)=>{if(this.currentUser)e();else{const r=this.onAuthStateChanged((()=>{r(),e()}),t)}}))}async revokeAccessToken(e){if(this.currentUser){const t={providerId:”apple.com”,tokenType:”ACCESS_TOKEN”,token:e,idToken:await this.currentUser.getIdToken()};null!=this.tenantId&&(t.tenantId=this.tenantId),await async function revokeToken(e,t){return _performApiRequest(e,”POST”,”/v2/accounts:revokeToken”,_addTidIfNecessary(e,t))}(this,t)}}toJSON(){var e;return{apiKey:this.config.apiKey,authDomain:this.config.authDomain,appName:this.name,currentUser:null===(e=this._currentUser)||void 0===e?void 0:e.toJSON()}}async _setRedirectUser(e,t){const r=await this.getOrInitRedirectPersistenceManager(t);return null===e?r.removeCurrentUser():r.setCurrentUser(e)}async getOrInitRedirectPersistenceManager(e){if(!this.redirectPersistenceManager){const t=e&&_getInstance(e)||this._popupRedirectResolver;_assert(t,this,”argument-error”),this.redirectPersistenceManager=await PersistenceUserManager.create(this,[_getInstance(t._redirectPersistence)],”redirectUser”),this.redirectUser=await this.redirectPersistenceManager.getCurrentUser()}return this.redirectPersistenceManager}async _redirectUserForId(e){var t,r;return this._isInitialized&&await this.queue((async()=>{})),(null===(t=this._currentUser)||void 0===t?void 0:t._redirectEventId)===e?this._currentUser:(null===(r=this.redirectUser)||void 0===r?void 0:r._redirectEventId)===e?this.redirectUser:null}async _persistUserIfCurrent(e){if(e===this.currentUser)return this.queue((async()=>this.directlySetCurrentUser(e)))}_notifyListenersIfCurrent(e){e===this.currentUser&&this.notifyAuthListeners()}_key(){return`${this.config.authDomain}:${this.config.apiKey}:${this.name}`}_startProactiveRefresh(){this.isProactiveRefreshEnabled=!0,this.currentUser&&this._currentUser._startProactiveRefresh()}_stopProactiveRefresh(){this.isProactiveRefreshEnabled=!1,this.currentUser&&this._currentUser._stopProactiveRefresh()}get _currentUser(){return this.currentUser}notifyAuthListeners(){var e,t;if(!this._isInitialized)return;this.idTokenSubscription.next(this.currentUser);const r=null!==(t=null===(e=this.currentUser)||void 0===e?void 0:e.uid)&&void 0!==t?t:null;this.lastNotifiedUid!==r&&(this.lastNotifiedUid=r,this.authStateSubscription.next(this.currentUser))}registerStateListener(e,t,r,n){if(this._deleted)return()=>{};const i=”function”==typeof t?t:t.next.bind(t);let s=!1;const o=this._isInitialized?Promise.resolve():this._initializationPromise;if(_assert(o,this,”internal-error”),o.then((()=>{s||i(this.currentUser)})),”function”==typeof t){const i=e.addObserver(t,r,n);return()=>{s=!0,i()}}{const r=e.addObserver(t);return()=>{s=!0,r()}}}async directlySetCurrentUser(e){this.currentUser&&this.currentUser!==e&&this._currentUser._stopProactiveRefresh(),e&&this.isProactiveRefreshEnabled&&e._startProactiveRefresh(),this.currentUser=e,e?await this.assertedPersistence.setCurrentUser(e):await this.assertedPersistence.removeCurrentUser()}queue(e){return this.operations=this.operations.then(e,e),this.operations}get assertedPersistence(){return _assert(this.persistenceManager,this,”internal-error”),this.persistenceManager}_logFramework(e){e&&!this.frameworks.includes(e)&&(this.frameworks.push(e),this.frameworks.sort(),this.clientVersion=_getClientVersion(this.config.clientPlatform,this._getFrameworks()))}_getFrameworks(){return this.frameworks}async _getAdditionalHeaders(){var e;const t={“X-Client-Version”:this.clientVersion};this.app.options.appId&&(t[“X-Firebase-gmpid”]=this.app.options.appId);const r=await(null===(e=this.heartbeatServiceProvider.getImmediate({optional:!0}))||void 0===e?void 0:e.getHeartbeatsHeader());r&&(t[“X-Firebase-Client”]=r);const n=await this._getAppCheckToken();return n&&(t[“X-Firebase-AppCheck”]=n),t}async _getAppCheckToken(){var t;if(e(this.app)&&this.app.settings.appCheckToken)return this.app.settings.appCheckToken;const r=await(null===(t=this.appCheckServiceProvider.getImmediate({optional:!0}))||void 0===t?void 0:t.getToken());return(null==r?void 0:r.error)&&function _logWarn(e,…t){E.logLevel<=a.WARN&&E.warn(`Auth (${i}): ${e}`,...t)}(`Error while retrieving App Check token: ${r.error}`),null==r?void 0:r.token}}function _castAuth(e){return getModularInstance(e)}class Subscription{constructor(e){this.auth=e,this.observer=null,this.addObserver=function createSubscribe(e,t){const r=new ObserverProxy(e,t);return r.subscribe.bind(r)}((e=>this.observer=e))}get next(){return _assert(this.observer,this.auth,”internal-error”),this.observer.next.bind(this.observer)}}let P={async loadJS(){throw new Error(“Unable to load external scripts”)},recaptchaV2Script:””,recaptchaEnterpriseScript:””,gapiScript:””};function _loadJS(e){return P.loadJS(e)}function _generateCallbackName(e){return`__${e}${Math.floor(1e6*Math.random())}`}const R=1e12;class MockReCaptcha{constructor(e){this.auth=e,this.counter=R,this._widgets=new Map}render(e,t){const r=this.counter;return this._widgets.set(r,new MockWidget(e,this.auth.name,t||{})),this.counter++,r}reset(e){var t;const r=e||R;null===(t=this._widgets.get(r))||void 0===t||t.delete(),this._widgets.delete(r)}getResponse(e){var t;const r=e||R;return(null===(t=this._widgets.get(r))||void 0===t?void 0:t.getResponse())||””}async execute(e){var t;const r=e||R;return null===(t=this._widgets.get(r))||void 0===t||t.execute(),””}}class MockGreCAPTCHATopLevel{constructor(){this.enterprise=new MockGreCAPTCHA}ready(e){e()}execute(e,t){return Promise.resolve(“token”)}render(e,t){return””}}class MockGreCAPTCHA{ready(e){e()}execute(e,t){return Promise.resolve(“token”)}render(e,t){return””}}class MockWidget{constructor(e,t,r){this.params=r,this.timerId=null,this.deleted=!1,this.responseToken=null,this.clickHandler=()=>{this.execute()};const n=”string”==typeof e?document.getElementById(e):e;_assert(n,”argument-error”,{appName:t}),this.container=n,this.isVisible=”invisible”!==this.params.size,this.isVisible?this.execute():this.container.addEventListener(“click”,this.clickHandler)}getResponse(){return this.checkIfDeleted(),this.responseToken}delete(){this.checkIfDeleted(),this.deleted=!0,this.timerId&&(clearTimeout(this.timerId),this.timerId=null),this.container.removeEventListener(“click”,this.clickHandler)}execute(){this.checkIfDeleted(),this.timerId||(this.timerId=window.setTimeout((()=>{this.responseToken=function generateRandomAlphaNumericString(e){const t=[],r=”1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”;for(let n=0;n{if(this.timerId=null,this.responseToken=null,t)try{t()}catch(e){}this.isVisible&&this.execute()}),6e4)}),500))}checkIfDeleted(){if(this.deleted)throw new Error(“reCAPTCHA mock was already deleted!”)}}const k=”NO_RECAPTCHA”;class RecaptchaEnterpriseVerifier{constructor(e){this.type=”recaptcha-enterprise”,this.auth=_castAuth(e)}async verify(e=”verify”,t=!1){function retrieveRecaptchaToken(t,r,n){const i=window.grecaptcha;isEnterprise(i)?i.enterprise.ready((()=>{i.enterprise.execute(t,{action:e}).then((e=>{r(e)})).catch((()=>{r(k)}))})):n(Error(“No reCAPTCHA enterprise script loaded.”))}if(this.auth.settings.appVerificationDisabledForTesting){return(new MockGreCAPTCHATopLevel).execute(“siteKey”,{action:”verify”})}return new Promise(((e,r)=>{(async function retrieveSiteKey(e){if(!t){if(null==e.tenantId&&null!=e._agentRecaptchaConfig)return e._agentRecaptchaConfig.siteKey;if(null!=e.tenantId&&void 0!==e._tenantRecaptchaConfigs[e.tenantId])return e._tenantRecaptchaConfigs[e.tenantId].siteKey}return new Promise((async(t,r)=>{getRecaptchaConfig(e,{clientType:”CLIENT_TYPE_WEB”,version:”RECAPTCHA_ENTERPRISE”}).then((n=>{if(void 0!==n.recaptchaKey){const r=new RecaptchaConfig(n);return null==e.tenantId?e._agentRecaptchaConfig=r:e._tenantRecaptchaConfigs[e.tenantId]=r,t(r.siteKey)}r(new Error(“recaptcha Enterprise site key undefined”))})).catch((e=>{r(e)}))}))})(this.auth).then((n=>{if(!t&&isEnterprise(window.grecaptcha))retrieveRecaptchaToken(n,e,r);else{if(“undefined”==typeof window)return void r(new Error(“RecaptchaVerifier is only supported in browser”));let t=function _recaptchaEnterpriseScriptUrl(){return P.recaptchaEnterpriseScript}();0!==t.length&&(t+=n),_loadJS(t).then((()=>{retrieveRecaptchaToken(n,e,r)})).catch((e=>{r(e)}))}})).catch((e=>{r(e)}))}))}}async function injectRecaptchaFields(e,t,r,n=!1,i=!1){const s=new RecaptchaEnterpriseVerifier(e);let o;if(i)o=k;else try{o=await s.verify(r)}catch(e){o=await s.verify(r,!0)}const a=Object.assign({},t);if(“mfaSmsEnrollment”===r||”mfaSmsSignIn”===r){if(“phoneEnrollmentInfo”in a){const e=a.phoneEnrollmentInfo.phoneNumber,t=a.phoneEnrollmentInfo.recaptchaToken;Object.assign(a,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:t,captchaResponse:o,clientType:”CLIENT_TYPE_WEB”,recaptchaVersion:”RECAPTCHA_ENTERPRISE”}})}else if(“phoneSignInInfo”in a){const e=a.phoneSignInInfo.recaptchaToken;Object.assign(a,{phoneSignInInfo:{recaptchaToken:e,captchaResponse:o,clientType:”CLIENT_TYPE_WEB”,recaptchaVersion:”RECAPTCHA_ENTERPRISE”}})}return a}return n?Object.assign(a,{captchaResp:o}):Object.assign(a,{captchaResponse:o}),Object.assign(a,{clientType:”CLIENT_TYPE_WEB”}),Object.assign(a,{recaptchaVersion:”RECAPTCHA_ENTERPRISE”}),a}async function handleRecaptchaFlow(e,t,r,n,i){var s,o;if(“EMAIL_PASSWORD_PROVIDER”===i){if(null===(s=e._getRecaptchaConfig())||void 0===s?void 0:s.isProviderEnabled(“EMAIL_PASSWORD_PROVIDER”)){const i=await injectRecaptchaFields(e,t,r,”getOobCode”===r);return n(e,i)}return n(e,t).catch((async i=>{if(“auth/missing-recaptcha-token”===i.code){console.log(`${r} is protected by reCAPTCHA Enterprise for this project. Automatically triggering the reCAPTCHA flow and restarting the flow.`);const i=await injectRecaptchaFields(e,t,r,”getOobCode”===r);return n(e,i)}return Promise.reject(i)}))}if(“PHONE_PROVIDER”===i){if(null===(o=e._getRecaptchaConfig())||void 0===o?void 0:o.isProviderEnabled(“PHONE_PROVIDER”)){const i=await injectRecaptchaFields(e,t,r);return n(e,i).catch((async i=>{var s;if(“AUDIT”===(null===(s=e._getRecaptchaConfig())||void 0===s?void 0:s.getProviderEnforcementState(“PHONE_PROVIDER”))&&(“auth/missing-recaptcha-token”===i.code||”auth/invalid-app-credential”===i.code)){console.log(`Failed to verify with reCAPTCHA Enterprise. Automatically triggering the reCAPTCHA v2 flow to complete the ${r} flow.`);const i=await injectRecaptchaFields(e,t,r,!1,!0);return n(e,i)}return Promise.reject(i)}))}{const i=await injectRecaptchaFields(e,t,r,!1,!0);return n(e,i)}}return Promise.reject(i+” provider is not supported.”)}async function _initializeRecaptchaConfig(e){const t=_castAuth(e),r=await getRecaptchaConfig(t,{clientType:”CLIENT_TYPE_WEB”,version:”RECAPTCHA_ENTERPRISE”}),n=new RecaptchaConfig(r);if(null==t.tenantId?t._agentRecaptchaConfig=n:t._tenantRecaptchaConfigs[t.tenantId]=n,n.isAnyProviderEnabled()){new RecaptchaEnterpriseVerifier(t).verify()}}function initializeAuth(e,t){const r=_getProvider(e,”auth”);if(r.isInitialized()){const e=r.getImmediate();if(deepEqual(r.getOptions(),null!=t?t:{}))return e;_fail(e,”already-initialized”)}return r.initialize({options:t})}function connectAuthEmulator(e,t,r){const n=_castAuth(e);_assert(/^https?:\/\//.test(t),n,”invalid-emulator-scheme”);const i=!!(null==r?void 0:r.disableWarnings),s=extractProtocol(t),{host:o,port:a}=function extractHostAndPort(e){const t=extractProtocol(e),r=/(\/\/)?([^?#/]+)/.exec(e.substr(t.length));if(!r)return{host:””,port:null};const n=r[2].split(“@”).pop()||””,i=/^(\[[^\]]+\])(:|$)/.exec(n);if(i){const e=i[1];return{host:e,port:parsePort(n.substr(e.length+1))}}{const[e,t]=n.split(“:”);return{host:e,port:parsePort(t)}}}(t),c={url:`${s}//${o}${null===a?””:`:${a}`}/`},u=Object.freeze({host:o,port:a,protocol:s.replace(“:”,””),options:Object.freeze({disableWarnings:i})});if(!n._canInitEmulator)return _assert(n.config.emulator&&n.emulatorConfig,n,”emulator-config-failed”),void _assert(deepEqual(c,n.config.emulator)&&deepEqual(u,n.emulatorConfig),n,”emulator-config-failed”);n.config.emulator=c,n.emulatorConfig=u,n.settings.appVerificationDisabledForTesting=!0,i||function emitEmulatorWarning(){function attachBanner(){const e=document.createElement(“p”),t=e.style;e.innerText=”Running in emulator mode. Do not use with production credentials.”,t.position=”fixed”,t.width=”100%”,t.backgroundColor=”#ffffff”,t.border=”.1em solid #000000″,t.color=”#b50000″,t.bottom=”0px”,t.left=”0px”,t.margin=”0px”,t.zIndex=”10000″,t.textAlign=”center”,e.classList.add(“firebase-emulator-warning”),document.body.appendChild(e)}”undefined”!=typeof console&&”function”==typeof console.info&&console.info(“WARNING: You are using the Auth Emulator, which is intended for local testing only. Do not use with production credentials.”);”undefined”!=typeof window&&”undefined”!=typeof document&&(“loading”===document.readyState?window.addEventListener(“DOMContentLoaded”,attachBanner):attachBanner())}()}function extractProtocol(e){const t=e.indexOf(“:”);return t<0?"":e.substr(0,t+1)}function parsePort(e){if(!e)return null;const t=Number(e);return isNaN(t)?null:t}class AuthCredential{constructor(e,t){this.providerId=e,this.signInMethod=t}toJSON(){return debugFail("not implemented")}_getIdTokenResponse(e){return debugFail("not implemented")}_linkToIdToken(e,t){return debugFail("not implemented")}_getReauthenticationResolver(e){return debugFail("not implemented")}}async function resetPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:resetPassword",_addTidIfNecessary(e,t))}async function linkEmailPassword(e,t){return _performApiRequest(e,"POST","/v1/accounts:signUp",t)}async function signInWithPassword(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPassword",_addTidIfNecessary(e,t))}async function sendOobCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendOobCode",_addTidIfNecessary(e,t))}async function sendPasswordResetEmail$1(e,t){return sendOobCode(e,t)}async function sendSignInLinkToEmail$1(e,t){return sendOobCode(e,t)}class EmailAuthCredential extends AuthCredential{constructor(e,t,r,n=null){super("password",r),this._email=e,this._password=t,this._tenantId=n}static _fromEmailAndPassword(e,t){return new EmailAuthCredential(e,t,"password")}static _fromEmailAndCode(e,t,r=null){return new EmailAuthCredential(e,t,"emailLink",r)}toJSON(){return{email:this._email,password:this._password,signInMethod:this.signInMethod,tenantId:this._tenantId}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e;if((null==t?void 0:t.email)&&(null==t?void 0:t.password)){if("password"===t.signInMethod)return this._fromEmailAndPassword(t.email,t.password);if("emailLink"===t.signInMethod)return this._fromEmailAndCode(t.email,t.password,t.tenantId)}return null}async _getIdTokenResponse(e){switch(this.signInMethod){case"password":return handleRecaptchaFlow(e,{returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signInWithPassword",signInWithPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function signInWithEmailLink$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}(e,{email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}async _linkToIdToken(e,t){switch(this.signInMethod){case"password":return handleRecaptchaFlow(e,{idToken:t,returnSecureToken:!0,email:this._email,password:this._password,clientType:"CLIENT_TYPE_WEB"},"signUpPassword",linkEmailPassword,"EMAIL_PASSWORD_PROVIDER");case"emailLink":return async function signInWithEmailLinkForLinking(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithEmailLink",_addTidIfNecessary(e,t))}(e,{idToken:t,email:this._email,oobCode:this._password});default:_fail(e,"internal-error")}}_getReauthenticationResolver(e){return this._getIdTokenResponse(e)}}async function signInWithIdp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithIdp",_addTidIfNecessary(e,t))}class OAuthCredential extends AuthCredential{constructor(){super(...arguments),this.pendingToken=null}static _fromParams(e){const t=new OAuthCredential(e.providerId,e.signInMethod);return e.idToken||e.accessToken?(e.idToken&&(t.idToken=e.idToken),e.accessToken&&(t.accessToken=e.accessToken),e.nonce&&!e.pendingToken&&(t.nonce=e.nonce),e.pendingToken&&(t.pendingToken=e.pendingToken)):e.oauthToken&&e.oauthTokenSecret?(t.accessToken=e.oauthToken,t.secret=e.oauthTokenSecret):_fail("argument-error"),t}toJSON(){return{idToken:this.idToken,accessToken:this.accessToken,secret:this.secret,nonce:this.nonce,pendingToken:this.pendingToken,providerId:this.providerId,signInMethod:this.signInMethod}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n}=t,i=__rest(t,["providerId","signInMethod"]);if(!r||!n)return null;const s=new OAuthCredential(r,n);return s.idToken=i.idToken||void 0,s.accessToken=i.accessToken||void 0,s.secret=i.secret,s.nonce=i.nonce,s.pendingToken=i.pendingToken||null,s}_getIdTokenResponse(e){return signInWithIdp(e,this.buildRequest())}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,signInWithIdp(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,signInWithIdp(e,t)}buildRequest(){const e={requestUri:"http://localhost",returnSecureToken:!0};if(this.pendingToken)e.pendingToken=this.pendingToken;else{const t={};this.idToken&&(t.id_token=this.idToken),this.accessToken&&(t.access_token=this.accessToken),this.secret&&(t.oauth_token_secret=this.secret),t.providerId=this.providerId,this.nonce&&!this.pendingToken&&(t.nonce=this.nonce),e.postBody=querystring(t)}return e}}async function sendPhoneVerificationCode(e,t){return _performApiRequest(e,"POST","/v1/accounts:sendVerificationCode",_addTidIfNecessary(e,t))}const C={USER_NOT_FOUND:"user-not-found"};class PhoneAuthCredential extends AuthCredential{constructor(e){super("phone","phone"),this.params=e}static _fromVerification(e,t){return new PhoneAuthCredential({verificationId:e,verificationCode:t})}static _fromTokenResponse(e,t){return new PhoneAuthCredential({phoneNumber:e,temporaryProof:t})}_getIdTokenResponse(e){return async function signInWithPhoneNumber$1(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t))}(e,this._makeVerificationRequest())}_linkToIdToken(e,t){return async function linkWithPhoneNumber$1(e,t){const r=await _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,t));if(r.temporaryProof)throw _makeTaggedError(e,"account-exists-with-different-credential",r);return r}(e,Object.assign({idToken:t},this._makeVerificationRequest()))}_getReauthenticationResolver(e){return async function verifyPhoneNumberForExisting(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signInWithPhoneNumber",_addTidIfNecessary(e,Object.assign(Object.assign({},t),{operation:"REAUTH"})),C)}(e,this._makeVerificationRequest())}_makeVerificationRequest(){const{temporaryProof:e,phoneNumber:t,verificationId:r,verificationCode:n}=this.params;return e&&t?{temporaryProof:e,phoneNumber:t}:{sessionInfo:r,code:n}}toJSON(){const e={providerId:this.providerId};return this.params.phoneNumber&&(e.phoneNumber=this.params.phoneNumber),this.params.temporaryProof&&(e.temporaryProof=this.params.temporaryProof),this.params.verificationCode&&(e.verificationCode=this.params.verificationCode),this.params.verificationId&&(e.verificationId=this.params.verificationId),e}static fromJSON(e){"string"==typeof e&&(e=JSON.parse(e));const{verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}=e;return r||t||n||i?new PhoneAuthCredential({verificationId:t,verificationCode:r,phoneNumber:n,temporaryProof:i}):null}}class ActionCodeURL{constructor(e){var t,r,n,i,s,o;const a=querystringDecode(extractQuerystring(e)),c=null!==(t=a.apiKey)&&void 0!==t?t:null,u=null!==(r=a.oobCode)&&void 0!==r?r:null,d=function parseMode(e){switch(e){case"recoverEmail":return"RECOVER_EMAIL";case"resetPassword":return"PASSWORD_RESET";case"signIn":return"EMAIL_SIGNIN";case"verifyEmail":return"VERIFY_EMAIL";case"verifyAndChangeEmail":return"VERIFY_AND_CHANGE_EMAIL";case"revertSecondFactorAddition":return"REVERT_SECOND_FACTOR_ADDITION";default:return null}}(null!==(n=a.mode)&&void 0!==n?n:null);_assert(c&&u&&d,"argument-error"),this.apiKey=c,this.operation=d,this.code=u,this.continueUrl=null!==(i=a.continueUrl)&&void 0!==i?i:null,this.languageCode=null!==(s=a.lang)&&void 0!==s?s:null,this.tenantId=null!==(o=a.tenantId)&&void 0!==o?o:null}static parseLink(e){const t=function parseDeepLink(e){const t=querystringDecode(extractQuerystring(e)).link,r=t?querystringDecode(extractQuerystring(t)).deep_link_id:null,n=querystringDecode(extractQuerystring(e)).deep_link_id;return(n?querystringDecode(extractQuerystring(n)).link:null)||n||r||t||e}(e);try{return new ActionCodeURL(t)}catch(e){return null}}}function parseActionCodeURL(e){return ActionCodeURL.parseLink(e)}class EmailAuthProvider{constructor(){this.providerId=EmailAuthProvider.PROVIDER_ID}static credential(e,t){return EmailAuthCredential._fromEmailAndPassword(e,t)}static credentialWithLink(e,t){const r=ActionCodeURL.parseLink(t);return _assert(r,"argument-error"),EmailAuthCredential._fromEmailAndCode(e,r.code,r.tenantId)}}EmailAuthProvider.PROVIDER_ID="password",EmailAuthProvider.EMAIL_PASSWORD_SIGN_IN_METHOD="password",EmailAuthProvider.EMAIL_LINK_SIGN_IN_METHOD="emailLink";class FederatedAuthProvider{constructor(e){this.providerId=e,this.defaultLanguageCode=null,this.customParameters={}}setDefaultLanguage(e){this.defaultLanguageCode=e}setCustomParameters(e){return this.customParameters=e,this}getCustomParameters(){return this.customParameters}}class BaseOAuthProvider extends FederatedAuthProvider{constructor(){super(...arguments),this.scopes=[]}addScope(e){return this.scopes.includes(e)||this.scopes.push(e),this}getScopes(){return[...this.scopes]}}class OAuthProvider extends BaseOAuthProvider{static credentialFromJSON(e){const t="string"==typeof e?JSON.parse(e):e;return _assert("providerId"in t&&"signInMethod"in t,"argument-error"),OAuthCredential._fromParams(t)}credential(e){return this._credential(Object.assign(Object.assign({},e),{nonce:e.rawNonce}))}_credential(e){return _assert(e.idToken||e.accessToken,"argument-error"),OAuthCredential._fromParams(Object.assign(Object.assign({},e),{providerId:this.providerId,signInMethod:this.providerId}))}static credentialFromResult(e){return OAuthProvider.oauthCredentialFromTaggedObject(e)}static credentialFromError(e){return OAuthProvider.oauthCredentialFromTaggedObject(e.customData||{})}static oauthCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r,oauthTokenSecret:n,pendingToken:i,nonce:s,providerId:o}=e;if(!(r||n||t||i))return null;if(!o)return null;try{return new OAuthProvider(o)._credential({idToken:t,accessToken:r,nonce:s,pendingToken:i})}catch(e){return null}}}class FacebookAuthProvider extends BaseOAuthProvider{constructor(){super("facebook.com")}static credential(e){return OAuthCredential._fromParams({providerId:FacebookAuthProvider.PROVIDER_ID,signInMethod:FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return FacebookAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return FacebookAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return FacebookAuthProvider.credential(e.oauthAccessToken)}catch(e){return null}}}FacebookAuthProvider.FACEBOOK_SIGN_IN_METHOD="facebook.com",FacebookAuthProvider.PROVIDER_ID="facebook.com";class GoogleAuthProvider extends BaseOAuthProvider{constructor(){super("google.com"),this.addScope("profile")}static credential(e,t){return OAuthCredential._fromParams({providerId:GoogleAuthProvider.PROVIDER_ID,signInMethod:GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD,idToken:e,accessToken:t})}static credentialFromResult(e){return GoogleAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GoogleAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthIdToken:t,oauthAccessToken:r}=e;if(!t&&!r)return null;try{return GoogleAuthProvider.credential(t,r)}catch(e){return null}}}GoogleAuthProvider.GOOGLE_SIGN_IN_METHOD="google.com",GoogleAuthProvider.PROVIDER_ID="google.com";class GithubAuthProvider extends BaseOAuthProvider{constructor(){super("github.com")}static credential(e){return OAuthCredential._fromParams({providerId:GithubAuthProvider.PROVIDER_ID,signInMethod:GithubAuthProvider.GITHUB_SIGN_IN_METHOD,accessToken:e})}static credentialFromResult(e){return GithubAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return GithubAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e||!("oauthAccessToken"in e))return null;if(!e.oauthAccessToken)return null;try{return GithubAuthProvider.credential(e.oauthAccessToken)}catch(e){return null}}}GithubAuthProvider.GITHUB_SIGN_IN_METHOD="github.com",GithubAuthProvider.PROVIDER_ID="github.com";class SAMLAuthCredential extends AuthCredential{constructor(e,t){super(e,e),this.pendingToken=t}_getIdTokenResponse(e){return signInWithIdp(e,this.buildRequest())}_linkToIdToken(e,t){const r=this.buildRequest();return r.idToken=t,signInWithIdp(e,r)}_getReauthenticationResolver(e){const t=this.buildRequest();return t.autoCreate=!1,signInWithIdp(e,t)}toJSON(){return{signInMethod:this.signInMethod,providerId:this.providerId,pendingToken:this.pendingToken}}static fromJSON(e){const t="string"==typeof e?JSON.parse(e):e,{providerId:r,signInMethod:n,pendingToken:i}=t;return r&&n&&i&&r===n?new SAMLAuthCredential(r,i):null}static _create(e,t){return new SAMLAuthCredential(e,t)}buildRequest(){return{requestUri:"http://localhost",returnSecureToken:!0,pendingToken:this.pendingToken}}}class SAMLAuthProvider extends FederatedAuthProvider{constructor(e){_assert(e.startsWith("saml."),"argument-error"),super(e)}static credentialFromResult(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e)}static credentialFromError(e){return SAMLAuthProvider.samlCredentialFromTaggedObject(e.customData||{})}static credentialFromJSON(e){const t=SAMLAuthCredential.fromJSON(e);return _assert(t,"argument-error"),t}static samlCredentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{pendingToken:t,providerId:r}=e;if(!t||!r)return null;try{return SAMLAuthCredential._create(r,t)}catch(e){return null}}}class TwitterAuthProvider extends BaseOAuthProvider{constructor(){super("twitter.com")}static credential(e,t){return OAuthCredential._fromParams({providerId:TwitterAuthProvider.PROVIDER_ID,signInMethod:TwitterAuthProvider.TWITTER_SIGN_IN_METHOD,oauthToken:e,oauthTokenSecret:t})}static credentialFromResult(e){return TwitterAuthProvider.credentialFromTaggedObject(e)}static credentialFromError(e){return TwitterAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{oauthAccessToken:t,oauthTokenSecret:r}=e;if(!t||!r)return null;try{return TwitterAuthProvider.credential(t,r)}catch(e){return null}}}async function signUp(e,t){return _performSignInRequest(e,"POST","/v1/accounts:signUp",_addTidIfNecessary(e,t))}TwitterAuthProvider.TWITTER_SIGN_IN_METHOD="twitter.com",TwitterAuthProvider.PROVIDER_ID="twitter.com";class UserCredentialImpl{constructor(e){this.user=e.user,this.providerId=e.providerId,this._tokenResponse=e._tokenResponse,this.operationType=e.operationType}static async _fromIdTokenResponse(e,t,r,n=!1){const i=await UserImpl._fromIdTokenResponse(e,r,n),s=providerIdForResponse(r);return new UserCredentialImpl({user:i,providerId:s,_tokenResponse:r,operationType:t})}static async _forOperation(e,t,r){await e._updateTokensIfNecessary(r,!0);const n=providerIdForResponse(r);return new UserCredentialImpl({user:e,providerId:n,_tokenResponse:r,operationType:t})}}function providerIdForResponse(e){return e.providerId?e.providerId:"phoneNumber"in e?"phone":null}async function signInAnonymously(t){var r;if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const n=_castAuth(t);if(await n._initializationPromise,null===(r=n.currentUser)||void 0===r?void 0:r.isAnonymous)return new UserCredentialImpl({user:n.currentUser,providerId:null,operationType:"signIn"});const i=await signUp(n,{returnSecureToken:!0}),s=await UserCredentialImpl._fromIdTokenResponse(n,"signIn",i,!0);return await n._updateCurrentUser(s.user),s}class MultiFactorError extends FirebaseError{constructor(e,t,r,n){var i;super(t.code,t.message),this.operationType=r,this.user=n,Object.setPrototypeOf(this,MultiFactorError.prototype),this.customData={appName:e.name,tenantId:null!==(i=e.tenantId)&&void 0!==i?i:void 0,_serverResponse:t.customData._serverResponse,operationType:r}}static _fromErrorAndOperation(e,t,r,n){return new MultiFactorError(e,t,r,n)}}function _processCredentialSavingMfaContextIfNecessary(e,t,r,n){return("reauthenticate"===t?r._getReauthenticationResolver(e):r._getIdTokenResponse(e)).catch((r=>{if(“auth/multi-factor-auth-required”===r.code)throw MultiFactorError._fromErrorAndOperation(e,r,t,n);throw r}))}function providerDataAsNames(e){return new Set(e.map((({providerId:e})=>e)).filter((e=>!!e)))}async function unlink(e,t){const r=getModularInstance(e);await _assertLinkedStatus(!0,r,t);const{providerUserInfo:n}=await async function deleteLinkedAccounts(e,t){return _performApiRequest(e,”POST”,”/v1/accounts:update”,t)}(r.auth,{idToken:await r.getIdToken(),deleteProvider:[t]}),i=providerDataAsNames(n||[]);return r.providerData=r.providerData.filter((e=>i.has(e.providerId))),i.has(“phone”)||(r.phoneNumber=null),await r.auth._persistUserIfCurrent(r),r}async function _link$1(e,t,r=!1){const n=await _logoutIfInvalidated(e,t._linkToIdToken(e.auth,await e.getIdToken()),r);return UserCredentialImpl._forOperation(e,”link”,n)}async function _assertLinkedStatus(e,t,r){await _reloadWithoutSaving(t);const n=!1===e?”provider-already-linked”:”no-such-provider”;_assert(providerDataAsNames(t.providerData).has(r)===e,t.auth,n)}async function _reauthenticate(t,r,n=!1){const{auth:i}=t;if(e(i.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i));const s=”reauthenticate”;try{const e=await _logoutIfInvalidated(t,_processCredentialSavingMfaContextIfNecessary(i,s,r,t),n);_assert(e.idToken,i,”internal-error”);const o=_parseToken(e.idToken);_assert(o,i,”internal-error”);const{sub:a}=o;return _assert(t.uid===a,i,”user-mismatch”),UserCredentialImpl._forOperation(t,s,e)}catch(e){throw”auth/user-not-found”===(null==e?void 0:e.code)&&_fail(i,”user-mismatch”),e}}async function _signInWithCredential(t,r,n=!1){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=”signIn”,s=await _processCredentialSavingMfaContextIfNecessary(t,i,r),o=await UserCredentialImpl._fromIdTokenResponse(t,i,s);return n||await t._updateCurrentUser(o.user),o}async function signInWithCredential(e,t){return _signInWithCredential(_castAuth(e),t)}async function linkWithCredential(e,t){const r=getModularInstance(e);return await _assertLinkedStatus(!1,r,t.providerId),_link$1(r,t)}async function reauthenticateWithCredential(e,t){return _reauthenticate(getModularInstance(e),t)}async function signInWithCustomToken(t,r){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const n=_castAuth(t),i=await async function signInWithCustomToken$1(e,t){return _performSignInRequest(e,”POST”,”/v1/accounts:signInWithCustomToken”,_addTidIfNecessary(e,t))}(n,{token:r,returnSecureToken:!0}),s=await UserCredentialImpl._fromIdTokenResponse(n,”signIn”,i);return await n._updateCurrentUser(s.user),s}class MultiFactorInfoImpl{constructor(e,t){this.factorId=e,this.uid=t.mfaEnrollmentId,this.enrollmentTime=new Date(t.enrolledAt).toUTCString(),this.displayName=t.displayName}static _fromServerResponse(e,t){return”phoneInfo”in t?PhoneMultiFactorInfoImpl._fromServerResponse(e,t):”totpInfo”in t?TotpMultiFactorInfoImpl._fromServerResponse(e,t):_fail(e,”internal-error”)}}class PhoneMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super(“phone”,e),this.phoneNumber=e.phoneInfo}static _fromServerResponse(e,t){return new PhoneMultiFactorInfoImpl(t)}}class TotpMultiFactorInfoImpl extends MultiFactorInfoImpl{constructor(e){super(“totp”,e)}static _fromServerResponse(e,t){return new TotpMultiFactorInfoImpl(t)}}function _setActionCodeSettingsOnRequest(e,t,r){var n;_assert((null===(n=r.url)||void 0===n?void 0:n.length)>0,e,”invalid-continue-uri”),_assert(void 0===r.dynamicLinkDomain||r.dynamicLinkDomain.length>0,e,”invalid-dynamic-link-domain”),_assert(void 0===r.linkDomain||r.linkDomain.length>0,e,”invalid-hosting-link-domain”),t.continueUrl=r.url,t.dynamicLinkDomain=r.dynamicLinkDomain,t.linkDomain=r.linkDomain,t.canHandleCodeInApp=r.handleCodeInApp,r.iOS&&(_assert(r.iOS.bundleId.length>0,e,”missing-ios-bundle-id”),t.iOSBundleId=r.iOS.bundleId),r.android&&(_assert(r.android.packageName.length>0,e,”missing-android-pkg-name”),t.androidInstallApp=r.android.installApp,t.androidMinimumVersionCode=r.android.minimumVersion,t.androidPackageName=r.android.packageName)}async function recachePasswordPolicy(e){const t=_castAuth(e);t._getPasswordPolicyInternal()&&await t._updatePasswordPolicy()}async function sendPasswordResetEmail(e,t,r){const n=_castAuth(e),i={requestType:”PASSWORD_RESET”,email:t,clientType:”CLIENT_TYPE_WEB”};r&&_setActionCodeSettingsOnRequest(n,i,r),await handleRecaptchaFlow(n,i,”getOobCode”,sendPasswordResetEmail$1,”EMAIL_PASSWORD_PROVIDER”)}async function confirmPasswordReset(e,t,r){await resetPassword(getModularInstance(e),{oobCode:t,newPassword:r}).catch((async t=>{throw”auth/password-does-not-meet-requirements”===t.code&&recachePasswordPolicy(e),t}))}async function applyActionCode(e,t){await async function applyActionCode$1(e,t){return _performApiRequest(e,”POST”,”/v1/accounts:update”,_addTidIfNecessary(e,t))}(getModularInstance(e),{oobCode:t})}async function checkActionCode(e,t){const r=getModularInstance(e),n=await resetPassword(r,{oobCode:t}),i=n.requestType;switch(_assert(i,r,”internal-error”),i){case”EMAIL_SIGNIN”:break;case”VERIFY_AND_CHANGE_EMAIL”:_assert(n.newEmail,r,”internal-error”);break;case”REVERT_SECOND_FACTOR_ADDITION”:_assert(n.mfaInfo,r,”internal-error”);default:_assert(n.email,r,”internal-error”)}let s=null;return n.mfaInfo&&(s=MultiFactorInfoImpl._fromServerResponse(_castAuth(r),n.mfaInfo)),{data:{email:(“VERIFY_AND_CHANGE_EMAIL”===n.requestType?n.newEmail:n.email)||null,previousEmail:(“VERIFY_AND_CHANGE_EMAIL”===n.requestType?n.email:n.newEmail)||null,multiFactorInfo:s},operation:i}}async function verifyPasswordResetCode(e,t){const{data:r}=await checkActionCode(getModularInstance(e),t);return r.email}async function createUserWithEmailAndPassword(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=handleRecaptchaFlow(i,{returnSecureToken:!0,email:r,password:n,clientType:”CLIENT_TYPE_WEB”},”signUpPassword”,signUp,”EMAIL_PASSWORD_PROVIDER”),o=await s.catch((e=>{throw”auth/password-does-not-meet-requirements”===e.code&&recachePasswordPolicy(t),e})),a=await UserCredentialImpl._fromIdTokenResponse(i,”signIn”,o);return await i._updateCurrentUser(a.user),a}function signInWithEmailAndPassword(t,r,n){return e(t.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t)):signInWithCredential(getModularInstance(t),EmailAuthProvider.credential(r,n)).catch((async e=>{throw”auth/password-does-not-meet-requirements”===e.code&&recachePasswordPolicy(t),e}))}async function sendSignInLinkToEmail(e,t,r){const n=_castAuth(e),i={requestType:”EMAIL_SIGNIN”,email:t,clientType:”CLIENT_TYPE_WEB”};!function setActionCodeSettings(e,t){_assert(t.handleCodeInApp,n,”argument-error”),t&&_setActionCodeSettingsOnRequest(n,e,t)}(i,r),await handleRecaptchaFlow(n,i,”getOobCode”,sendSignInLinkToEmail$1,”EMAIL_PASSWORD_PROVIDER”)}function isSignInWithEmailLink(e,t){const r=ActionCodeURL.parseLink(t);return”EMAIL_SIGNIN”===(null==r?void 0:r.operation)}async function signInWithEmailLink(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=getModularInstance(t),s=EmailAuthProvider.credentialWithLink(r,n||_getCurrentUrl());return _assert(s._tenantId===(i.tenantId||null),i,”tenant-id-mismatch”),signInWithCredential(i,s)}async function fetchSignInMethodsForEmail(e,t){const r={identifier:t,continueUri:_isHttpOrHttps()?_getCurrentUrl():”http://localhost”},{signinMethods:n}=await async function createAuthUri(e,t){return _performApiRequest(e,”POST”,”/v1/accounts:createAuthUri”,_addTidIfNecessary(e,t))}(getModularInstance(e),r);return n||[]}async function sendEmailVerification(e,t){const r=getModularInstance(e),n={requestType:”VERIFY_EMAIL”,idToken:await e.getIdToken()};t&&_setActionCodeSettingsOnRequest(r.auth,n,t);const{email:i}=await async function sendEmailVerification$1(e,t){return sendOobCode(e,t)}(r.auth,n);i!==e.email&&await e.reload()}async function verifyBeforeUpdateEmail(e,t,r){const n=getModularInstance(e),i={requestType:”VERIFY_AND_CHANGE_EMAIL”,idToken:await e.getIdToken(),newEmail:t};r&&_setActionCodeSettingsOnRequest(n.auth,i,r);const{email:s}=await async function verifyAndChangeEmail(e,t){return sendOobCode(e,t)}(n.auth,i);s!==e.email&&await e.reload()}async function updateProfile(e,{displayName:t,photoURL:r}){if(void 0===t&&void 0===r)return;const n=getModularInstance(e),i={idToken:await n.getIdToken(),displayName:t,photoUrl:r,returnSecureToken:!0},s=await _logoutIfInvalidated(n,async function updateProfile$1(e,t){return _performApiRequest(e,”POST”,”/v1/accounts:update”,t)}(n.auth,i));n.displayName=s.displayName||null,n.photoURL=s.photoUrl||null;const o=n.providerData.find((({providerId:e})=>”password”===e));o&&(o.displayName=n.displayName,o.photoURL=n.photoURL),await n._updateTokensIfNecessary(s)}function updateEmail(t,r){const n=getModularInstance(t);return e(n.auth.app)?Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth)):updateEmailOrPassword(n,r,null)}function updatePassword(e,t){return updateEmailOrPassword(getModularInstance(e),null,t)}async function updateEmailOrPassword(e,t,r){const{auth:n}=e,i={idToken:await e.getIdToken(),returnSecureToken:!0};t&&(i.email=t),r&&(i.password=r);const s=await _logoutIfInvalidated(e,async function updateEmailPassword(e,t){return _performApiRequest(e,”POST”,”/v1/accounts:update”,t)}(n,i));await e._updateTokensIfNecessary(s,!0)}class GenericAdditionalUserInfo{constructor(e,t,r={}){this.isNewUser=e,this.providerId=t,this.profile=r}}class FederatedAdditionalUserInfoWithUsername extends GenericAdditionalUserInfo{constructor(e,t,r,n){super(e,t,r),this.username=n}}class FacebookAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,”facebook.com”,t)}}class GithubAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t){super(e,”github.com”,t,”string”==typeof(null==t?void 0:t.login)?null==t?void 0:t.login:null)}}class GoogleAdditionalUserInfo extends GenericAdditionalUserInfo{constructor(e,t){super(e,”google.com”,t)}}class TwitterAdditionalUserInfo extends FederatedAdditionalUserInfoWithUsername{constructor(e,t,r){super(e,”twitter.com”,t,r)}}function getAdditionalUserInfo(e){const{user:t,_tokenResponse:r}=e;return t.isAnonymous&&!r?{providerId:null,isNewUser:!1,profile:null}:function _fromIdTokenResponse(e){var t,r;if(!e)return null;const{providerId:n}=e,i=e.rawUserInfo?JSON.parse(e.rawUserInfo):{},s=e.isNewUser||”identitytoolkit#SignupNewUserResponse”===e.kind;if(!n&&(null==e?void 0:e.idToken)){const n=null===(r=null===(t=_parseToken(e.idToken))||void 0===t?void 0:t.firebase)||void 0===r?void 0:r.sign_in_provider;if(n)return new GenericAdditionalUserInfo(s,”anonymous”!==n&&”custom”!==n?n:null)}if(!n)return null;switch(n){case”facebook.com”:return new FacebookAdditionalUserInfo(s,i);case”github.com”:return new GithubAdditionalUserInfo(s,i);case”google.com”:return new GoogleAdditionalUserInfo(s,i);case”twitter.com”:return new TwitterAdditionalUserInfo(s,i,e.screenName||null);case”custom”:case”anonymous”:return new GenericAdditionalUserInfo(s,null);default:return new GenericAdditionalUserInfo(s,n,i)}}(r)}function setPersistence(e,t){return getModularInstance(e).setPersistence(t)}function initializeRecaptchaConfig(e){return _initializeRecaptchaConfig(e)}async function validatePassword(e,t){return _castAuth(e).validatePassword(t)}function onIdTokenChanged(e,t,r,n){return getModularInstance(e).onIdTokenChanged(t,r,n)}function beforeAuthStateChanged(e,t,r){return getModularInstance(e).beforeAuthStateChanged(t,r)}function onAuthStateChanged(e,t,r,n){return getModularInstance(e).onAuthStateChanged(t,r,n)}function useDeviceLanguage(e){getModularInstance(e).useDeviceLanguage()}function updateCurrentUser(e,t){return getModularInstance(e).updateCurrentUser(t)}function signOut(e){return getModularInstance(e).signOut()}function revokeAccessToken(e,t){return _castAuth(e).revokeAccessToken(t)}async function deleteUser(e){return getModularInstance(e).delete()}class MultiFactorSessionImpl{constructor(e,t,r){this.type=e,this.credential=t,this.user=r}static _fromIdtoken(e,t){return new MultiFactorSessionImpl(“enroll”,e,t)}static _fromMfaPendingCredential(e){return new MultiFactorSessionImpl(“signin”,e)}toJSON(){const e=”enroll”===this.type?”idToken”:”pendingCredential”;return{multiFactorSession:{[e]:this.credential}}}static fromJSON(e){var t,r;if(null==e?void 0:e.multiFactorSession){if(null===(t=e.multiFactorSession)||void 0===t?void 0:t.pendingCredential)return MultiFactorSessionImpl._fromMfaPendingCredential(e.multiFactorSession.pendingCredential);if(null===(r=e.multiFactorSession)||void 0===r?void 0:r.idToken)return MultiFactorSessionImpl._fromIdtoken(e.multiFactorSession.idToken)}return null}}class MultiFactorResolverImpl{constructor(e,t,r){this.session=e,this.hints=t,this.signInResolver=r}static _fromError(e,t){const r=_castAuth(e),n=t.customData._serverResponse,i=(n.mfaInfo||[]).map((e=>MultiFactorInfoImpl._fromServerResponse(r,e)));_assert(n.mfaPendingCredential,r,”internal-error”);const s=MultiFactorSessionImpl._fromMfaPendingCredential(n.mfaPendingCredential);return new MultiFactorResolverImpl(s,i,(async e=>{const i=await e._process(r,s);delete n.mfaInfo,delete n.mfaPendingCredential;const o=Object.assign(Object.assign({},n),{idToken:i.idToken,refreshToken:i.refreshToken});switch(t.operationType){case”signIn”:const e=await UserCredentialImpl._fromIdTokenResponse(r,t.operationType,o);return await r._updateCurrentUser(e.user),e;case”reauthenticate”:return _assert(t.user,r,”internal-error”),UserCredentialImpl._forOperation(t.user,t.operationType,o);default:_fail(r,”internal-error”)}}))}async resolveSignIn(e){const t=e;return this.signInResolver(t)}}function getMultiFactorResolver(e,t){var r;const n=getModularInstance(e),i=t;return _assert(t.customData.operationType,n,”argument-error”),_assert(null===(r=i.customData._serverResponse)||void 0===r?void 0:r.mfaPendingCredential,n,”argument-error”),MultiFactorResolverImpl._fromError(n,i)}function startEnrollPhoneMfa(e,t){return _performApiRequest(e,”POST”,”/v2/accounts/mfaEnrollment:start”,_addTidIfNecessary(e,t))}class MultiFactorUserImpl{constructor(e){this.user=e,this.enrolledFactors=[],e._onReload((t=>{t.mfaInfo&&(this.enrolledFactors=t.mfaInfo.map((t=>MultiFactorInfoImpl._fromServerResponse(e.auth,t))))}))}static _fromUser(e){return new MultiFactorUserImpl(e)}async getSession(){return MultiFactorSessionImpl._fromIdtoken(await this.user.getIdToken(),this.user)}async enroll(e,t){const r=e,n=await this.getSession(),i=await _logoutIfInvalidated(this.user,r._process(this.user.auth,n,t));return await this.user._updateTokensIfNecessary(i),this.user.reload()}async unenroll(e){const t=”string”==typeof e?e:e.uid,r=await this.user.getIdToken();try{const e=await _logoutIfInvalidated(this.user,function withdrawMfa(e,t){return _performApiRequest(e,”POST”,”/v2/accounts/mfaEnrollment:withdraw”,_addTidIfNecessary(e,t))}(this.user.auth,{idToken:r,mfaEnrollmentId:t}));this.enrolledFactors=this.enrolledFactors.filter((({uid:e})=>e!==t)),await this.user._updateTokensIfNecessary(e),await this.user.reload()}catch(e){throw e}}}const b=new WeakMap;function multiFactor(e){const t=getModularInstance(e);return b.has(t)||b.set(t,MultiFactorUserImpl._fromUser(t)),b.get(t)}const O=”__sak”;class BrowserPersistenceClass{constructor(e,t){this.storageRetriever=e,this.type=t}_isAvailable(){try{return this.storage?(this.storage.setItem(O,”1″),this.storage.removeItem(O),Promise.resolve(!0)):Promise.resolve(!1)}catch(e){return Promise.resolve(!1)}}_set(e,t){return this.storage.setItem(e,JSON.stringify(t)),Promise.resolve()}_get(e){const t=this.storage.getItem(e);return Promise.resolve(t?JSON.parse(t):null)}_remove(e){return this.storage.removeItem(e),Promise.resolve()}get storage(){return this.storageRetriever()}}class BrowserLocalPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.localStorage),”LOCAL”),this.boundEventHandler=(e,t)=>this.onStorageEvent(e,t),this.listeners={},this.localCache={},this.pollTimer=null,this.fallbackToPolling=_isMobileBrowser(),this._shouldAllowMigration=!0}forAllChangedKeys(e){for(const t of Object.keys(this.listeners)){const r=this.storage.getItem(t),n=this.localCache[t];r!==n&&e(t,n,r)}}onStorageEvent(e,t=!1){if(!e.key)return void this.forAllChangedKeys(((e,t,r)=>{this.notifyListeners(e,r)}));const r=e.key;t?this.detachListener():this.stopPolling();const triggerListeners=()=>{const e=this.storage.getItem(r);(t||this.localCache[r]!==e)&&this.notifyListeners(r,e)},n=this.storage.getItem(r);_isIE10()&&n!==e.newValue&&e.newValue!==e.oldValue?setTimeout(triggerListeners,10):triggerListeners()}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const e of Array.from(r))e(t?JSON.parse(t):t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((()=>{this.forAllChangedKeys(((e,t,r)=>{this.onStorageEvent(new StorageEvent(“storage”,{key:e,oldValue:t,newValue:r}),!0)}))}),1e3)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}attachListener(){window.addEventListener(“storage”,this.boundEventHandler)}detachListener(){window.removeEventListener(“storage”,this.boundEventHandler)}_addListener(e,t){0===Object.keys(this.listeners).length&&(this.fallbackToPolling?this.startPolling():this.attachListener()),this.listeners[e]||(this.listeners[e]=new Set,this.localCache[e]=this.storage.getItem(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&(this.detachListener(),this.stopPolling())}async _set(e,t){await super._set(e,t),this.localCache[e]=JSON.stringify(t)}async _get(e){const t=await super._get(e);return this.localCache[e]=JSON.stringify(t),t}async _remove(e){await super._remove(e),delete this.localCache[e]}}BrowserLocalPersistence.type=”LOCAL”;const N=BrowserLocalPersistence;function getDocumentCookie(e){var t,r;const n=e.replace(/[\\^$.*+?()[\]{}|]/g,”\\$&”),i=RegExp(`${n}=([^;]+)`);return null!==(r=null===(t=document.cookie.match(i))||void 0===t?void 0:t[1])&&void 0!==r?r:null}function getCookieName(e){return`${“http:”===window.location.protocol?”__dev_”:”__HOST-“}FIREBASE_${e.split(“:”)[3]}`}class CookiePersistence{constructor(){this.type=”COOKIE”,this.listenerUnsubscribes=new Map}_getFinalTarget(e){if(void 0===typeof window)return e;const t=new URL(`${window.location.origin}/__cookies__`);return t.searchParams.set(“finalTarget”,e),t}async _isAvailable(){var e;return!(“boolean”==typeof isSecureContext&&!isSecureContext)&&(“undefined”!=typeof navigator&&”undefined”!=typeof document&&(null===(e=navigator.cookieEnabled)||void 0===e||e))}async _set(e,t){}async _get(e){if(!this._isAvailable())return null;const t=getCookieName(e);if(window.cookieStore){const e=await window.cookieStore.get(t);return null==e?void 0:e.value}return getDocumentCookie(t)}async _remove(e){if(!this._isAvailable())return;if(!await this._get(e))return;const t=getCookieName(e);document.cookie=`${t}=;Max-Age=34560000;Partitioned;Secure;SameSite=Strict;Path=/;Priority=High`,await fetch(“/__cookies__”,{method:”DELETE”}).catch((()=>{}))}_addListener(e,t){if(!this._isAvailable())return;const r=getCookieName(e);if(window.cookieStore){const cb=e=>{const n=e.changed.find((e=>e.name===r));n&&t(n.value);e.deleted.find((e=>e.name===r))&&t(null)},unsubscribe=()=>window.cookieStore.removeEventListener(“change”,cb);return this.listenerUnsubscribes.set(t,unsubscribe),window.cookieStore.addEventListener(“change”,cb)}let n=getDocumentCookie(r);const i=setInterval((()=>{const e=getDocumentCookie(r);e!==n&&(t(e),n=e)}),1e3);this.listenerUnsubscribes.set(t,(()=>clearInterval(i)))}_removeListener(e,t){const r=this.listenerUnsubscribes.get(t);r&&(r(),this.listenerUnsubscribes.delete(t))}}CookiePersistence.type=”COOKIE”;const D=CookiePersistence;class BrowserSessionPersistence extends BrowserPersistenceClass{constructor(){super((()=>window.sessionStorage),”SESSION”)}_addListener(e,t){}_removeListener(e,t){}}BrowserSessionPersistence.type=”SESSION”;const L=BrowserSessionPersistence;class Receiver{constructor(e){this.eventTarget=e,this.handlersMap={},this.boundEventHandler=this.handleEvent.bind(this)}static _getInstance(e){const t=this.receivers.find((t=>t.isListeningto(e)));if(t)return t;const r=new Receiver(e);return this.receivers.push(r),r}isListeningto(e){return this.eventTarget===e}async handleEvent(e){const t=e,{eventId:r,eventType:n,data:i}=t.data,s=this.handlersMap[n];if(!(null==s?void 0:s.size))return;t.ports[0].postMessage({status:”ack”,eventId:r,eventType:n});const o=Array.from(s).map((async e=>e(t.origin,i))),a=await function _allSettled(e){return Promise.all(e.map((async e=>{try{return{fulfilled:!0,value:await e}}catch(e){return{fulfilled:!1,reason:e}}})))}(o);t.ports[0].postMessage({status:”done”,eventId:r,eventType:n,response:a})}_subscribe(e,t){0===Object.keys(this.handlersMap).length&&this.eventTarget.addEventListener(“message”,this.boundEventHandler),this.handlersMap[e]||(this.handlersMap[e]=new Set),this.handlersMap[e].add(t)}_unsubscribe(e,t){this.handlersMap[e]&&t&&this.handlersMap[e].delete(t),t&&0!==this.handlersMap[e].size||delete this.handlersMap[e],0===Object.keys(this.handlersMap).length&&this.eventTarget.removeEventListener(“message”,this.boundEventHandler)}}function _generateEventId(e=””,t=10){let r=””;for(let e=0;e{const c=_generateEventId(“”,20);n.port1.start();const u=setTimeout((()=>{a(new Error(“unsupported_event”))}),r);s={messageChannel:n,onMessage(e){const t=e;if(t.data.eventId===c)switch(t.data.status){case”ack”:clearTimeout(u),i=setTimeout((()=>{a(new Error(“timeout”))}),3e3);break;case”done”:clearTimeout(i),o(t.data.response);break;default:clearTimeout(u),clearTimeout(i),a(new Error(“invalid_response”))}}},this.handlers.add(s),n.port1.addEventListener(“message”,s.onMessage),this.target.postMessage({eventType:e,eventId:c,data:t},[n.port2])})).finally((()=>{s&&this.removeMessageHandler(s)}))}}function _window(){return window}function _isWorker(){return void 0!==_window().WorkerGlobalScope&&”function”==typeof _window().importScripts}const M=”firebaseLocalStorageDb”,U=”firebaseLocalStorage”,F=”fbase_key”;class DBPromise{constructor(e){this.request=e}toPromise(){return new Promise(((e,t)=>{this.request.addEventListener(“success”,(()=>{e(this.request.result)})),this.request.addEventListener(“error”,(()=>{t(this.request.error)}))}))}}function getObjectStore(e,t){return e.transaction([U],t?”readwrite”:”readonly”).objectStore(U)}function _openDatabase(){const e=indexedDB.open(M,1);return new Promise(((t,r)=>{e.addEventListener(“error”,(()=>{r(e.error)})),e.addEventListener(“upgradeneeded”,(()=>{const t=e.result;try{t.createObjectStore(U,{keyPath:F})}catch(e){r(e)}})),e.addEventListener(“success”,(async()=>{const r=e.result;r.objectStoreNames.contains(U)?t(r):(r.close(),await function _deleteDatabase(){const e=indexedDB.deleteDatabase(M);return new DBPromise(e).toPromise()}(),t(await _openDatabase()))}))}))}async function _putObject(e,t,r){const n=getObjectStore(e,!0).put({[F]:t,value:r});return new DBPromise(n).toPromise()}function _deleteObject(e,t){const r=getObjectStore(e,!0).delete(t);return new DBPromise(r).toPromise()}class IndexedDBLocalPersistence{constructor(){this.type=”LOCAL”,this._shouldAllowMigration=!0,this.listeners={},this.localCache={},this.pollTimer=null,this.pendingWrites=0,this.receiver=null,this.sender=null,this.serviceWorkerReceiverAvailable=!1,this.activeServiceWorker=null,this._workerInitializationPromise=this.initializeServiceWorkerMessaging().then((()=>{}),(()=>{}))}async _openDb(){return this.db||(this.db=await _openDatabase()),this.db}async _withRetries(e){let t=0;for(;;)try{const t=await this._openDb();return await e(t)}catch(e){if(t++>3)throw e;this.db&&(this.db.close(),this.db=void 0)}}async initializeServiceWorkerMessaging(){return _isWorker()?this.initializeReceiver():this.initializeSender()}async initializeReceiver(){this.receiver=Receiver._getInstance(function _getWorkerGlobalScope(){return _isWorker()?self:null}()),this.receiver._subscribe(“keyChanged”,(async(e,t)=>({keyProcessed:(await this._poll()).includes(t.key)}))),this.receiver._subscribe(“ping”,(async(e,t)=>[“keyChanged”]))}async initializeSender(){var e,t;if(this.activeServiceWorker=await async function _getActiveServiceWorker(){if(!(null===navigator||void 0===navigator?void 0:navigator.serviceWorker))return null;try{return(await navigator.serviceWorker.ready).active}catch(e){return null}}(),!this.activeServiceWorker)return;this.sender=new Sender(this.activeServiceWorker);const r=await this.sender._send(“ping”,{},800);r&&(null===(e=r[0])||void 0===e?void 0:e.fulfilled)&&(null===(t=r[0])||void 0===t?void 0:t.value.includes(“keyChanged”))&&(this.serviceWorkerReceiverAvailable=!0)}async notifyServiceWorker(e){if(this.sender&&this.activeServiceWorker&&function _getServiceWorkerController(){var e;return(null===(e=null===navigator||void 0===navigator?void 0:navigator.serviceWorker)||void 0===e?void 0:e.controller)||null}()===this.activeServiceWorker)try{await this.sender._send(“keyChanged”,{key:e},this.serviceWorkerReceiverAvailable?800:50)}catch(e){}}async _isAvailable(){try{if(!indexedDB)return!1;const e=await _openDatabase();return await _putObject(e,O,”1″),await _deleteObject(e,O),!0}catch(e){}return!1}async _withPendingWrite(e){this.pendingWrites++;try{await e()}finally{this.pendingWrites–}}async _set(e,t){return this._withPendingWrite((async()=>(await this._withRetries((r=>_putObject(r,e,t))),this.localCache[e]=t,this.notifyServiceWorker(e))))}async _get(e){const t=await this._withRetries((t=>async function getObject(e,t){const r=getObjectStore(e,!1).get(t),n=await new DBPromise(r).toPromise();return void 0===n?null:n.value}(t,e)));return this.localCache[e]=t,t}async _remove(e){return this._withPendingWrite((async()=>(await this._withRetries((t=>_deleteObject(t,e))),delete this.localCache[e],this.notifyServiceWorker(e))))}async _poll(){const e=await this._withRetries((e=>{const t=getObjectStore(e,!1).getAll();return new DBPromise(t).toPromise()}));if(!e)return[];if(0!==this.pendingWrites)return[];const t=[],r=new Set;if(0!==e.length)for(const{fbase_key:n,value:i}of e)r.add(n),JSON.stringify(this.localCache[n])!==JSON.stringify(i)&&(this.notifyListeners(n,i),t.push(n));for(const e of Object.keys(this.localCache))this.localCache[e]&&!r.has(e)&&(this.notifyListeners(e,null),t.push(e));return t}notifyListeners(e,t){this.localCache[e]=t;const r=this.listeners[e];if(r)for(const e of Array.from(r))e(t)}startPolling(){this.stopPolling(),this.pollTimer=setInterval((async()=>this._poll()),800)}stopPolling(){this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}_addListener(e,t){0===Object.keys(this.listeners).length&&this.startPolling(),this.listeners[e]||(this.listeners[e]=new Set,this._get(e)),this.listeners[e].add(t)}_removeListener(e,t){this.listeners[e]&&(this.listeners[e].delete(t),0===this.listeners[e].size&&delete this.listeners[e]),0===Object.keys(this.listeners).length&&this.stopPolling()}}IndexedDBLocalPersistence.type=”LOCAL”;const V=IndexedDBLocalPersistence;function startSignInPhoneMfa(e,t){return _performApiRequest(e,”POST”,”/v2/accounts/mfaSignIn:start”,_addTidIfNecessary(e,t))}const W=_generateCallbackName(“rcb”),x=new Delay(3e4,6e4);class ReCaptchaLoaderImpl{constructor(){var e;this.hostLanguage=””,this.counter=0,this.librarySeparatelyLoaded=!!(null===(e=_window().grecaptcha)||void 0===e?void 0:e.render)}load(e,t=””){return _assert(function isHostLanguageValid(e){return e.length<=6&&/^\s*[a-zA-Z0-9\-]*\s*$/.test(e)}(t),e,"argument-error"),this.shouldResolveImmediately(t)&&isV2(_window().grecaptcha)?Promise.resolve(_window().grecaptcha):new Promise(((r,n)=>{const i=_window().setTimeout((()=>{n(_createError(e,”network-request-failed”))}),x.get());_window()[W]=()=>{_window().clearTimeout(i),delete _window()[W];const s=_window().grecaptcha;if(!s||!isV2(s))return void n(_createError(e,”internal-error”));const o=s.render;s.render=(e,t)=>{const r=o(e,t);return this.counter++,r},this.hostLanguage=t,r(s)};_loadJS(`${function _recaptchaV2ScriptUrl(){return P.recaptchaV2Script}()}?${querystring({onload:W,render:”explicit”,hl:t})}`).catch((()=>{clearTimeout(i),n(_createError(e,”internal-error”))}))}))}clearedOneInstance(){this.counter–}shouldResolveImmediately(e){var t;return!!(null===(t=_window().grecaptcha)||void 0===t?void 0:t.render)&&(e===this.hostLanguage||this.counter>0||this.librarySeparatelyLoaded)}}class MockReCaptchaLoaderImpl{async load(e){return new MockReCaptcha(e)}clearedOneInstance(){}}const H=”recaptcha”,j={theme:”light”,type:”image”};class RecaptchaVerifier{constructor(e,t,r=Object.assign({},j)){this.parameters=r,this.type=H,this.destroyed=!1,this.widgetId=null,this.tokenChangeListeners=new Set,this.renderPromise=null,this.recaptcha=null,this.auth=_castAuth(e),this.isInvisible=”invisible”===this.parameters.size,_assert(“undefined”!=typeof document,this.auth,”operation-not-supported-in-this-environment”);const n=”string”==typeof t?document.getElementById(t):t;_assert(n,this.auth,”argument-error”),this.container=n,this.parameters.callback=this.makeTokenCallback(this.parameters.callback),this._recaptchaLoader=this.auth.settings.appVerificationDisabledForTesting?new MockReCaptchaLoaderImpl:new ReCaptchaLoaderImpl,this.validateStartingState()}async verify(){this.assertNotDestroyed();const e=await this.render(),t=this.getAssertedRecaptcha(),r=t.getResponse(e);return r||new Promise((r=>{const tokenChange=e=>{e&&(this.tokenChangeListeners.delete(tokenChange),r(e))};this.tokenChangeListeners.add(tokenChange),this.isInvisible&&t.execute(e)}))}render(){try{this.assertNotDestroyed()}catch(e){return Promise.reject(e)}return this.renderPromise||(this.renderPromise=this.makeRenderPromise().catch((e=>{throw this.renderPromise=null,e}))),this.renderPromise}_reset(){this.assertNotDestroyed(),null!==this.widgetId&&this.getAssertedRecaptcha().reset(this.widgetId)}clear(){this.assertNotDestroyed(),this.destroyed=!0,this._recaptchaLoader.clearedOneInstance(),this.isInvisible||this.container.childNodes.forEach((e=>{this.container.removeChild(e)}))}validateStartingState(){_assert(!this.parameters.sitekey,this.auth,”argument-error”),_assert(this.isInvisible||!this.container.hasChildNodes(),this.auth,”argument-error”),_assert(“undefined”!=typeof document,this.auth,”operation-not-supported-in-this-environment”)}makeTokenCallback(e){return t=>{if(this.tokenChangeListeners.forEach((e=>e(t))),”function”==typeof e)e(t);else if(“string”==typeof e){const r=_window()[e];”function”==typeof r&&r(t)}}}assertNotDestroyed(){_assert(!this.destroyed,this.auth,”internal-error”)}async makeRenderPromise(){if(await this.init(),!this.widgetId){let e=this.container;if(!this.isInvisible){const t=document.createElement(“div”);e.appendChild(t),e=t}this.widgetId=this.getAssertedRecaptcha().render(e,this.parameters)}return this.widgetId}async init(){_assert(_isHttpOrHttps()&&!_isWorker(),this.auth,”internal-error”),await function domReady(){let e=null;return new Promise((t=>{“complete”!==document.readyState?(e=()=>t(),window.addEventListener(“load”,e)):t()})).catch((t=>{throw e&&window.removeEventListener(“load”,e),t}))}(),this.recaptcha=await this._recaptchaLoader.load(this.auth,this.auth.languageCode||void 0);const e=await async function getRecaptchaParams(e){return(await _performApiRequest(e,”GET”,”/v1/recaptchaParams”)).recaptchaSiteKey||””}(this.auth);_assert(e,this.auth,”internal-error”),this.parameters.sitekey=e}getAssertedRecaptcha(){return _assert(this.recaptcha,this.auth,”internal-error”),this.recaptcha}}class ConfirmationResultImpl{constructor(e,t){this.verificationId=e,this.onConfirmation=t}confirm(e){const t=PhoneAuthCredential._fromVerification(this.verificationId,e);return this.onConfirmation(t)}}async function signInWithPhoneNumber(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=await _verifyPhoneNumber(i,r,getModularInstance(n));return new ConfirmationResultImpl(s,(e=>signInWithCredential(i,e)))}async function linkWithPhoneNumber(e,t,r){const n=getModularInstance(e);await _assertLinkedStatus(!1,n,”phone”);const i=await _verifyPhoneNumber(n.auth,t,getModularInstance(r));return new ConfirmationResultImpl(i,(e=>linkWithCredential(n,e)))}async function reauthenticateWithPhoneNumber(t,r,n){const i=getModularInstance(t);if(e(i.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i.auth));const s=await _verifyPhoneNumber(i.auth,r,getModularInstance(n));return new ConfirmationResultImpl(s,(e=>reauthenticateWithCredential(i,e)))}async function _verifyPhoneNumber(e,t,r){var n;if(!e._getRecaptchaConfig())try{await _initializeRecaptchaConfig(e)}catch(e){console.log(“Failed to initialize reCAPTCHA Enterprise config. Triggering the reCAPTCHA v2 verification.”)}try{let i;if(i=”string”==typeof t?{phoneNumber:t}:t,”session”in i){const t=i.session;if(“phoneNumber”in i){_assert(“enroll”===t.type,e,”internal-error”);const n={idToken:t.credential,phoneEnrollmentInfo:{phoneNumber:i.phoneNumber,clientType:”CLIENT_TYPE_WEB”}},s=handleRecaptchaFlow(e,n,”mfaSmsEnrollment”,(async(e,t)=>{if(t.phoneEnrollmentInfo.captchaResponse===k){_assert((null==r?void 0:r.type)===H,e,”argument-error”);return startEnrollPhoneMfa(e,await injectRecaptchaV2Token(e,t,r))}return startEnrollPhoneMfa(e,t)}),”PHONE_PROVIDER”);return(await s.catch((e=>Promise.reject(e)))).phoneSessionInfo.sessionInfo}{_assert(“signin”===t.type,e,”internal-error”);const s=(null===(n=i.multiFactorHint)||void 0===n?void 0:n.uid)||i.multiFactorUid;_assert(s,e,”missing-multi-factor-info”);const o={mfaPendingCredential:t.credential,mfaEnrollmentId:s,phoneSignInInfo:{clientType:”CLIENT_TYPE_WEB”}},a=handleRecaptchaFlow(e,o,”mfaSmsSignIn”,(async(e,t)=>{if(t.phoneSignInInfo.captchaResponse===k){_assert((null==r?void 0:r.type)===H,e,”argument-error”);return startSignInPhoneMfa(e,await injectRecaptchaV2Token(e,t,r))}return startSignInPhoneMfa(e,t)}),”PHONE_PROVIDER”);return(await a.catch((e=>Promise.reject(e)))).phoneResponseInfo.sessionInfo}}{const t={phoneNumber:i.phoneNumber,clientType:”CLIENT_TYPE_WEB”},n=handleRecaptchaFlow(e,t,”sendVerificationCode”,(async(e,t)=>{if(t.captchaResponse===k){_assert((null==r?void 0:r.type)===H,e,”argument-error”);return sendPhoneVerificationCode(e,await injectRecaptchaV2Token(e,t,r))}return sendPhoneVerificationCode(e,t)}),”PHONE_PROVIDER”);return(await n.catch((e=>Promise.reject(e)))).sessionInfo}}finally{null==r||r._reset()}}async function updatePhoneNumber(t,r){const n=getModularInstance(t);if(e(n.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(n.auth));await _link$1(n,r)}async function injectRecaptchaV2Token(e,t,r){_assert(r.type===H,e,”argument-error”);const n=await r.verify();_assert(“string”==typeof n,e,”argument-error”);const i=Object.assign({},t);if(“phoneEnrollmentInfo”in i){const e=i.phoneEnrollmentInfo.phoneNumber,t=i.phoneEnrollmentInfo.captchaResponse,r=i.phoneEnrollmentInfo.clientType,s=i.phoneEnrollmentInfo.recaptchaVersion;return Object.assign(i,{phoneEnrollmentInfo:{phoneNumber:e,recaptchaToken:n,captchaResponse:t,clientType:r,recaptchaVersion:s}}),i}if(“phoneSignInInfo”in i){const e=i.phoneSignInInfo.captchaResponse,t=i.phoneSignInInfo.clientType,r=i.phoneSignInInfo.recaptchaVersion;return Object.assign(i,{phoneSignInInfo:{recaptchaToken:n,captchaResponse:e,clientType:t,recaptchaVersion:r}}),i}return Object.assign(i,{recaptchaToken:n}),i}class PhoneAuthProvider{constructor(e){this.providerId=PhoneAuthProvider.PROVIDER_ID,this.auth=_castAuth(e)}verifyPhoneNumber(e,t){return _verifyPhoneNumber(this.auth,e,getModularInstance(t))}static credential(e,t){return PhoneAuthCredential._fromVerification(e,t)}static credentialFromResult(e){const t=e;return PhoneAuthProvider.credentialFromTaggedObject(t)}static credentialFromError(e){return PhoneAuthProvider.credentialFromTaggedObject(e.customData||{})}static credentialFromTaggedObject({_tokenResponse:e}){if(!e)return null;const{phoneNumber:t,temporaryProof:r}=e;return t&&r?PhoneAuthCredential._fromTokenResponse(t,r):null}}function _withDefaultResolver(e,t){return t?_getInstance(t):(_assert(e._popupRedirectResolver,e,”argument-error”),e._popupRedirectResolver)}PhoneAuthProvider.PROVIDER_ID=”phone”,PhoneAuthProvider.PHONE_SIGN_IN_METHOD=”phone”;class IdpCredential extends AuthCredential{constructor(e){super(“custom”,”custom”),this.params=e}_getIdTokenResponse(e){return signInWithIdp(e,this._buildIdpRequest())}_linkToIdToken(e,t){return signInWithIdp(e,this._buildIdpRequest(t))}_getReauthenticationResolver(e){return signInWithIdp(e,this._buildIdpRequest())}_buildIdpRequest(e){const t={requestUri:this.params.requestUri,sessionId:this.params.sessionId,postBody:this.params.postBody,tenantId:this.params.tenantId,pendingToken:this.params.pendingToken,returnSecureToken:!0,returnIdpCredential:!0};return e&&(t.idToken=e),t}}function _signIn(e){return _signInWithCredential(e.auth,new IdpCredential(e),e.bypassAuthState)}function _reauth(e){const{auth:t,user:r}=e;return _assert(r,t,”internal-error”),_reauthenticate(r,new IdpCredential(e),e.bypassAuthState)}async function _link(e){const{auth:t,user:r}=e;return _assert(r,t,”internal-error”),_link$1(r,new IdpCredential(e),e.bypassAuthState)}class AbstractPopupRedirectOperation{constructor(e,t,r,n,i=!1){this.auth=e,this.resolver=r,this.user=n,this.bypassAuthState=i,this.pendingPromise=null,this.eventManager=null,this.filter=Array.isArray(t)?t:[t]}execute(){return new Promise((async(e,t)=>{this.pendingPromise={resolve:e,reject:t};try{this.eventManager=await this.resolver._initialize(this.auth),await this.onExecution(),this.eventManager.registerConsumer(this)}catch(e){this.reject(e)}}))}async onAuthEvent(e){const{urlResponse:t,sessionId:r,postBody:n,tenantId:i,error:s,type:o}=e;if(s)return void this.reject(s);const a={auth:this.auth,requestUri:t,sessionId:r,tenantId:i||void 0,postBody:n||void 0,user:this.user,bypassAuthState:this.bypassAuthState};try{this.resolve(await this.getIdpTask(o)(a))}catch(e){this.reject(e)}}onError(e){this.reject(e)}getIdpTask(e){switch(e){case”signInViaPopup”:case”signInViaRedirect”:return _signIn;case”linkViaPopup”:case”linkViaRedirect”:return _link;case”reauthViaPopup”:case”reauthViaRedirect”:return _reauth;default:_fail(this.auth,”internal-error”)}}resolve(e){debugAssert(this.pendingPromise,”Pending promise was never set”),this.pendingPromise.resolve(e),this.unregisterAndCleanUp()}reject(e){debugAssert(this.pendingPromise,”Pending promise was never set”),this.pendingPromise.reject(e),this.unregisterAndCleanUp()}unregisterAndCleanUp(){this.eventManager&&this.eventManager.unregisterConsumer(this),this.pendingPromise=null,this.cleanUp()}}const q=new Delay(2e3,1e4);async function signInWithPopup(t,r,n){if(e(t.app))return Promise.reject(_createError(t,”operation-not-supported-in-this-environment”));const i=_castAuth(t);_assertInstanceOf(t,r,FederatedAuthProvider);const s=_withDefaultResolver(i,n);return new PopupOperation(i,”signInViaPopup”,r,s).executeNotNull()}async function reauthenticateWithPopup(t,r,n){const i=getModularInstance(t);if(e(i.auth.app))return Promise.reject(_createError(i.auth,”operation-not-supported-in-this-environment”));_assertInstanceOf(i.auth,r,FederatedAuthProvider);const s=_withDefaultResolver(i.auth,n);return new PopupOperation(i.auth,”reauthViaPopup”,r,s,i).executeNotNull()}async function linkWithPopup(e,t,r){const n=getModularInstance(e);_assertInstanceOf(n.auth,t,FederatedAuthProvider);const i=_withDefaultResolver(n.auth,r);return new PopupOperation(n.auth,”linkViaPopup”,t,i,n).executeNotNull()}class PopupOperation extends AbstractPopupRedirectOperation{constructor(e,t,r,n,i){super(e,t,n,i),this.provider=r,this.authWindow=null,this.pollId=null,PopupOperation.currentPopupAction&&PopupOperation.currentPopupAction.cancel(),PopupOperation.currentPopupAction=this}async executeNotNull(){const e=await this.execute();return _assert(e,this.auth,”internal-error”),e}async onExecution(){debugAssert(1===this.filter.length,”Popup operations only handle one event”);const e=_generateEventId();this.authWindow=await this.resolver._openPopup(this.auth,this.provider,this.filter[0],e),this.authWindow.associatedEvent=e,this.resolver._originValidation(this.auth).catch((e=>{this.reject(e)})),this.resolver._isIframeWebStorageSupported(this.auth,(e=>{e||this.reject(_createError(this.auth,”web-storage-unsupported”))})),this.pollUserCancellation()}get eventId(){var e;return(null===(e=this.authWindow)||void 0===e?void 0:e.associatedEvent)||null}cancel(){this.reject(_createError(this.auth,”cancelled-popup-request”))}cleanUp(){this.authWindow&&this.authWindow.close(),this.pollId&&window.clearTimeout(this.pollId),this.authWindow=null,this.pollId=null,PopupOperation.currentPopupAction=null}pollUserCancellation(){const poll=()=>{var e,t;(null===(t=null===(e=this.authWindow)||void 0===e?void 0:e.window)||void 0===t?void 0:t.closed)?this.pollId=window.setTimeout((()=>{this.pollId=null,this.reject(_createError(this.auth,”popup-closed-by-user”))}),8e3):this.pollId=window.setTimeout(poll,q.get())};poll()}}PopupOperation.currentPopupAction=null;const G=new Map;class RedirectAction extends AbstractPopupRedirectOperation{constructor(e,t,r=!1){super(e,[“signInViaRedirect”,”linkViaRedirect”,”reauthViaRedirect”,”unknown”],t,void 0,r),this.eventId=null}async execute(){let e=G.get(this.auth._key());if(!e){try{const t=await async function _getAndClearPendingRedirectStatus(e,t){const r=pendingRedirectKey(t),n=resolverPersistence(e);if(!await n._isAvailable())return!1;const i=”true”===await n._get(r);return await n._remove(r),i}(this.resolver,this.auth)?await super.execute():null;e=()=>Promise.resolve(t)}catch(t){e=()=>Promise.reject(t)}G.set(this.auth._key(),e)}return this.bypassAuthState||G.set(this.auth._key(),(()=>Promise.resolve(null))),e()}async onAuthEvent(e){if(“signInViaRedirect”===e.type)return super.onAuthEvent(e);if(“unknown”!==e.type){if(e.eventId){const t=await this.auth._redirectUserForId(e.eventId);if(t)return this.user=t,super.onAuthEvent(e);this.resolve(null)}}else this.resolve(null)}async onExecution(){}cleanUp(){}}async function _setPendingRedirectStatus(e,t){return resolverPersistence(e)._set(pendingRedirectKey(t),”true”)}function _overrideRedirectResult(e,t){G.set(e._key(),t)}function resolverPersistence(e){return _getInstance(e._redirectPersistence)}function pendingRedirectKey(e){return _persistenceKeyName(“pendingRedirect”,e.config.apiKey,e.name)}function signInWithRedirect(t,r,n){return async function _signInWithRedirect(t,r,n){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t);_assertInstanceOf(t,r,FederatedAuthProvider),await i._initializationPromise;const s=_withDefaultResolver(i,n);return await _setPendingRedirectStatus(s,i),s._openRedirect(i,r,”signInViaRedirect”)}(t,r,n)}function reauthenticateWithRedirect(t,r,n){return async function _reauthenticateWithRedirect(t,r,n){const i=getModularInstance(t);if(_assertInstanceOf(i.auth,r,FederatedAuthProvider),e(i.auth.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(i.auth));await i.auth._initializationPromise;const s=_withDefaultResolver(i.auth,n);await _setPendingRedirectStatus(s,i.auth);const o=await prepareUserForRedirect(i);return s._openRedirect(i.auth,r,”reauthViaRedirect”,o)}(t,r,n)}function linkWithRedirect(e,t,r){return async function _linkWithRedirect(e,t,r){const n=getModularInstance(e);_assertInstanceOf(n.auth,t,FederatedAuthProvider),await n.auth._initializationPromise;const i=_withDefaultResolver(n.auth,r);await _assertLinkedStatus(!1,n,t.providerId),await _setPendingRedirectStatus(i,n.auth);const s=await prepareUserForRedirect(n);return i._openRedirect(n.auth,t,”linkViaRedirect”,s)}(e,t,r)}async function getRedirectResult(e,t){return await _castAuth(e)._initializationPromise,_getRedirectResult(e,t,!1)}async function _getRedirectResult(t,r,n=!1){if(e(t.app))return Promise.reject(_serverAppCurrentUserOperationNotSupportedError(t));const i=_castAuth(t),s=_withDefaultResolver(i,r),o=new RedirectAction(i,s,n),a=await o.execute();return a&&!n&&(delete a.user._redirectEventId,await i._persistUserIfCurrent(a.user),await i._setRedirectUser(null,r)),a}async function prepareUserForRedirect(e){const t=_generateEventId(`${e.uid}:::`);return e._redirectEventId=t,await e.auth._setRedirectUser(e),await e.auth._persistUserIfCurrent(e),t}class AuthEventManager{constructor(e){this.auth=e,this.cachedEventUids=new Set,this.consumers=new Set,this.queuedRedirectEvent=null,this.hasHandledPotentialRedirect=!1,this.lastProcessedEventTime=Date.now()}registerConsumer(e){this.consumers.add(e),this.queuedRedirectEvent&&this.isEventForConsumer(this.queuedRedirectEvent,e)&&(this.sendToConsumer(this.queuedRedirectEvent,e),this.saveEventToCache(this.queuedRedirectEvent),this.queuedRedirectEvent=null)}unregisterConsumer(e){this.consumers.delete(e)}onEvent(e){if(this.hasEventBeenHandled(e))return!1;let t=!1;return this.consumers.forEach((r=>{this.isEventForConsumer(e,r)&&(t=!0,this.sendToConsumer(e,r),this.saveEventToCache(e))})),this.hasHandledPotentialRedirect||!function isRedirectEvent(e){switch(e.type){case”signInViaRedirect”:case”linkViaRedirect”:case”reauthViaRedirect”:return!0;case”unknown”:return isNullRedirectEvent(e);default:return!1}}(e)||(this.hasHandledPotentialRedirect=!0,t||(this.queuedRedirectEvent=e,t=!0)),t}sendToConsumer(e,t){var r;if(e.error&&!isNullRedirectEvent(e)){const n=(null===(r=e.error.code)||void 0===r?void 0:r.split(“auth/”)[1])||”internal-error”;t.onError(_createError(this.auth,n))}else t.onAuthEvent(e)}isEventForConsumer(e,t){const r=null===t.eventId||!!e.eventId&&e.eventId===t.eventId;return t.filter.includes(e.type)&&r}hasEventBeenHandled(e){return Date.now()-this.lastProcessedEventTime>=6e5&&this.cachedEventUids.clear(),this.cachedEventUids.has(eventUid(e))}saveEventToCache(e){this.cachedEventUids.add(eventUid(e)),this.lastProcessedEventTime=Date.now()}}function eventUid(e){return[e.type,e.eventId,e.sessionId,e.tenantId].filter((e=>e)).join(“-“)}function isNullRedirectEvent({type:e,error:t}){return”unknown”===e&&”auth/no-auth-event”===(null==t?void 0:t.code)}const B=/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/,z=/^https?/;async function _validateOrigin(e){if(e.config.emulator)return;const{authorizedDomains:t}=await async function _getProjectConfig(e,t={}){return _performApiRequest(e,”GET”,”/v1/projects”,t)}(e);for(const e of t)try{if(matchDomain(e))return}catch(e){}_fail(e,”unauthorized-domain”)}function matchDomain(e){const t=_getCurrentUrl(),{protocol:r,hostname:n}=new URL(t);if(e.startsWith(“chrome-extension://”)){const i=new URL(e);return””===i.hostname&&””===n?”chrome-extension:”===r&&e.replace(“chrome-extension://”,””)===t.replace(“chrome-extension://”,””):”chrome-extension:”===r&&i.hostname===n}if(!z.test(r))return!1;if(B.test(e))return n===e;const i=e.replace(/\./g,”\\.”);return new RegExp(“^(.+\\.”+i+”|”+i+”)$”,”i”).test(n)}const K=new Delay(3e4,6e4);function resetUnloadedGapiModules(){const e=_window().___jsl;if(null==e?void 0:e.H)for(const t of Object.keys(e.H))if(e.H[t].r=e.H[t].r||[],e.H[t].L=e.H[t].L||[],e.H[t].r=[…e.H[t].L],e.CP)for(let t=0;t{var n,i,s;function loadGapiIframe(){resetUnloadedGapiModules(),gapi.load(“gapi.iframes”,{callback:()=>{t(gapi.iframes.getContext())},ontimeout:()=>{resetUnloadedGapiModules(),r(_createError(e,”network-request-failed”))},timeout:K.get()})}if(null===(i=null===(n=_window().gapi)||void 0===n?void 0:n.iframes)||void 0===i?void 0:i.Iframe)t(gapi.iframes.getContext());else{if(!(null===(s=_window().gapi)||void 0===s?void 0:s.load)){const t=_generateCallbackName(“iframefcb”);return _window()[t]=()=>{gapi.load?loadGapiIframe():r(_createError(e,”network-request-failed”))},_loadJS(`${function _gapiScriptUrl(){return P.gapiScript}()}?onload=${t}`).catch((e=>r(e)))}loadGapiIframe()}})).catch((e=>{throw $=null,e}))}let $=null;const J=new Delay(5e3,15e3),Y={style:{position:”absolute”,top:”-100px”,width:”1px”,height:”1px”},”aria-hidden”:”true”,tabindex:”-1″},X=new Map([[“identitytoolkit.googleapis.com”,”p”],[“staging-identitytoolkit.sandbox.googleapis.com”,”s”],[“test-identitytoolkit.sandbox.googleapis.com”,”t”]]);function getIframeUrl(e){const t=e.config;_assert(t.authDomain,e,”auth-domain-config-required”);const r=t.emulator?_emulatorUrl(t,”emulator/auth/iframe”):`https://${e.config.authDomain}/__/auth/iframe`,n={apiKey:t.apiKey,appName:e.name,v:i},s=X.get(e.config.apiHost);s&&(n.eid=s);const o=e._getFrameworks();return o.length&&(n.fw=o.join(“,”)),`${r}?${querystring(n).slice(1)}`}async function _openIframe(e){const t=await function _loadGapi(e){return $=$||loadGapi(e),$}(e),r=_window().gapi;return _assert(r,e,”internal-error”),t.open({where:document.body,url:getIframeUrl(e),messageHandlersFilter:r.iframes.CROSS_ORIGIN_IFRAMES_FILTER,attributes:Y,dontclear:!0},(t=>new Promise((async(r,n)=>{await t.restyle({setHideOnLeave:!1});const i=_createError(e,”network-request-failed”),s=_window().setTimeout((()=>{n(i)}),J.get());function clearTimerAndResolve(){_window().clearTimeout(s),r(t)}t.ping(clearTimerAndResolve).then(clearTimerAndResolve,(()=>{n(i)}))}))))}const Q={location:”yes”,resizable:”yes”,statusbar:”yes”,toolbar:”no”};class AuthPopup{constructor(e){this.window=e,this.associatedEvent=null}close(){if(this.window)try{this.window.close()}catch(e){}}}function _open(e,t,r,n=500,i=600){const s=Math.max((window.screen.availHeight-i)/2,0).toString(),o=Math.max((window.screen.availWidth-n)/2,0).toString();let a=””;const c=Object.assign(Object.assign({},Q),{width:n.toString(),height:i.toString(),top:s,left:o}),u=getUA().toLowerCase();r&&(a=_isChromeIOS(u)?”_blank”:r),_isFirefox(u)&&(t=t||”http://localhost”,c.scrollbars=”yes”);const d=Object.entries(c).reduce(((e,[t,r])=>`${e}${t}=${r},`),””);if(function _isIOSStandalone(e=getUA()){var t;return _isIOS(e)&&!!(null===(t=window.navigator)||void 0===t?void 0:t.standalone)}(u)&&”_self”!==a)return function openAsNewWindowIOS(e,t){const r=document.createElement(“a”);r.href=e,r.target=t;const n=document.createEvent(“MouseEvent”);n.initMouseEvent(“click”,!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,1,null),r.dispatchEvent(n)}(t||””,a),new AuthPopup(null);const l=window.open(t||””,a,d);_assert(l,e,”popup-blocked”);try{l.focus()}catch(e){}return new AuthPopup(l)}const Z=”__/auth/handler”,ee=”emulator/auth/handler”,te=encodeURIComponent(“fac”);async function _getRedirectUrl(e,t,r,n,s,o){_assert(e.config.authDomain,e,”auth-domain-config-required”),_assert(e.config.apiKey,e,”invalid-api-key”);const a={apiKey:e.config.apiKey,appName:e.name,authType:r,redirectUrl:n,v:i,eventId:s};if(t instanceof FederatedAuthProvider){t.setDefaultLanguage(e.languageCode),a.providerId=t.providerId||””,function isEmpty(e){for(const t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!1;return!0}(t.getCustomParameters())||(a.customParameters=JSON.stringify(t.getCustomParameters()));for(const[e,t]of Object.entries(o||{}))a[e]=t}if(t instanceof BaseOAuthProvider){const e=t.getScopes().filter((e=>””!==e));e.length>0&&(a.scopes=e.join(“,”))}e.tenantId&&(a.tid=e.tenantId);const c=a;for(const e of Object.keys(c))void 0===c[e]&&delete c[e];const u=await e._getAppCheckToken(),d=u?`#${te}=${encodeURIComponent(u)}`:””;return`${function getHandlerBase({config:e}){if(!e.emulator)return`https://${e.authDomain}/${Z}`;return _emulatorUrl(e,ee)}(e)}?${querystring(c).slice(1)}${d}`}const re=”webStorageSupport”;const ne=class BrowserPopupRedirectResolver{constructor(){this.eventManagers={},this.iframes={},this.originValidationPromises={},this._redirectPersistence=L,this._completeRedirectFn=_getRedirectResult,this._overrideRedirectResult=_overrideRedirectResult}async _openPopup(e,t,r,n){var i;debugAssert(null===(i=this.eventManagers[e._key()])||void 0===i?void 0:i.manager,”_initialize() not called before _openPopup()”);return _open(e,await _getRedirectUrl(e,t,r,_getCurrentUrl(),n),_generateEventId())}async _openRedirect(e,t,r,n){await this._originValidation(e);return function _setWindowLocation(e){_window().location.href=e}(await _getRedirectUrl(e,t,r,_getCurrentUrl(),n)),new Promise((()=>{}))}_initialize(e){const t=e._key();if(this.eventManagers[t]){const{manager:e,promise:r}=this.eventManagers[t];return e?Promise.resolve(e):(debugAssert(r,”If manager is not set, promise should be”),r)}const r=this.initAndGetManager(e);return this.eventManagers[t]={promise:r},r.catch((()=>{delete this.eventManagers[t]})),r}async initAndGetManager(e){const t=await _openIframe(e),r=new AuthEventManager(e);return t.register(“authEvent”,(t=>{_assert(null==t?void 0:t.authEvent,e,”invalid-auth-event”);return{status:r.onEvent(t.authEvent)?”ACK”:”ERROR”}}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER),this.eventManagers[e._key()]={manager:r},this.iframes[e._key()]=t,r}_isIframeWebStorageSupported(e,t){this.iframes[e._key()].send(re,{type:re},(r=>{var n;const i=null===(n=null==r?void 0:r[0])||void 0===n?void 0:n[re];void 0!==i&&t(!!i),_fail(e,”internal-error”)}),gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER)}_originValidation(e){const t=e._key();return this.originValidationPromises[t]||(this.originValidationPromises[t]=_validateOrigin(e)),this.originValidationPromises[t]}get _shouldInitProactively(){return _isMobileBrowser()||_isSafari()||_isIOS()}};class MultiFactorAssertionImpl{constructor(e){this.factorId=e}_process(e,t,r){switch(t.type){case”enroll”:return this._finalizeEnroll(e,t.credential,r);case”signin”:return this._finalizeSignIn(e,t.credential);default:return debugFail(“unexpected MultiFactorSessionType”)}}}class PhoneMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e){super(“phone”),this.credential=e}static _fromCredential(e){return new PhoneMultiFactorAssertionImpl(e)}_finalizeEnroll(e,t,r){return function finalizeEnrollPhoneMfa(e,t){return _performApiRequest(e,”POST”,”/v2/accounts/mfaEnrollment:finalize”,_addTidIfNecessary(e,t))}(e,{idToken:t,displayName:r,phoneVerificationInfo:this.credential._makeVerificationRequest()})}_finalizeSignIn(e,t){return function finalizeSignInPhoneMfa(e,t){return _performApiRequest(e,”POST”,”/v2/accounts/mfaSignIn:finalize”,_addTidIfNecessary(e,t))}(e,{mfaPendingCredential:t,phoneVerificationInfo:this.credential._makeVerificationRequest()})}}class PhoneMultiFactorGenerator{constructor(){}static assertion(e){return PhoneMultiFactorAssertionImpl._fromCredential(e)}}PhoneMultiFactorGenerator.FACTOR_ID=”phone”;class TotpMultiFactorGenerator{static assertionForEnrollment(e,t){return TotpMultiFactorAssertionImpl._fromSecret(e,t)}static assertionForSignIn(e,t){return TotpMultiFactorAssertionImpl._fromEnrollmentId(e,t)}static async generateSecret(e){var t;const r=e;_assert(void 0!==(null===(t=r.user)||void 0===t?void 0:t.auth),”internal-error”);const n=await function startEnrollTotpMfa(e,t){return _performApiRequest(e,”POST”,”/v2/accounts/mfaEnrollment:start”,_addTidIfNecessary(e,t))}(r.user.auth,{idToken:r.credential,totpEnrollmentInfo:{}});return TotpSecret._fromStartTotpMfaEnrollmentResponse(n,r.user.auth)}}TotpMultiFactorGenerator.FACTOR_ID=”totp”;class TotpMultiFactorAssertionImpl extends MultiFactorAssertionImpl{constructor(e,t,r){super(“totp”),this.otp=e,this.enrollmentId=t,this.secret=r}static _fromSecret(e,t){return new TotpMultiFactorAssertionImpl(t,void 0,e)}static _fromEnrollmentId(e,t){return new TotpMultiFactorAssertionImpl(t,e)}async _finalizeEnroll(e,t,r){return _assert(void 0!==this.secret,e,”argument-error”),function finalizeEnrollTotpMfa(e,t){return _performApiRequest(e,”POST”,”/v2/accounts/mfaEnrollment:finalize”,_addTidIfNecessary(e,t))}(e,{idToken:t,displayName:r,totpVerificationInfo:this.secret._makeTotpVerificationInfo(this.otp)})}async _finalizeSignIn(e,t){_assert(void 0!==this.enrollmentId&&void 0!==this.otp,e,”argument-error”);const r={verificationCode:this.otp};return function finalizeSignInTotpMfa(e,t){return _performApiRequest(e,”POST”,”/v2/accounts/mfaSignIn:finalize”,_addTidIfNecessary(e,t))}(e,{mfaPendingCredential:t,mfaEnrollmentId:this.enrollmentId,totpVerificationInfo:r})}}class TotpSecret{constructor(e,t,r,n,i,s,o){this.sessionInfo=s,this.auth=o,this.secretKey=e,this.hashingAlgorithm=t,this.codeLength=r,this.codeIntervalSeconds=n,this.enrollmentCompletionDeadline=i}static _fromStartTotpMfaEnrollmentResponse(e,t){return new TotpSecret(e.totpSessionInfo.sharedSecretKey,e.totpSessionInfo.hashingAlgorithm,e.totpSessionInfo.verificationCodeLength,e.totpSessionInfo.periodSec,new Date(e.totpSessionInfo.finalizeEnrollmentTime).toUTCString(),e.totpSessionInfo.sessionInfo,t)}_makeTotpVerificationInfo(e){return{sessionInfo:this.sessionInfo,verificationCode:e}}generateQrCodeUrl(e,t){var r;let n=!1;return(_isEmptyString(e)||_isEmptyString(t))&&(n=!0),n&&(_isEmptyString(e)&&(e=(null===(r=this.auth.currentUser)||void 0===r?void 0:r.email)||”unknownuser”),_isEmptyString(t)&&(t=this.auth.name)),`otpauth://totp/${t}:${e}?secret=${this.secretKey}&issuer=${t}&algorithm=${this.hashingAlgorithm}&digits=${this.codeLength}`}}function _isEmptyString(e){return void 0===e||0===(null==e?void 0:e.length)}var ie=”@firebase/auth”,se=”1.10.1″;class AuthInterop{constructor(e){this.auth=e,this.internalListeners=new Map}getUid(){var e;return this.assertAuthConfigured(),(null===(e=this.auth.currentUser)||void 0===e?void 0:e.uid)||null}async getToken(e){if(this.assertAuthConfigured(),await this.auth._initializationPromise,!this.auth.currentUser)return null;return{accessToken:await this.auth.currentUser.getIdToken(e)}}addAuthTokenListener(e){if(this.assertAuthConfigured(),this.internalListeners.has(e))return;const t=this.auth.onIdTokenChanged((t=>{e((null==t?void 0:t.stsTokenManager.accessToken)||null)}));this.internalListeners.set(e,t),this.updateProactiveRefresh()}removeAuthTokenListener(e){this.assertAuthConfigured();const t=this.internalListeners.get(e);t&&(this.internalListeners.delete(e),t(),this.updateProactiveRefresh())}assertAuthConfigured(){_assert(this.auth._initializationPromise,”dependent-sdk-initialized-before-auth”)}updateProactiveRefresh(){this.internalListeners.size>0?this.auth._startProactiveRefresh():this.auth._stopProactiveRefresh()}}const oe=getExperimentalSetting(“authIdTokenMaxAge”)||300;let ae=null;function getAuth(e=n()){const t=_getProvider(e,”auth”);if(t.isInitialized())return t.getImmediate();const r=initializeAuth(e,{popupRedirectResolver:ne,persistence:[V,N,L]}),i=getExperimentalSetting(“authTokenSyncURL”);if(i&&”boolean”==typeof isSecureContext&&isSecureContext){const e=new URL(i,location.origin);if(location.origin===e.origin){const t=(s=e.toString(),async e=>{const t=e&&await e.getIdTokenResult(),r=t&&((new Date).getTime()-Date.parse(t.issuedAtTime))/1e3;if(r&&r>oe)return;const n=null==t?void 0:t.token;ae!==n&&(ae=n,await fetch(s,{method:n?”POST”:”DELETE”,headers:n?{Authorization:`Bearer ${n}`}:{}}))});beforeAuthStateChanged(r,t,(()=>t(r.currentUser))),onIdTokenChanged(r,(e=>t(e)))}}var s;const o=(a=”auth”,null===(u=null===(c=getDefaults())||void 0===c?void 0:c.emulatorHosts)||void 0===u?void 0:u[a]);var a,c,u;return o&&connectAuthEmulator(r,`http://${o}`),r}!function _setExternalJSProvider(e){P=e}({loadJS:e=>new Promise(((t,r)=>{const n=document.createElement(“script”);n.setAttribute(“src”,e),n.onload=t,n.onerror=e=>{const t=_createError(“internal-error”);t.customData=e,r(t)},n.type=”text/javascript”,n.charset=”UTF-8″,function getScriptParentElement(){var e,t;return null!==(t=null===(e=document.getElementsByTagName(“head”))||void 0===e?void 0:e[0])&&void 0!==t?t:document}().appendChild(n)})),gapiScript:”https://apis.google.com/js/api.js”,recaptchaV2Script:”https://www.google.com/recaptcha/api.js”,recaptchaEnterpriseScript:”https://www.google.com/recaptcha/enterprise.js?render=”}),function registerAuth(e){t(new Component(“auth”,((t,{options:r})=>{const n=t.getProvider(“app”).getImmediate(),i=t.getProvider(“heartbeat”),s=t.getProvider(“app-check-internal”),{apiKey:o,authDomain:a}=n.options;_assert(o&&!o.includes(“:”),”invalid-api-key”,{appName:n.name});const c={apiKey:o,authDomain:a,clientPlatform:e,apiHost:”identitytoolkit.googleapis.com”,tokenApiHost:”securetoken.googleapis.com”,apiScheme:”https”,sdkClientVersion:_getClientVersion(e)},u=new AuthImpl(n,i,s,c);return function _initializeAuthInstance(e,t){const r=(null==t?void 0:t.persistence)||[],n=(Array.isArray(r)?r:[r]).map(_getInstance);(null==t?void 0:t.errorMap)&&e._updateErrorMap(t.errorMap),e._initializeWithPersistence(n,null==t?void 0:t.popupRedirectResolver)}(u,r),u}),”PUBLIC”).setInstantiationMode(“EXPLICIT”).setInstanceCreatedCallback(((e,t,r)=>{e.getProvider(“auth-internal”).initialize()}))),t(new Component(“auth-internal”,(e=>(e=>new AuthInterop(e))(_castAuth(e.getProvider(“auth”).getImmediate()))),”PRIVATE”).setInstantiationMode(“EXPLICIT”)),r(ie,se,function getVersionForPlatform(e){switch(e){case”Node”:return”node”;case”ReactNative”:return”rn”;case”Worker”:return”webworker”;case”Cordova”:return”cordova”;case”WebExtension”:return”web-extension”;default:return}}(e)),r(ie,se,”esm2017″)}(“Browser”);export{m as ActionCodeOperation,ActionCodeURL,AuthCredential,v as AuthErrorCodes,EmailAuthCredential,EmailAuthProvider,FacebookAuthProvider,l as FactorId,GithubAuthProvider,GoogleAuthProvider,OAuthCredential,OAuthProvider,f as OperationType,PhoneAuthCredential,PhoneAuthProvider,PhoneMultiFactorGenerator,h as ProviderId,RecaptchaVerifier,SAMLAuthProvider,p as SignInMethod,TotpMultiFactorGenerator,TotpSecret,TwitterAuthProvider,applyActionCode,beforeAuthStateChanged,D as browserCookiePersistence,N as browserLocalPersistence,ne as browserPopupRedirectResolver,L as browserSessionPersistence,checkActionCode,confirmPasswordReset,connectAuthEmulator,createUserWithEmailAndPassword,g as debugErrorMap,deleteUser,fetchSignInMethodsForEmail,getAdditionalUserInfo,getAuth,getIdToken,getIdTokenResult,getMultiFactorResolver,getRedirectResult,S as inMemoryPersistence,V as indexedDBLocalPersistence,initializeAuth,initializeRecaptchaConfig,isSignInWithEmailLink,linkWithCredential,linkWithPhoneNumber,linkWithPopup,linkWithRedirect,multiFactor,onAuthStateChanged,onIdTokenChanged,parseActionCodeURL,_ as prodErrorMap,reauthenticateWithCredential,reauthenticateWithPhoneNumber,reauthenticateWithPopup,reauthenticateWithRedirect,reload,revokeAccessToken,sendEmailVerification,sendPasswordResetEmail,sendSignInLinkToEmail,setPersistence,signInAnonymously,signInWithCredential,signInWithCustomToken,signInWithEmailAndPassword,signInWithEmailLink,signInWithPhoneNumber,signInWithPopup,signInWithRedirect,signOut,unlink,updateCurrentUser,updateEmail,updatePassword,updatePhoneNumber,updateProfile,useDeviceLanguage,validatePassword,verifyBeforeUpdateEmail,verifyPasswordResetCode};
//# sourceMappingURL=firebase-auth.js.map
import{_registerComponent as e,registerVersion as i,_isFirebaseServerApp as s,_getProvider,getApp as o,_removeServiceInstance as _,SDK_VERSION as h}from”https://www.gstatic.com/firebasejs/11.6.1/firebase-app.js”;const stringToByteArray$1=function(e){const i=[];let s=0;for(let o=0;o>6|192,i[s++]=63&_|128):55296==(64512&_)&&o+1>18|240,i[s++]=_>>12&63|128,i[s++]=_>>6&63|128,i[s++]=63&_|128):(i[s++]=_>>12|224,i[s++]=_>>6&63|128,i[s++]=63&_|128)}return i},d={byteToCharMap_:null,charToByteMap_:null,byteToCharMapWebSafe_:null,charToByteMapWebSafe_:null,ENCODED_VALS_BASE:”ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″,get ENCODED_VALS(){return this.ENCODED_VALS_BASE+”+/=”},get ENCODED_VALS_WEBSAFE(){return this.ENCODED_VALS_BASE+”-_.”},HAS_NATIVE_SUPPORT:”function”==typeof atob,encodeByteArray(e,i){if(!Array.isArray(e))throw Error(“encodeByteArray takes an array as a parameter”);this.init_();const s=i?this.byteToCharMapWebSafe_:this.byteToCharMap_,o=[];for(let i=0;i>2,w=(3&_)<<4|d>>4;let O=(15&d)<<2|g>>6,q=63&g;f||(q=64,h||(O=64)),o.push(s[b],s[w],s[O],s[q])}return o.join(“”)},encodeString(e,i){return this.HAS_NATIVE_SUPPORT&&!i?btoa(e):this.encodeByteArray(stringToByteArray$1(e),i)},decodeString(e,i){return this.HAS_NATIVE_SUPPORT&&!i?atob(e):function(e){const i=[];let s=0,o=0;for(;s191&&_<224){const h=e[s++];i[o++]=String.fromCharCode((31&_)<<6|63&h)}else if(_>239&&_<365){const h=((7&_)<<18|(63&e[s++])<<12|(63&e[s++])<<6|63&e[s++])-65536;i[o++]=String.fromCharCode(55296+(h>>10)),i[o++]=String.fromCharCode(56320+(1023&h))}else{const h=e[s++],d=e[s++];i[o++]=String.fromCharCode((15&_)<<12|(63&h)<<6|63&d)}}return i.join("")}(this.decodeStringToByteArray(e,i))},decodeStringToByteArray(e,i){this.init_();const s=i?this.charToByteMapWebSafe_:this.charToByteMap_,o=[];for(let i=0;i>4;if(o.push(g),64!==d){const e=h<<4&240|d>>2;if(o.push(e),64!==f){const e=d<<6&192|f;o.push(e)}}}return o},init_(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(let e=0;e=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(e)]=e,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(e)]=e)}}};class DecodeBase64StringError extends Error{constructor(){super(…arguments),this.name=”DecodeBase64StringError”}}const base64urlEncodeWithoutPadding=function(e){return function(e){const i=stringToByteArray$1(e);return d.encodeByteArray(i,!0)}(e).replace(/\./g,””)};function getGlobal(){if(“undefined”!=typeof self)return self;if(“undefined”!=typeof window)return window;if(“undefined”!=typeof global)return global;throw new Error(“Unable to locate global object.”)}const getDefaultsFromCookie=()=>{if(“undefined”==typeof document)return;let e;try{e=document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/)}catch(e){return}const i=e&&function(e){try{return d.decodeString(e,!0)}catch(e){console.error(“base64Decode failed: “,e)}return null}(e[1]);return i&&JSON.parse(i)},getDefaults=()=>{try{return getGlobal().__FIREBASE_DEFAULTS__||(()=>{if(“undefined”==typeof process||void 0===process.env)return;const e=process.env.__FIREBASE_DEFAULTS__;return e?JSON.parse(e):void 0})()||getDefaultsFromCookie()}catch(e){return void console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`)}},getDefaultEmulatorHostnameAndPort=e=>{const i=(e=>{var i,s;return null===(s=null===(i=getDefaults())||void 0===i?void 0:i.emulatorHosts)||void 0===s?void 0:s[e]})(e);if(!i)return;const s=i.lastIndexOf(“:”);if(s<=0||s+1===i.length)throw new Error(`Invalid host ${i} with no separate hostname and port!`);const o=parseInt(i.substring(s+1),10);return"["===i[0]?[i.substring(1,s-1),o]:[i.substring(0,s),o]};function getUA(){return"undefined"!=typeof navigator&&"string"==typeof navigator.userAgent?navigator.userAgent:""}function isSafari(){return!function isNode(){var e;const i=null===(e=getDefaults())||void 0===e?void 0:e.forceEnvironment;if("node"===i)return!0;if("browser"===i)return!1;try{return"[object process]"===Object.prototype.toString.call(global.process)}catch(e){return!1}}()&&!!navigator.userAgent&&navigator.userAgent.includes("Safari")&&!navigator.userAgent.includes("Chrome")}class FirebaseError extends Error{constructor(e,i,s){super(i),this.code=e,this.customData=s,this.name="FirebaseError",Object.setPrototypeOf(this,FirebaseError.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,ErrorFactory.prototype.create)}}class ErrorFactory{constructor(e,i,s){this.service=e,this.serviceName=i,this.errors=s}create(e,...i){const s=i[0]||{},o=`${this.service}/${e}`,_=this.errors[e],h=_?function replaceTemplate(e,i){return e.replace(f,((e,s)=>{const o=i[s];return null!=o?String(o):`<${s}?>`}))}(_,s):”Error”,d=`${this.serviceName}: ${h} (${o}).`;return new FirebaseError(o,d,s)}}const f=/\{\$([^}]+)}/g;function deepEqual(e,i){if(e===i)return!0;const s=Object.keys(e),o=Object.keys(i);for(const _ of s){if(!o.includes(_))return!1;const s=e[_],h=i[_];if(isObject(s)&&isObject(h)){if(!deepEqual(s,h))return!1}else if(s!==h)return!1}for(const e of o)if(!s.includes(e))return!1;return!0}function isObject(e){return null!==e&&”object”==typeof e}function getModularInstance(e){return e&&e._delegate?e._delegate:e}class Component{constructor(e,i,s){this.name=e,this.instanceFactory=i,this.type=s,this.multipleInstances=!1,this.serviceProps={},this.instantiationMode=”LAZY”,this.onInstanceCreated=null}setInstantiationMode(e){return this.instantiationMode=e,this}setMultipleInstances(e){return this.multipleInstances=e,this}setServiceProps(e){return this.serviceProps=e,this}setInstanceCreatedCallback(e){return this.onInstanceCreated=e,this}}var g;!function(e){e[e.DEBUG=0]=”DEBUG”,e[e.VERBOSE=1]=”VERBOSE”,e[e.INFO=2]=”INFO”,e[e.WARN=3]=”WARN”,e[e.ERROR=4]=”ERROR”,e[e.SILENT=5]=”SILENT”}(g||(g={}));const b={debug:g.DEBUG,verbose:g.VERBOSE,info:g.INFO,warn:g.WARN,error:g.ERROR,silent:g.SILENT},w=g.INFO,O={[g.DEBUG]:”log”,[g.VERBOSE]:”log”,[g.INFO]:”info”,[g.WARN]:”warn”,[g.ERROR]:”error”},defaultLogHandler=(e,i,…s)=>{if(i_;++_)o[_]=i.charCodeAt(s++)|i.charCodeAt(s++)<<8|i.charCodeAt(s++)<<16|i.charCodeAt(s++)<<24;else for(_=0;16>_;++_)o[_]=i[s++]|i[s++]<<8|i[s++]<<16|i[s++]<<24;i=e.g[0],s=e.g[1],_=e.g[2];var h=e.g[3],d=i+(h^s&(_^h))+o[0]+3614090360&4294967295;d=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=(s=(_=(h=(i=s+(d<<7&4294967295|d>>>25))+((d=h+(_^i&(s^_))+o[1]+3905402710&4294967295)<<12&4294967295|d>>>20))+((d=_+(s^h&(i^s))+o[2]+606105819&4294967295)<<17&4294967295|d>>>15))+((d=s+(i^_&(h^i))+o[3]+3250441966&4294967295)<<22&4294967295|d>>>10))+((d=i+(h^s&(_^h))+o[4]+4118548399&4294967295)<<7&4294967295|d>>>25))+((d=h+(_^i&(s^_))+o[5]+1200080426&4294967295)<<12&4294967295|d>>>20))+((d=_+(s^h&(i^s))+o[6]+2821735955&4294967295)<<17&4294967295|d>>>15))+((d=s+(i^_&(h^i))+o[7]+4249261313&4294967295)<<22&4294967295|d>>>10))+((d=i+(h^s&(_^h))+o[8]+1770035416&4294967295)<<7&4294967295|d>>>25))+((d=h+(_^i&(s^_))+o[9]+2336552879&4294967295)<<12&4294967295|d>>>20))+((d=_+(s^h&(i^s))+o[10]+4294925233&4294967295)<<17&4294967295|d>>>15))+((d=s+(i^_&(h^i))+o[11]+2304563134&4294967295)<<22&4294967295|d>>>10))+((d=i+(h^s&(_^h))+o[12]+1804603682&4294967295)<<7&4294967295|d>>>25))+((d=h+(_^i&(s^_))+o[13]+4254626195&4294967295)<<12&4294967295|d>>>20))+((d=_+(s^h&(i^s))+o[14]+2792965006&4294967295)<<17&4294967295|d>>>15))+((d=s+(i^_&(h^i))+o[15]+1236535329&4294967295)<<22&4294967295|d>>>10))+((d=i+(_^h&(s^_))+o[1]+4129170786&4294967295)<<5&4294967295|d>>>27))+((d=h+(s^_&(i^s))+o[6]+3225465664&4294967295)<<9&4294967295|d>>>23))+((d=_+(i^s&(h^i))+o[11]+643717713&4294967295)<<14&4294967295|d>>>18))+((d=s+(h^i&(_^h))+o[0]+3921069994&4294967295)<<20&4294967295|d>>>12))+((d=i+(_^h&(s^_))+o[5]+3593408605&4294967295)<<5&4294967295|d>>>27))+((d=h+(s^_&(i^s))+o[10]+38016083&4294967295)<<9&4294967295|d>>>23))+((d=_+(i^s&(h^i))+o[15]+3634488961&4294967295)<<14&4294967295|d>>>18))+((d=s+(h^i&(_^h))+o[4]+3889429448&4294967295)<<20&4294967295|d>>>12))+((d=i+(_^h&(s^_))+o[9]+568446438&4294967295)<<5&4294967295|d>>>27))+((d=h+(s^_&(i^s))+o[14]+3275163606&4294967295)<<9&4294967295|d>>>23))+((d=_+(i^s&(h^i))+o[3]+4107603335&4294967295)<<14&4294967295|d>>>18))+((d=s+(h^i&(_^h))+o[8]+1163531501&4294967295)<<20&4294967295|d>>>12))+((d=i+(_^h&(s^_))+o[13]+2850285829&4294967295)<<5&4294967295|d>>>27))+((d=h+(s^_&(i^s))+o[2]+4243563512&4294967295)<<9&4294967295|d>>>23))+((d=_+(i^s&(h^i))+o[7]+1735328473&4294967295)<<14&4294967295|d>>>18))+((d=s+(h^i&(_^h))+o[12]+2368359562&4294967295)<<20&4294967295|d>>>12))+((d=i+(s^_^h)+o[5]+4294588738&4294967295)<<4&4294967295|d>>>28))+((d=h+(i^s^_)+o[8]+2272392833&4294967295)<<11&4294967295|d>>>21))+((d=_+(h^i^s)+o[11]+1839030562&4294967295)<<16&4294967295|d>>>16))+((d=s+(_^h^i)+o[14]+4259657740&4294967295)<<23&4294967295|d>>>9))+((d=i+(s^_^h)+o[1]+2763975236&4294967295)<<4&4294967295|d>>>28))+((d=h+(i^s^_)+o[4]+1272893353&4294967295)<<11&4294967295|d>>>21))+((d=_+(h^i^s)+o[7]+4139469664&4294967295)<<16&4294967295|d>>>16))+((d=s+(_^h^i)+o[10]+3200236656&4294967295)<<23&4294967295|d>>>9))+((d=i+(s^_^h)+o[13]+681279174&4294967295)<<4&4294967295|d>>>28))+((d=h+(i^s^_)+o[0]+3936430074&4294967295)<<11&4294967295|d>>>21))+((d=_+(h^i^s)+o[3]+3572445317&4294967295)<<16&4294967295|d>>>16))+((d=s+(_^h^i)+o[6]+76029189&4294967295)<<23&4294967295|d>>>9))+((d=i+(s^_^h)+o[9]+3654602809&4294967295)<<4&4294967295|d>>>28))+((d=h+(i^s^_)+o[12]+3873151461&4294967295)<<11&4294967295|d>>>21))+((d=_+(h^i^s)+o[15]+530742520&4294967295)<<16&4294967295|d>>>16))+((d=s+(_^h^i)+o[2]+3299628645&4294967295)<<23&4294967295|d>>>9))+((d=i+(_^(s|~h))+o[0]+4096336452&4294967295)<<6&4294967295|d>>>26))+((d=h+(s^(i|~_))+o[7]+1126891415&4294967295)<<10&4294967295|d>>>22))+((d=_+(i^(h|~s))+o[14]+2878612391&4294967295)<<15&4294967295|d>>>17))+((d=s+(h^(_|~i))+o[5]+4237533241&4294967295)<<21&4294967295|d>>>11))+((d=i+(_^(s|~h))+o[12]+1700485571&4294967295)<<6&4294967295|d>>>26))+((d=h+(s^(i|~_))+o[3]+2399980690&4294967295)<<10&4294967295|d>>>22))+((d=_+(i^(h|~s))+o[10]+4293915773&4294967295)<<15&4294967295|d>>>17))+((d=s+(h^(_|~i))+o[1]+2240044497&4294967295)<<21&4294967295|d>>>11))+((d=i+(_^(s|~h))+o[8]+1873313359&4294967295)<<6&4294967295|d>>>26))+((d=h+(s^(i|~_))+o[15]+4264355552&4294967295)<<10&4294967295|d>>>22))+((d=_+(i^(h|~s))+o[6]+2734768916&4294967295)<<15&4294967295|d>>>17))+((d=s+(h^(_|~i))+o[13]+1309151649&4294967295)<<21&4294967295|d>>>11))+((h=(i=s+((d=i+(_^(s|~h))+o[4]+4149444226&4294967295)<<6&4294967295|d>>>26))+((d=h+(s^(i|~_))+o[11]+3174756917&4294967295)<<10&4294967295|d>>>22))^((_=h+((d=_+(i^(h|~s))+o[2]+718787259&4294967295)<<15&4294967295|d>>>17))|~i))+o[9]+3951481745&4294967295,e.g[0]=e.g[0]+i&4294967295,e.g[1]=e.g[1]+(_+(d<<21&4294967295|d>>>11))&4294967295,e.g[2]=e.g[2]+_&4294967295,e.g[3]=e.g[3]+h&4294967295}function t(e,i){this.h=i;for(var s=[],o=!0,_=e.length-1;0<=_;_--){var h=0|e[_];o&&h==i||(s[_]=h,o=!1)}this.g=s}!function k(e,i){function c(){}c.prototype=i.prototype,e.D=i.prototype,e.prototype=new c,e.prototype.constructor=e,e.C=function(e,s,o){for(var _=Array(arguments.length-2),h=2;hthis.h?this.blockSize:2*this.blockSize)-this.h);e[0]=128;for(var i=1;ii;++i)for(var o=0;32>o;o+=8)e[s++]=this.g[i]>>>o&255;return e};var i={};function u(e){return-128<=e&&128>e?function p(e,s){var o=i;return Object.prototype.hasOwnProperty.call(o,e)?o[e]:o[e]=s(e)}(e,(function(e){return new t([0|e],0>e?-1:0)})):new t([0|e],0>e?-1:0)}function v(e){if(isNaN(e)||!isFinite(e))return s;if(0>e)return x(v(-e));for(var i=[],o=1,_=0;e>=o;_++)i[_]=e/o|0,o*=4294967296;return new t(i,0)}var s=u(0),o=u(1),_=u(16777216);function C(e){if(0!=e.h)return!1;for(var i=0;i>>16,e[i]&=65535,i++}function H(e,i){this.g=e,this.h=i}function D(e,i){if(C(i))throw Error(“division by zero”);if(C(e))return new H(s,s);if(B(e))return i=D(x(e),i),new H(x(i.g),x(i.h));if(B(i))return i=D(e,x(i)),new H(x(i.g),i.h);if(30=h.l(e);)_=I(_),h=I(h);var d=J(_,1),f=J(h,1);for(h=J(h,2),_=J(_,2);!C(h);){var g=f.add(h);0>=g.l(e)&&(d=d.add(_),f=g),h=J(h,1),_=J(_,1)}return i=F(e,d.j(i)),new H(d,i)}for(d=s;0<=e.l(i);){for(_=Math.max(1,Math.floor(e.m()/i.m())),h=48>=(h=Math.ceil(Math.log(_)/Math.LN2))?1:Math.pow(2,h-48),g=(f=v(_)).j(i);B(g)||0>>31;return new t(s,e.h)}function J(e,i){var s=i>>5;i%=32;for(var o=e.g.length-s,_=[],h=0;h>>i|e.i(h+s+1)<<32-i:e.i(h+s);return new t(_,e.h)}(e=t.prototype).m=function(){if(B(this))return-x(this).m();for(var e=0,i=1,s=0;s(e=e||10)||36>>0).toString(e);if(C(s=_))return h+o;for(;6>h.length;)h=”0″+h;o=h+o}},e.i=function(e){return 0>e?0:e>>16)+(this.i(_)>>>16)+(e.i(_)>>>16);o=d>>>16,h&=65535,d&=65535,s[_]=d<<16|h}return new t(s,-2147483648&s[s.length-1]?-1:0)},e.j=function(e){if(C(this)||C(e))return s;if(B(this))return B(e)?x(this).j(x(e)):x(x(this).j(e));if(B(e))return x(this.j(x(e)));if(0>this.l(_)&&0>e.l(_))return v(this.m()*e.m());for(var i=this.g.length+e.g.length,o=[],h=0;h<2*i;h++)o[h]=0;for(h=0;h>>16,g=65535&this.i(h),b=e.i(d)>>>16,w=65535&e.i(d);o[2*h+2*d]+=g*w,G(o,2*h+2*d),o[2*h+2*d+1]+=f*w,G(o,2*h+2*d+1),o[2*h+2*d+1]+=g*b,G(o,2*h+2*d+1),o[2*h+2*d+2]+=f*b,G(o,2*h+2*d+2)}for(h=0;h(i=i||10)||36d?(d=v(Math.pow(i,d)),_=_.j(d).add(v(f))):_=(_=_.j(o)).add(v(f))}return _},q=t}).apply(void 0!==$?$:”undefined”!=typeof self?self:”undefined”!=typeof window?window:{});var ee,te,ne,re,ie,se,oe,ae,ue=”undefined”!=typeof globalThis?globalThis:”undefined”!=typeof window?window:”undefined”!=typeof global?global:”undefined”!=typeof self?self:{};(function(){var e,i=”function”==typeof Object.defineProperties?Object.defineProperty:function(e,i,s){return e==Array.prototype||e==Object.prototype||(e[i]=s.value),e};var s=function ba(e){e=[“object”==typeof globalThis&&globalThis,e,”object”==typeof window&&window,”object”==typeof self&&self,”object”==typeof ue&&ue];for(var i=0;i{throw e}),0)}function xa(){var e=w;let i=null;return e.g&&(i=e.g,e.g=e.g.next,e.g||(e.h=null),i.next=null),i}var f=new class na{constructor(e,i){this.i=e,this.j=i,this.h=0,this.g=null}get(){let e;return 0new Ca),(e=>e.reset()));class Ca{constructor(){this.next=this.g=this.h=null}set(e,i){this.h=e,this.g=i,this.next=null}reset(){this.next=this.g=this.h=null}}let g,b=!1,w=new class Aa{constructor(){this.h=this.g=null}add(e,i){const s=f.get();s.set(e,i),this.h?this.h.next=s:this.g=s,this.h=s}},Ea=()=>{const e=_.Promise.resolve(void 0);g=()=>{e.then(Da)}};var Da=()=>{for(var e;e=xa();){try{e.h.call(e.g)}catch(e){wa(e)}var i=f;i.j(e),100>i.h&&(i.h++,e.next=i.g,i.g=e)}b=!1};function z(){this.s=this.s,this.C=this.C}function A(e,i){this.type=e,this.g=this.target=i,this.defaultPrevented=!1}z.prototype.s=!1,z.prototype.ma=function(){this.s||(this.s=!0,this.N())},z.prototype.N=function(){if(this.C)for(;this.C.length;)this.C.shift()()},A.prototype.h=function(){this.defaultPrevented=!0};var O=function(){if(!_.addEventListener||!Object.defineProperty)return!1;var e=!1,i=Object.defineProperty({},”passive”,{get:function(){e=!0}});try{const c=()=>{};_.addEventListener(“test”,c,i),_.removeEventListener(“test”,c,i)}catch(e){}return e}();function C(e,i){if(A.call(this,e?e.type:””),this.relatedTarget=this.g=this.target=null,this.button=this.screenY=this.screenX=this.clientY=this.clientX=0,this.key=””,this.metaKey=this.shiftKey=this.altKey=this.ctrlKey=!1,this.state=null,this.pointerId=0,this.pointerType=””,this.i=null,e){var s=this.type=e.type,o=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:null;if(this.target=e.target||e.srcElement,this.g=i,i=e.relatedTarget){if(h){e:{try{oa(i.nodeName);var _=!0;break e}catch(e){}_=!1}_||(i=null)}}else”mouseover”==s?i=e.fromElement:”mouseout”==s&&(i=e.toElement);this.relatedTarget=i,o?(this.clientX=void 0!==o.clientX?o.clientX:o.pageX,this.clientY=void 0!==o.clientY?o.clientY:o.pageY,this.screenX=o.screenX||0,this.screenY=o.screenY||0):(this.clientX=void 0!==e.clientX?e.clientX:e.pageX,this.clientY=void 0!==e.clientY?e.clientY:e.pageY,this.screenX=e.screenX||0,this.screenY=e.screenY||0),this.button=e.button,this.key=e.key||””,this.ctrlKey=e.ctrlKey,this.altKey=e.altKey,this.shiftKey=e.shiftKey,this.metaKey=e.metaKey,this.pointerId=e.pointerId||0,this.pointerType=”string”==typeof e.pointerType?e.pointerType:q[e.pointerType]||””,this.state=e.state,this.i=e,e.defaultPrevented&&C.aa.h.call(this)}}r(C,A);var q={2:”touch”,3:”pen”,4:”mouse”};C.prototype.h=function(){C.aa.h.call(this);var e=this.i;e.preventDefault?e.preventDefault():e.returnValue=!1};var j=”closure_listenable_”+(1e6*Math.random()|0),$=0;function Ia(e,i,s,o,_){this.listener=e,this.proxy=null,this.src=i,this.type=s,this.capture=!!o,this.ha=_,this.key=++$,this.da=this.fa=!1}function Ja(e){e.da=!0,e.listener=null,e.proxy=null,e.src=null,e.ha=null}function Ka(e){this.src=e,this.g={},this.h=0}function Ma(e,i){var s=i.type;if(s in e.g){var o,_=e.g[s],h=Array.prototype.indexOf.call(_,i,void 0);(o=0<=h)&&Array.prototype.splice.call(_,h,1),o&&(Ja(i),0==e.g[s].length&&(delete e.g[s],e.h--))}}function La(e,i,s,o){for(var _=0;_>>0);function Sa(e){return”function”==typeof e?e:(e[_e]||(e[_e]=function(i){return e.handleEvent(i)}),e[_e])}function E(){z.call(this),this.i=new Ka(this),this.M=this,this.F=null}function F(e,i){var s,o=e.F;if(o)for(s=[];o;o=o.F)s.push(o);if(e=e.M,o=i.type||i,”string”==typeof i)i=new A(i,e);else if(i instanceof A)i.target=i.target||e;else{var _=i;ua(i=new A(o,e),_)}if(_=!0,s)for(var h=s.length-1;0<=h;h--){var d=i.g=s[h];_=ab(d,o,!0,i)&&_}if(_=ab(d=i.g=e,o,!0,i)&&_,_=ab(d,o,!1,i)&&_,s)for(h=0;h{e.g=null,e.i&&(e.i=!1,cb(e))}),e.l);const i=e.h;e.h=null,e.m.apply(null,i)}r(E,z),E.prototype[j]=!0,E.prototype.removeEventListener=function(e,i,s,o){Ya(this,e,i,s,o)},E.prototype.N=function(){if(E.aa.N.call(this),this.i){var e,i=this.i;for(e in i.g){for(var s=i.g[e],o=0;oo.length)){var _=o[1];if(Array.isArray(_)&&!(1>_.length)){var h=_[0];if(“noop”!=h&&”stop”!=h&&”close”!=h)for(var d=1;d<_.length;d++)_[d]=""}}}return de(s)}catch(e){return i}}(e,s)+(o?" "+o:"")}))}pe.La="serverreachability",r(rb,A),pe.STAT_EVENT="statevent",r(sb,A),pe.Ma="timingevent",r(tb,A),vb.prototype.xa=function(){this.g=!1},vb.prototype.info=function(){};var Ie,Ee={NO_ERROR:0,gb:1,tb:2,sb:3,nb:4,rb:5,ub:6,Ia:7,TIMEOUT:8,xb:9},Pe={lb:"complete",Hb:"success",Ja:"error",Ia:"abort",zb:"ready",Ab:"readystatechange",TIMEOUT:"timeout",vb:"incrementaldata",yb:"progress",ob:"downloadprogress",Pb:"uploadprogress"};function Db(){}function M(e,i,s,o){this.j=e,this.i=i,this.l=s,this.R=o||1,this.U=new G(this),this.I=45e3,this.H=null,this.o=!1,this.m=this.A=this.v=this.L=this.F=this.S=this.B=null,this.D=[],this.g=null,this.C=0,this.s=this.u=null,this.X=-1,this.J=!1,this.O=0,this.M=null,this.W=this.K=this.T=this.P=!1,this.h=new Eb}function Eb(){this.i=null,this.g="",this.h=!1}r(Db,kb),Db.prototype.g=function(){return new XMLHttpRequest},Db.prototype.i=function(){return{}},Ie=new Db;var Ae={},Re={};function Hb(e,i,s){e.L=1,e.v=Ib(N(i)),e.m=s,e.P=!0,Jb(e,null)}function Jb(e,i){e.F=Date.now(),Kb(e),e.A=N(e.v);var s=e.A,o=e.R;Array.isArray(o)||(o=[String(o)]),Lb(s.i,"t",o),e.C=0,s=e.j.J,e.h=new Eb,e.g=Mb(e.j,s?i:null,!e.m),0i.length?Re:(i=i.slice(o,o+s),e.C=o+s,i))}function Kb(e){e.S=Date.now()+e.I,Wb(e,e.I)}function Wb(e,i){if(null!=e.B)throw Error(“WatchDog timer not null”);e.B=ub(p(e.ba,e),i)}function Ob(e){e.B&&(_.clearTimeout(e.B),e.B=null)}function Qb(e){0==e.j.G||e.J||Ub(e.j,e)}function Q(e){Ob(e);var i=e.M;i&&”function”==typeof i.ma&&i.ma(),e.M=null,gb(e.U),e.g&&(i=e.g,e.g=null,i.abort(),i.ma())}function Rb(e,i){try{var s=e.j;if(0!=s.G&&(s.g==e||Xb(s.h,e)))if(!e.K&&Xb(s.h,e)&&3==s.G){try{var o=s.Da.g.parse(i)}catch(e){o=null}if(Array.isArray(o)&&3==o.length){var _=o;if(0==_[0]){e:if(!s.u){if(s.g){if(!(s.g.F+3e3_[2]&&s.F&&0==s.v&&!s.C&&(s.C=ub(p(s.Za,s),6e3));if(1>=ac(s.h)&&s.ca){try{s.ca()}catch(e){}s.ca=void 0}}else R(s,11)}else if((e.K||s.g==e)&&Yb(s),!t(i))for(_=s.Da.g.parse(i),i=0;i<_.length;i++){let b=_[i];if(s.T=b[0],b=b[1],2==s.G)if("c"==b[0]){s.K=b[1],s.ia=b[2];const i=b[3];null!=i&&(s.la=i,s.j.info("VER="+s.la));const _=b[4];null!=_&&(s.Aa=_,s.j.info("SVER="+s.Aa));const w=b[5];null!=w&&"number"==typeof w&&0q)&&(3!=q||this.g&&(this.h.h||this.g.oa()||Nb(this.g)))){this.J||4!=q||7==i||J(),Ob(this);var s=this.g.Z();this.X=s;t:if(Pb(this)){var o=Nb(this.g);e=””;var h=o.length,d=4==P(this.g);if(!this.h.i){if(“undefined”==typeof TextDecoder){Q(this),Qb(this);var f=””;break t}this.h.i=new _.TextDecoder}for(i=0;i=e.j}function ac(e){return e.h?1:e.g?e.g.size:0}function Xb(e,i){return e.h?e.h==i:!!e.g&&e.g.has(i)}function bc(e,i){e.g?e.g.add(i):e.h=i}function dc(e,i){e.h&&e.h==i?e.h=null:e.g&&e.g.has(i)&&e.g.delete(i)}function kc(e){if(null!=e.h)return e.i.concat(e.h.D);if(null!=e.g&&0!==e.g.size){let i=e.i;for(const s of e.g.values())i=i.concat(s.D);return i}return la(e.i)}function nc(e,i){if(e.forEach&&”function”==typeof e.forEach)e.forEach(i,void 0);else if(ha(e)||”string”==typeof e)Array.prototype.forEach.call(e,i,void 0);else for(var s=function mc(e){if(e.na&&”function”==typeof e.na)return e.na();if(!e.V||”function”!=typeof e.V){if(“undefined”!=typeof Map&&e instanceof Map)return Array.from(e.keys());if(!(“undefined”!=typeof Set&&e instanceof Set)){if(ha(e)||”string”==typeof e){var i=[];e=e.length;for(var s=0;si)throw Error(“Bad port number “+i);e.s=i}else e.s=null}function tc(e,i,s){i instanceof sc?(e.i=i,function Ac(e,i){i&&!e.j&&(U(e),e.i=null,e.g.forEach((function(e,i){var s=i.toLowerCase();i!=s&&(Dc(this,i),Lb(this,s,e))}),e)),e.j=i}(e.i,e.h)):(s||(i=vc(i,De)),e.i=new sc(i,e.h))}function S(e,i,s){e.i.set(i,s)}function Ib(e){return S(e,”zx”,Math.floor(2147483648*Math.random()).toString(36)+Math.abs(Math.floor(2147483648*Math.random())^Date.now()).toString(36)),e}function uc(e,i){return e?i?decodeURI(e.replace(/%25/g,”%2525″)):decodeURIComponent(e):””}function vc(e,i,s){return”string”==typeof e?(e=encodeURI(e).replace(i,Cc),s&&(e=e.replace(/%25([0-9a-fA-F]{2})/g,”%$1″)),e):null}function Cc(e){return”%”+((e=e.charCodeAt(0))>>4&15).toString(16)+(15&e).toString(16)}T.prototype.toString=function(){var e=[],i=this.j;i&&e.push(vc(i,be,!0),”:”);var s=this.g;return(s||”file”==i)&&(e.push(“//”),(i=this.o)&&e.push(vc(i,be,!0),”@”),e.push(encodeURIComponent(String(s)).replace(/%25([0-9a-fA-F]{2})/g,”%$1″)),null!=(s=this.s)&&e.push(“:”,String(s))),(s=this.l)&&(this.g&&”/”!=s.charAt(0)&&e.push(“/”),e.push(vc(s,”/”==s.charAt(0)?we:Se,!0))),(s=this.i.toString())&&e.push(“?”,s),(s=this.m)&&e.push(“#”,vc(s,Ce)),e.join(“”)};var ve,be=/[#\/\?@]/g,Se=/[#\?:]/g,we=/[#\?]/g,De=/[#\?@]/g,Ce=/#/g;function sc(e,i){this.h=this.g=null,this.i=e||null,this.j=!!i}function U(e){e.g||(e.g=new Map,e.h=0,e.i&&function pc(e,i){if(e){e=e.split(“&”);for(var s=0;s{})),1<=this.readyState&&this.g&&4!=this.readyState&&(this.g=!1,Mc(this)),this.readyState=0},e.Sa=function(e){if(this.g&&(this.l=e,this.h||(this.status=this.l.status,this.statusText=this.l.statusText,this.h=e.headers,this.readyState=2,Lc(this)),this.g&&(this.readyState=3,Lc(this),this.g)))if("arraybuffer"===this.responseType)e.arrayBuffer().then(this.Qa.bind(this),this.ga.bind(this));else if(void 0!==_.ReadableStream&&"body"in e){if(this.j=e.body.getReader(),this.o){if(this.responseType)throw Error('responseType must be empty for "streamBinaryChunks" mode responses.');this.response=[]}else this.response=this.responseText="",this.v=new TextDecoder;Nc(this)}else e.text().then(this.Ra.bind(this),this.ga.bind(this))},e.Pa=function(e){if(this.g){if(this.o&&e.value)this.response.push(e.value);else if(!this.o){var i=e.value?e.value:new Uint8Array(0);(i=this.v.decode(i,{stream:!e.done}))&&(this.response=this.responseText+=i)}e.done?Mc(this):Lc(this),3==this.readyState&&Nc(this)}},e.Ra=function(e){this.g&&(this.response=this.responseText=e,Mc(this))},e.Qa=function(e){this.g&&(this.response=e,Mc(this))},e.ga=function(){this.g&&Mc(this)},e.setRequestHeader=function(e,i){this.u.append(e,i)},e.getResponseHeader=function(e){return this.h&&this.h.get(e.toLowerCase())||""},e.getAllResponseHeaders=function(){if(!this.h)return"";const e=[],i=this.h.entries();for(var s=i.next();!s.done;)s=s.value,e.push(s[0]+": "+s[1]),s=i.next();return e.join("\r\n")},Object.defineProperty(Kc.prototype,"withCredentials",{get:function(){return"include"===this.m},set:function(e){this.m=e?"include":"same-origin"}}),r(X,E);var Fe=/^https?$/i,xe=["POST","PUT"];function Sc(e,i){e.h=!1,e.g&&(e.j=!0,e.g.abort(),e.j=!1),e.l=i,e.m=5,Uc(e),Vc(e)}function Uc(e){e.A||(e.A=!0,F(e,"complete"),F(e,"error"))}function Wc(e){if(e.h&&void 0!==o&&(!e.v[1]||4!=P(e)||2!=e.Z()))if(e.u&&4==P(e))bb(e.Ea,0,e);else if(F(e,"readystatechange"),4==P(e)){e.h=!1;try{const o=e.Z();e:switch(o){case 200:case 201:case 202:case 204:case 206:case 304:case 1223:var i=!0;break e;default:i=!1}var s;if(!(s=i)){var h;if(h=0===o){var d=String(e.D).match(Ve)[1]||null;!d&&_.self&&_.self.location&&(d=_.self.location.protocol.slice(0,-1)),h=!Fe.test(d?d.toLowerCase():"")}s=h}if(s)F(e,"complete"),F(e,"success");else{e.m=6;try{var f=2{}:null;e.g=null,e.v=null,i||F(e,”ready”);try{s.onreadystatechange=o}catch(e){}}}function Tc(e){e.I&&(_.clearTimeout(e.I),e.I=null)}function P(e){return e.g?e.g.readyState:0}function Nb(e){try{if(!e.g)return null;if(“response”in e.g)return e.g.response;switch(e.H){case””:case”text”:return e.g.responseText;case”arraybuffer”:if(“mozResponseArrayBuffer”in e.g)return e.g.mozResponseArrayBuffer}return null}catch(e){return null}}function Xc(e,i,s){return s&&s.internalChannelParams&&s.internalChannelParams[e]||i}function Yc(e){this.Aa=0,this.i=[],this.j=new vb,this.ia=this.qa=this.I=this.W=this.g=this.ya=this.D=this.H=this.m=this.S=this.o=null,this.Ya=this.U=0,this.Va=Xc(“failFast”,!1,e),this.F=this.C=this.u=this.s=this.l=null,this.X=!0,this.za=this.T=-1,this.Y=this.v=this.B=0,this.Ta=Xc(“baseRetryDelayMs”,5e3,e),this.cb=Xc(“retryDelaySeedMs”,1e4,e),this.Wa=Xc(“forwardChannelMaxRetries”,2,e),this.wa=Xc(“forwardChannelRequestTimeoutMs”,2e4,e),this.pa=e&&e.xmlHttpFactory||void 0,this.Xa=e&&e.Tb||void 0,this.Ca=e&&e.useFetchStreams||!1,this.L=void 0,this.J=e&&e.supportsCrossDomainXhr||!1,this.K=””,this.h=new ic(e&&e.concurrentRequestLimit),this.Da=new Hc,this.P=e&&e.fastHandshake||!1,this.O=e&&e.encodeInitMessageHeaders||!1,this.P&&this.O&&(this.O=!1),this.Ua=e&&e.Rb||!1,e&&e.xa&&this.j.xa(),e&&e.forceLongPolling&&(this.X=!1),this.ba=!this.P&&this.X&&e&&e.detectBufferingProxy||!1,this.ja=void 0,e&&e.longPollingTimeout&&0s)i=Math.max(0,_[d].g-100),h=!1;else try{Ic(f,e,”req”+s+”_”)}catch(e){o&&o(f)}}if(h){o=e.join(“&”);break e}}}return e=e.i.splice(0,s),i.D=e,o}function ec(e){if(!e.g&&!e.u){e.Y=1;var i=e.Fa;g||Ea(),b||(g(),b=!0),w.add(i,e),e.v=0}}function $b(e){return!(e.g||e.u||3<=e.v)&&(e.Y++,e.u=ub(p(e.Fa,e),cd(e,e.v)),e.v++,!0)}function Tb(e){null!=e.A&&(_.clearTimeout(e.A),e.A=null)}function fd(e){e.g=new M(e,e.j,"rpc",e.Y),null===e.m&&(e.g.H=e.o),e.g.O=0;var i=N(e.qa);S(i,"RID","rpc"),S(i,"SID",e.K),S(i,"AID",e.T),S(i,"CI",e.F?"0":"1"),!e.F&&e.ja&&S(i,"TO",e.ja),S(i,"TYPE","xmlhttp"),$c(e,i),e.m&&e.o&&Pc(i,e.m,e.o),e.L&&(e.g.I=e.L);var s=e.g;e=e.ia,s.L=1,s.v=Ib(N(i)),s.m=null,s.P=!0,Jb(s,e)}function Yb(e){null!=e.C&&(_.clearTimeout(e.C),e.C=null)}function Ub(e,i){var s=null;if(e.g==i){Yb(e),Tb(e),e.g=null;var o=2}else{if(!Xb(e.h,i))return;s=i.D,dc(e.h,i),o=1}if(0!=e.G)if(i.o)if(1==o){s=i.m?i.m.length:0,i=Date.now()-i.F;var _=e.B;F(o=qb(),new tb(o,s)),fc(e)}else ec(e);else if(3==(_=i.s)||0==_&&0=e.h.j-(e.s?1:0)||(e.s?(e.i=i.D.concat(e.i),0):1==e.G||2==e.G||e.B>=(e.Va?0:e.Wa)||(e.s=ub(p(e.Ga,e,i),cd(e,e.B)),e.B++,0)))}(e,i)||2==o&&$b(e)))switch(s&&0{s.abort(),W(0,0,!1,i)}),1e4);fetch(e,{signal:s.signal}).then((e=>{clearTimeout(o),e.ok?W(0,0,!0,i):W(0,0,!1,i)})).catch((()=>{clearTimeout(o),W(0,0,!1,i)}))}(o.toString(),s)}else K(2);e.G=0,e.l&&e.l.sa(i),ad(e),Zc(e)}function ad(e){if(e.G=0,e.ka=[],e.l){const i=kc(e.h);0==i.length&&0==e.i.length||(ma(e.ka,i),ma(e.ka,e.i),e.h.i.length=0,la(e.i),e.i.length=0),e.l.ra()}}function cc(e,i,s){var o=s instanceof T?N(s):new T(s);if(“”!=o.g)i&&(o.g=i+”.”+o.g),rc(o,o.s);else{var h=_.location;o=h.protocol,i=i?i+”.”+h.hostname:h.hostname,h=+h.port;var d=new T(null);o&&qc(d,o),i&&(d.g=i),h&&rc(d,h),s&&(d.l=s),o=d}return s=e.D,i=e.ya,s&&i&&S(o,s,i),S(o,”VER”,e.la),$c(e,o),o}function Mb(e,i,s){if(i&&!e.J)throw Error(“Can’t create secondary domain capable XhrIo object.”);return(i=e.Ca&&!e.pa?new X(new Jc({eb:s})):new X(e.pa)).Ha(e.J),i}function gd(){}function hd(){}function Y(e,i){E.call(this),this.g=new Yc(i),this.l=e,this.h=i&&i.messageUrlParams||null,e=i&&i.messageHeaders||null,i&&i.clientProtocolHeaderRequired&&(e?e[“X-Client-Protocol”]=”webchannel”:e={“X-Client-Protocol”:”webchannel”}),this.g.o=e,e=i&&i.initMessageHeaders||null,i&&i.messageContentType&&(e?e[“X-WebChannel-Content-Type”]=i.messageContentType:e={“X-WebChannel-Content-Type”:i.messageContentType}),i&&i.va&&(e?e[“X-WebChannel-Client-Profile”]=i.va:e={“X-WebChannel-Client-Profile”:i.va}),this.g.S=e,(e=i&&i.Sb)&&!t(e)&&(this.g.m=e),this.v=i&&i.supportsCrossDomainXhr||!1,this.u=i&&i.sendRawJson||!1,(i=i&&i.httpSessionIdParam)&&!t(i)&&(this.g.D=i,null!==(e=this.h)&&i in e&&(i in(e=this.h)&&delete e[i])),this.j=new Z(this)}function id(e){nb.call(this),e.__headers__&&(this.headers=e.__headers__,this.statusCode=e.__status__,delete e.__headers__,delete e.__status__);var i=e.__sm__;if(i){e:{for(const s in i){e=s;break e}e=void 0}(this.i=e)&&(e=this.i,i=null!==i&&e in i?i[e]:void 0),this.data=i}else this.data=e}function jd(){ob.call(this),this.status=1}function Z(e){this.g=e}(e=X.prototype).Ha=function(e){this.J=e},e.ea=function(e,i,s,o){if(this.g)throw Error(“[goog.net.XhrIo] Object is active with another request=”+this.D+”; newUri=”+e);i=i?i.toUpperCase():”GET”,this.D=e,this.l=””,this.m=0,this.A=!1,this.h=!0,this.g=this.o?this.o.g():Ie.g(),this.v=this.o?lb(this.o):lb(Ie),this.g.onreadystatechange=p(this.Ea,this);try{this.B=!0,this.g.open(i,String(e),!0),this.B=!1}catch(e){return void Sc(this,e)}if(e=s||””,s=new Map(this.headers),o)if(Object.getPrototypeOf(o)===Object.prototype)for(var h in o)s.set(h,o[h]);else{if(“function”!=typeof o.keys||”function”!=typeof o.get)throw Error(“Unknown input type for opt_headers: “+String(o));for(const e of o.keys())s.set(e,o.get(e))}o=Array.from(s.keys()).find((e=>”content-type”==e.toLowerCase())),h=_.FormData&&e instanceof _.FormData,!(0<=Array.prototype.indexOf.call(xe,i,void 0))||o||h||s.set("Content-Type","application/x-www-form-urlencoded;charset=utf-8");for(const[e,i]of s)this.g.setRequestHeader(e,i);this.H&&(this.g.responseType=this.H),"withCredentials"in this.g&&this.g.withCredentials!==this.J&&(this.g.withCredentials=this.J);try{Tc(this),this.u=!0,this.g.send(e),this.u=!1}catch(e){Sc(this,e)}},e.abort=function(e){this.g&&this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1,this.m=e||7,F(this,"complete"),F(this,"abort"),Vc(this))},e.N=function(){this.g&&(this.h&&(this.h=!1,this.j=!0,this.g.abort(),this.j=!1),Vc(this,!0)),X.aa.N.call(this)},e.Ea=function(){this.s||(this.B||this.u||this.j?Wc(this):this.bb())},e.bb=function(){Wc(this)},e.isActive=function(){return!!this.g},e.Z=function(){try{return 2=this.R)){var e=2*this.R;this.j.info(“BP detection timer enabled: “+e),this.A=ub(p(this.ab,this),e)}},e.ab=function(){this.A&&(this.A=null,this.j.info(“BP detection timeout reached.”),this.j.info(“Buffering proxy detected and switch to long-polling!”),this.F=!1,this.M=!0,K(10),Zb(this),fd(this))},e.Za=function(){null!=this.C&&(this.C=null,Zb(this),$b(this),K(19))},e.fb=function(e){e?(this.j.info(“Successfully pinged google.com”),K(2)):(this.j.info(“Failed to ping google.com”),K(1))},e.isActive=function(){return!!this.l&&this.l.isActive(this)},(e=gd.prototype).ua=function(){},e.ta=function(){},e.sa=function(){},e.ra=function(){},e.isActive=function(){return!0},e.Na=function(){},hd.prototype.g=function(e,i){return new Y(e,i)},r(Y,E),Y.prototype.m=function(){this.g.l=this.j,this.v&&(this.g.J=!0),this.g.connect(this.l,this.h||void 0)},Y.prototype.close=function(){gc(this.g)},Y.prototype.o=function(e){var i=this.g;if(“string”==typeof e){var s={};s.__data__=e,e=s}else this.u&&((s={}).__data__=de(e),e=s);i.i.push(new ye(i.Ya++,e)),3==i.G&&fc(i)},Y.prototype.N=function(){this.g.l=null,delete this.j,gc(this.g),delete this.g,Y.aa.N.call(this)},r(id,nb),r(jd,ob),r(Z,gd),Z.prototype.ua=function(){F(this.g,”a”)},Z.prototype.ta=function(e){F(this.g,new id(e))},Z.prototype.sa=function(e){F(this.g,new jd)},Z.prototype.ra=function(){F(this.g,”b”)},hd.prototype.createWebChannel=hd.prototype.g,Y.prototype.send=Y.prototype.o,Y.prototype.open=Y.prototype.m,Y.prototype.close=Y.prototype.close,ae=function(){return new hd},oe=function(){return qb()},se=pe,ie={mb:0,pb:1,qb:2,Jb:3,Ob:4,Lb:5,Mb:6,Kb:7,Ib:8,Nb:9,PROXY:10,NOPROXY:11,Gb:12,Cb:13,Db:14,Bb:15,Eb:16,Fb:17,ib:18,hb:19,jb:20},Ee.NO_ERROR=0,Ee.TIMEOUT=8,Ee.HTTP_ERROR=6,re=Ee,Pe.COMPLETE=”complete”,ne=Pe,mb.EventType=ge,ge.OPEN=”a”,ge.CLOSE=”b”,ge.ERROR=”c”,ge.MESSAGE=”d”,E.prototype.listen=E.prototype.K,te=mb,X.prototype.listenOnce=X.prototype.L,X.prototype.getLastError=X.prototype.Ka,X.prototype.getLastErrorCode=X.prototype.Ba,X.prototype.getStatus=X.prototype.Z,X.prototype.getResponseJson=X.prototype.Oa,X.prototype.getResponseText=X.prototype.oa,X.prototype.send=X.prototype.ea,X.prototype.setWithCredentials=X.prototype.Ha,ee=X}).apply(void 0!==ue?ue:”undefined”!=typeof self?self:”undefined”!=typeof window?window:{});const ce=”@firebase/firestore”,le=”4.7.11″;class User{constructor(e){this.uid=e}isAuthenticated(){return null!=this.uid}toKey(){return this.isAuthenticated()?”uid:”+this.uid:”anonymous-user”}isEqual(e){return e.uid===this.uid}}User.UNAUTHENTICATED=new User(null),User.GOOGLE_CREDENTIALS=new User(“google-credentials-uid”),User.FIRST_PARTY=new User(“first-party-uid”),User.MOCK_USER=new User(“mock-user”);let _e=”11.6.1″;const he=new class Logger{constructor(e){this.name=e,this._logLevel=w,this._logHandler=defaultLogHandler,this._userLogHandler=null}get logLevel(){return this._logLevel}set logLevel(e){if(!(e in g))throw new TypeError(`Invalid value “${e}” assigned to \`logLevel\“);this._logLevel=e}setLogLevel(e){this._logLevel=”string”==typeof e?b[e]:e}get logHandler(){return this._logHandler}set logHandler(e){if(“function”!=typeof e)throw new TypeError(“Value assigned to `logHandler` must be a function”);this._logHandler=e}get userLogHandler(){return this._userLogHandler}set userLogHandler(e){this._userLogHandler=e}debug(…e){this._userLogHandler&&this._userLogHandler(this,g.DEBUG,…e),this._logHandler(this,g.DEBUG,…e)}log(…e){this._userLogHandler&&this._userLogHandler(this,g.VERBOSE,…e),this._logHandler(this,g.VERBOSE,…e)}info(…e){this._userLogHandler&&this._userLogHandler(this,g.INFO,…e),this._logHandler(this,g.INFO,…e)}warn(…e){this._userLogHandler&&this._userLogHandler(this,g.WARN,…e),this._logHandler(this,g.WARN,…e)}error(…e){this._userLogHandler&&this._userLogHandler(this,g.ERROR,…e),this._logHandler(this,g.ERROR,…e)}}(“@firebase/firestore”);function __PRIVATE_getLogLevel(){return he.logLevel}function setLogLevel(e){he.setLogLevel(e)}function __PRIVATE_logDebug(e,…i){if(he.logLevel<=g.DEBUG){const s=i.map(__PRIVATE_argToString);he.debug(`Firestore (${_e}): ${e}`,...s)}}function __PRIVATE_logError(e,...i){if(he.logLevel<=g.ERROR){const s=i.map(__PRIVATE_argToString);he.error(`Firestore (${_e}): ${e}`,...s)}}function __PRIVATE_logWarn(e,...i){if(he.logLevel<=g.WARN){const s=i.map(__PRIVATE_argToString);he.warn(`Firestore (${_e}): ${e}`,...s)}}function __PRIVATE_argToString(e){if("string"==typeof e)return e;try{return function __PRIVATE_formatJSON(e){return JSON.stringify(e)}(e)}catch(i){return e}}function fail(e,i,s){let o="Unexpected state";"string"==typeof i?o=i:s=i,__PRIVATE__fail(e,o,s)}function __PRIVATE__fail(e,i,s){let o=`FIRESTORE (${_e}) INTERNAL ASSERTION FAILED: ${i} (ID: ${e.toString(16)})`;if(void 0!==s)try{o+=" CONTEXT: "+JSON.stringify(s)}catch(e){o+=" CONTEXT: "+s}throw __PRIVATE_logError(o),new Error(o)}function __PRIVATE_hardAssert(e,i,s,o){let _="Unexpected state";"string"==typeof s?_=s:o=s,e||__PRIVATE__fail(i,_,o)}function __PRIVATE_debugAssert(e,i){e||fail(57014,i)}function __PRIVATE_debugCast(e,i){return e}const de={OK:"ok",CANCELLED:"cancelled",UNKNOWN:"unknown",INVALID_ARGUMENT:"invalid-argument",DEADLINE_EXCEEDED:"deadline-exceeded",NOT_FOUND:"not-found",ALREADY_EXISTS:"already-exists",PERMISSION_DENIED:"permission-denied",UNAUTHENTICATED:"unauthenticated",RESOURCE_EXHAUSTED:"resource-exhausted",FAILED_PRECONDITION:"failed-precondition",ABORTED:"aborted",OUT_OF_RANGE:"out-of-range",UNIMPLEMENTED:"unimplemented",INTERNAL:"internal",UNAVAILABLE:"unavailable",DATA_LOSS:"data-loss"};class FirestoreError extends FirebaseError{constructor(e,i){super(e,i),this.code=e,this.message=i,this.toString=()=>`${this.name}: [code=${this.code}]: ${this.message}`}}class __PRIVATE_Deferred{constructor(){this.promise=new Promise(((e,i)=>{this.resolve=e,this.reject=i}))}}class __PRIVATE_OAuthToken{constructor(e,i){this.user=i,this.type=”OAuth”,this.headers=new Map,this.headers.set(“Authorization”,`Bearer ${e}`)}}class __PRIVATE_EmptyAuthCredentialsProvider{getToken(){return Promise.resolve(null)}invalidateToken(){}start(e,i){e.enqueueRetryable((()=>i(User.UNAUTHENTICATED)))}shutdown(){}}class __PRIVATE_EmulatorAuthCredentialsProvider{constructor(e){this.token=e,this.changeListener=null}getToken(){return Promise.resolve(this.token)}invalidateToken(){}start(e,i){this.changeListener=i,e.enqueueRetryable((()=>i(this.token.user)))}shutdown(){this.changeListener=null}}class __PRIVATE_FirebaseAuthCredentialsProvider{constructor(e){this.t=e,this.currentUser=User.UNAUTHENTICATED,this.i=0,this.forceRefresh=!1,this.auth=null}start(e,i){__PRIVATE_hardAssert(void 0===this.o,42304);let s=this.i;const __PRIVATE_guardedChangeListener=e=>this.i!==s?(s=this.i,i(e)):Promise.resolve();let o=new __PRIVATE_Deferred;this.o=()=>{this.i++,this.currentUser=this.u(),o.resolve(),o=new __PRIVATE_Deferred,e.enqueueRetryable((()=>__PRIVATE_guardedChangeListener(this.currentUser)))};const __PRIVATE_awaitNextToken=()=>{const i=o;e.enqueueRetryable((async()=>{await i.promise,await __PRIVATE_guardedChangeListener(this.currentUser)}))},__PRIVATE_registerAuth=e=>{__PRIVATE_logDebug(“FirebaseAuthCredentialsProvider”,”Auth detected”),this.auth=e,this.o&&(this.auth.addAuthTokenListener(this.o),__PRIVATE_awaitNextToken())};this.t.onInit((e=>__PRIVATE_registerAuth(e))),setTimeout((()=>{if(!this.auth){const e=this.t.getImmediate({optional:!0});e?__PRIVATE_registerAuth(e):(__PRIVATE_logDebug(“FirebaseAuthCredentialsProvider”,”Auth not yet detected”),o.resolve(),o=new __PRIVATE_Deferred)}}),0),__PRIVATE_awaitNextToken()}getToken(){const e=this.i,i=this.forceRefresh;return this.forceRefresh=!1,this.auth?this.auth.getToken(i).then((i=>this.i!==e?(__PRIVATE_logDebug(“FirebaseAuthCredentialsProvider”,”getToken aborted due to token change.”),this.getToken()):i?(__PRIVATE_hardAssert(“string”==typeof i.accessToken,31837,{l:i}),new __PRIVATE_OAuthToken(i.accessToken,this.currentUser)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.auth&&this.o&&this.auth.removeAuthTokenListener(this.o),this.o=void 0}u(){const e=this.auth&&this.auth.getUid();return __PRIVATE_hardAssert(null===e||”string”==typeof e,2055,{h:e}),new User(e)}}class __PRIVATE_FirstPartyToken{constructor(e,i,s){this.P=e,this.T=i,this.I=s,this.type=”FirstParty”,this.user=User.FIRST_PARTY,this.A=new Map}R(){return this.I?this.I():null}get headers(){this.A.set(“X-Goog-AuthUser”,this.P);const e=this.R();return e&&this.A.set(“Authorization”,e),this.T&&this.A.set(“X-Goog-Iam-Authorization-Token”,this.T),this.A}}class __PRIVATE_FirstPartyAuthCredentialsProvider{constructor(e,i,s){this.P=e,this.T=i,this.I=s}getToken(){return Promise.resolve(new __PRIVATE_FirstPartyToken(this.P,this.T,this.I))}start(e,i){e.enqueueRetryable((()=>i(User.FIRST_PARTY)))}shutdown(){}invalidateToken(){}}class AppCheckToken{constructor(e){this.value=e,this.type=”AppCheck”,this.headers=new Map,e&&e.length>0&&this.headers.set(“x-firebase-appcheck”,this.value)}}class __PRIVATE_FirebaseAppCheckTokenProvider{constructor(e,i){this.V=i,this.forceRefresh=!1,this.appCheck=null,this.m=null,this.p=null,s(e)&&e.settings.appCheckToken&&(this.p=e.settings.appCheckToken)}start(e,i){__PRIVATE_hardAssert(void 0===this.o,3512);const onTokenChanged=e=>{null!=e.error&&__PRIVATE_logDebug(“FirebaseAppCheckTokenProvider”,`Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`);const s=e.token!==this.m;return this.m=e.token,__PRIVATE_logDebug(“FirebaseAppCheckTokenProvider”,`Received ${s?”new”:”existing”} token.`),s?i(e.token):Promise.resolve()};this.o=i=>{e.enqueueRetryable((()=>onTokenChanged(i)))};const __PRIVATE_registerAppCheck=e=>{__PRIVATE_logDebug(“FirebaseAppCheckTokenProvider”,”AppCheck detected”),this.appCheck=e,this.o&&this.appCheck.addTokenListener(this.o)};this.V.onInit((e=>__PRIVATE_registerAppCheck(e))),setTimeout((()=>{if(!this.appCheck){const e=this.V.getImmediate({optional:!0});e?__PRIVATE_registerAppCheck(e):__PRIVATE_logDebug(“FirebaseAppCheckTokenProvider”,”AppCheck not yet detected”)}}),0)}getToken(){if(this.p)return Promise.resolve(new AppCheckToken(this.p));const e=this.forceRefresh;return this.forceRefresh=!1,this.appCheck?this.appCheck.getToken(e).then((e=>e?(__PRIVATE_hardAssert(“string”==typeof e.token,44558,{tokenResult:e}),this.m=e.token,new AppCheckToken(e.token)):null)):Promise.resolve(null)}invalidateToken(){this.forceRefresh=!0}shutdown(){this.appCheck&&this.o&&this.appCheck.removeTokenListener(this.o),this.o=void 0}}class __PRIVATE_EmptyAppCheckTokenProvider{getToken(){return Promise.resolve(new AppCheckToken(“”))}invalidateToken(){}start(e,i){}shutdown(){}}function __PRIVATE_randomBytes(e){const i=”undefined”!=typeof self&&(self.crypto||self.msCrypto),s=new Uint8Array(e);if(i&&”function”==typeof i.getRandomValues)i.getRandomValues(s);else for(let i=0;ii?1:0}function __PRIVATE_compareUtf8Strings(e,i){let s=0;for(;s65535?2:1}return __PRIVATE_primitiveComparator(e.length,i.length)}function __PRIVATE_getUtf8SafeSubstring(e,i){return e.codePointAt(i)>65535?e.substring(i,i+2):e.substring(i,i+1)}function __PRIVATE_compareByteArrays$1(e,i){for(let s=0;ss(e,i[o])))}function __PRIVATE_immediateSuccessor(e){return e+”\0″}const me=-62135596800,fe=1e6;class Timestamp{static now(){return Timestamp.fromMillis(Date.now())}static fromDate(e){return Timestamp.fromMillis(e.getTime())}static fromMillis(e){const i=Math.floor(e/1e3),s=Math.floor((e-1e3*i)*fe);return new Timestamp(i,s)}constructor(e,i){if(this.seconds=e,this.nanoseconds=i,i<0)throw new FirestoreError(de.INVALID_ARGUMENT,"Timestamp nanoseconds out of range: "+i);if(i>=1e9)throw new FirestoreError(de.INVALID_ARGUMENT,”Timestamp nanoseconds out of range: “+i);if(e=253402300800)throw new FirestoreError(de.INVALID_ARGUMENT,”Timestamp seconds out of range: “+e)}toDate(){return new Date(this.toMillis())}toMillis(){return 1e3*this.seconds+this.nanoseconds/fe}_compareTo(e){return this.seconds===e.seconds?__PRIVATE_primitiveComparator(this.nanoseconds,e.nanoseconds):__PRIVATE_primitiveComparator(this.seconds,e.seconds)}isEqual(e){return e.seconds===this.seconds&&e.nanoseconds===this.nanoseconds}toString(){return”Timestamp(seconds=”+this.seconds+”, nanoseconds=”+this.nanoseconds+”)”}toJSON(){return{seconds:this.seconds,nanoseconds:this.nanoseconds}}valueOf(){const e=this.seconds-me;return String(e).padStart(12,”0″)+”.”+String(this.nanoseconds).padStart(9,”0″)}}class SnapshotVersion{static fromTimestamp(e){return new SnapshotVersion(e)}static min(){return new SnapshotVersion(new Timestamp(0,0))}static max(){return new SnapshotVersion(new Timestamp(253402300799,999999999))}constructor(e){this.timestamp=e}compareTo(e){return this.timestamp._compareTo(e.timestamp)}isEqual(e){return this.timestamp.isEqual(e.timestamp)}toMicroseconds(){return 1e6*this.timestamp.seconds+this.timestamp.nanoseconds/1e3}toString(){return”SnapshotVersion(“+this.timestamp.toString()+”)”}toTimestamp(){return this.timestamp}}const ge=”__name__”;class BasePath{constructor(e,i,s){void 0===i?i=0:i>e.length&&fail(637,{offset:i,range:e.length}),void 0===s?s=e.length-i:s>e.length-i&&fail(1746,{length:s,range:e.length-i}),this.segments=e,this.offset=i,this.len=s}get length(){return this.len}isEqual(e){return 0===BasePath.comparator(this,e)}child(e){const i=this.segments.slice(this.offset,this.limit());return e instanceof BasePath?e.forEach((e=>{i.push(e)})):i.push(e),this.construct(i)}limit(){return this.offset+this.length}popFirst(e){return e=void 0===e?1:e,this.construct(this.segments,this.offset+e,this.length-e)}popLast(){return this.construct(this.segments,this.offset,this.length-1)}firstSegment(){return this.segments[this.offset]}lastSegment(){return this.get(this.length-1)}get(e){return this.segments[this.offset+e]}isEmpty(){return 0===this.length}isPrefixOf(e){if(e.length=0)throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid segment (${s}). Paths must not contain // in them.`);i.push(…s.split(“/”).filter((e=>e.length>0)))}return new ResourcePath(i)}static emptyPath(){return new ResourcePath([])}}const pe=/^[_a-zA-Z][_a-zA-Z0-9]*$/;class FieldPath$1 extends BasePath{construct(e,i,s){return new FieldPath$1(e,i,s)}static isValidIdentifier(e){return pe.test(e)}canonicalString(){return this.toArray().map((e=>(e=e.replace(/\\/g,”\\\\”).replace(/`/g,”\\`”),FieldPath$1.isValidIdentifier(e)||(e=”`”+e+”`”),e))).join(“.”)}toString(){return this.canonicalString()}isKeyField(){return 1===this.length&&this.get(0)===ge}static keyField(){return new FieldPath$1([ge])}static fromServerFormat(e){const i=[];let s=””,o=0;const __PRIVATE_addCurrentSegment=()=>{if(0===s.length)throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid field path (${e}). Paths must not be empty, begin with ‘.’, end with ‘.’, or contain ‘..’`);i.push(s),s=””};let _=!1;for(;o=2&&this.path.get(this.path.length-2)===e}getCollectionGroup(){return this.path.get(this.path.length-2)}getCollectionPath(){return this.path.popLast()}isEqual(e){return null!==e&&0===ResourcePath.comparator(this.path,e.path)}toString(){return this.path.toString()}static comparator(e,i){return ResourcePath.comparator(e.path,i.path)}static isDocumentKey(e){return e.length%2==0}static fromSegments(e){return new DocumentKey(new ResourcePath(e.slice()))}}const Te=-1;class FieldIndex{constructor(e,i,s,o){this.indexId=e,this.collectionGroup=i,this.fields=s,this.indexState=o}}function __PRIVATE_fieldIndexGetArraySegment(e){return e.fields.find((e=>2===e.kind))}function __PRIVATE_fieldIndexGetDirectionalSegments(e){return e.fields.filter((e=>2!==e.kind))}function __PRIVATE_fieldIndexSemanticComparator(e,i){let s=__PRIVATE_primitiveComparator(e.collectionGroup,i.collectionGroup);if(0!==s)return s;for(let o=0;oe()))}}async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e){if(e.code!==de.FAILED_PRECONDITION||e.message!==Ie)throw e;__PRIVATE_logDebug(“LocalStore”,”Unexpectedly lost primary lease”)}class PersistencePromise{constructor(e){this.nextCallback=null,this.catchCallback=null,this.result=void 0,this.error=void 0,this.isDone=!1,this.callbackAttached=!1,e((e=>{this.isDone=!0,this.result=e,this.nextCallback&&this.nextCallback(e)}),(e=>{this.isDone=!0,this.error=e,this.catchCallback&&this.catchCallback(e)}))}catch(e){return this.next(void 0,e)}next(e,i){return this.callbackAttached&&fail(59440),this.callbackAttached=!0,this.isDone?this.error?this.wrapFailure(i,this.error):this.wrapSuccess(e,this.result):new PersistencePromise(((s,o)=>{this.nextCallback=i=>{this.wrapSuccess(e,i).next(s,o)},this.catchCallback=e=>{this.wrapFailure(i,e).next(s,o)}}))}toPromise(){return new Promise(((e,i)=>{this.next(e,i)}))}wrapUserFunction(e){try{const i=e();return i instanceof PersistencePromise?i:PersistencePromise.resolve(i)}catch(e){return PersistencePromise.reject(e)}}wrapSuccess(e,i){return e?this.wrapUserFunction((()=>e(i))):PersistencePromise.resolve(i)}wrapFailure(e,i){return e?this.wrapUserFunction((()=>e(i))):PersistencePromise.reject(i)}static resolve(e){return new PersistencePromise(((i,s)=>{i(e)}))}static reject(e){return new PersistencePromise(((i,s)=>{s(e)}))}static waitFor(e){return new PersistencePromise(((i,s)=>{let o=0,_=0,h=!1;e.forEach((e=>{++o,e.next((()=>{++_,h&&_===o&&i()}),(e=>s(e)))})),h=!0,_===o&&i()}))}static or(e){let i=PersistencePromise.resolve(!1);for(const s of e)i=i.next((e=>e?PersistencePromise.resolve(e):s()));return i}static forEach(e,i){const s=[];return e.forEach(((e,o)=>{s.push(i.call(this,e,o))})),this.waitFor(s)}static mapArray(e,i){return new PersistencePromise(((s,o)=>{const _=e.length,h=new Array(_);let d=0;for(let f=0;f<_;f++){const g=f;i(e[g]).next((e=>{h[g]=e,++d,d===_&&s(h)}),(e=>o(e)))}}))}static doWhile(e,i){return new PersistencePromise(((s,o)=>{const process=()=>{!0===e()?i().next((()=>{process()}),o):s()};process()}))}}const Ee=”SimpleDb”;class __PRIVATE_SimpleDbTransaction{static open(e,i,s,o){try{return new __PRIVATE_SimpleDbTransaction(i,e.transaction(o,s))}catch(e){throw new __PRIVATE_IndexedDbTransactionError(i,e)}}constructor(e,i){this.action=e,this.transaction=i,this.aborted=!1,this.S=new __PRIVATE_Deferred,this.transaction.oncomplete=()=>{this.S.resolve()},this.transaction.onabort=()=>{i.error?this.S.reject(new __PRIVATE_IndexedDbTransactionError(e,i.error)):this.S.resolve()},this.transaction.onerror=i=>{const s=__PRIVATE_checkForAndReportiOSError(i.target.error);this.S.reject(new __PRIVATE_IndexedDbTransactionError(e,s))}}get D(){return this.S.promise}abort(e){e&&this.S.reject(e),this.aborted||(__PRIVATE_logDebug(Ee,”Aborting transaction:”,e?e.message:”Client-initiated abort”),this.aborted=!0,this.transaction.abort())}v(){const e=this.transaction;this.aborted||”function”!=typeof e.commit||e.commit()}store(e){const i=this.transaction.objectStore(e);return new __PRIVATE_SimpleDbStore(i)}}class __PRIVATE_SimpleDb{static delete(e){return __PRIVATE_logDebug(Ee,”Removing database:”,e),__PRIVATE_wrapRequest(getGlobal().indexedDB.deleteDatabase(e)).toPromise()}static C(){if(!function isIndexedDBAvailable(){try{return”object”==typeof indexedDB}catch(e){return!1}}())return!1;if(__PRIVATE_SimpleDb.F())return!0;const e=getUA(),i=__PRIVATE_SimpleDb.M(e),s=00||e.indexOf(“Trident/”)>0||e.indexOf(“Edge/”)>0||s||_)}static F(){var e;return”undefined”!=typeof process&&”YES”===(null===(e=process.__PRIVATE_env)||void 0===e?void 0:e.O)}static N(e,i){return e.store(i)}static M(e){const i=e.match(/i(?:phone|pad|pod) os ([\d_]+)/i),s=i?i[1].split(“_”).slice(0,2).join(“.”):”-1″;return Number(s)}constructor(e,i,s){this.name=e,this.version=i,this.B=s,this.L=null,12.2===__PRIVATE_SimpleDb.M(getUA())&&__PRIVATE_logError(“Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.”)}async k(e){return this.db||(__PRIVATE_logDebug(Ee,”Opening database:”,this.name),this.db=await new Promise(((i,s)=>{const o=indexedDB.open(this.name,this.version);o.onsuccess=e=>{const s=e.target.result;i(s)},o.onblocked=()=>{s(new __PRIVATE_IndexedDbTransactionError(e,”Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.”))},o.onerror=i=>{const o=i.target.error;”VersionError”===o.name?s(new FirestoreError(de.FAILED_PRECONDITION,”A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.”)):”InvalidStateError”===o.name?s(new FirestoreError(de.FAILED_PRECONDITION,”Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: “+o)):s(new __PRIVATE_IndexedDbTransactionError(e,o))},o.onupgradeneeded=e=>{__PRIVATE_logDebug(Ee,’Database “‘+this.name+'” requires upgrade from version:’,e.oldVersion);const i=e.target.result;if(null!==this.L&&this.L!==e.oldVersion)throw new Error(`refusing to open IndexedDB database due to potential corruption of the IndexedDB database data; this corruption could be caused by clicking the “clear site data” button in a web browser; try reloading the web page to re-initialize the IndexedDB database: lastClosedDbVersion=${this.L}, event.oldVersion=${e.oldVersion}, event.newVersion=${e.newVersion}, db.version=${i.version}`);this.B.q(i,o.transaction,e.oldVersion,this.version).next((()=>{__PRIVATE_logDebug(Ee,”Database upgrade to version “+this.version+” complete”)}))}})),this.db.addEventListener(“close”,(e=>{const i=e.target;this.L=i.version}),{passive:!0})),this.$&&(this.db.onversionchange=e=>this.$(e)),this.db}U(e){this.$=e,this.db&&(this.db.onversionchange=i=>e(i))}async runTransaction(e,i,s,o){const _=”readonly”===i;let h=0;for(;;){++h;try{this.db=await this.k(e);const i=__PRIVATE_SimpleDbTransaction.open(this.db,e,_?”readonly”:”readwrite”,s),h=o(i).next((e=>(i.v(),e))).catch((e=>(i.abort(e),PersistencePromise.reject(e)))).toPromise();return h.catch((()=>{})),await i.D,h}catch(e){const i=e,s=”FirebaseError”!==i.name&&h<3;if(__PRIVATE_logDebug(Ee,"Transaction failed with error:",i.message,"Retrying:",s),this.close(),!s)return Promise.reject(i)}}}close(){this.db&&this.db.close(),this.db=void 0}}function __PRIVATE_getAndroidVersion(e){const i=e.match(/Android ([\d.]+)/i),s=i?i[1].split(".").slice(0,2).join("."):"-1";return Number(s)}class __PRIVATE_IterationController{constructor(e){this.K=e,this.W=!1,this.G=null}get isDone(){return this.W}get j(){return this.G}set cursor(e){this.K=e}done(){this.W=!0}H(e){this.G=e}delete(){return __PRIVATE_wrapRequest(this.K.delete())}}class __PRIVATE_IndexedDbTransactionError extends FirestoreError{constructor(e,i){super(de.UNAVAILABLE,`IndexedDB transaction '${e}' failed: ${i}`),this.name="IndexedDbTransactionError"}}function __PRIVATE_isIndexedDbTransactionError(e){return"IndexedDbTransactionError"===e.name}class __PRIVATE_SimpleDbStore{constructor(e){this.store=e}put(e,i){let s;return void 0!==i?(__PRIVATE_logDebug(Ee,"PUT",this.store.name,e,i),s=this.store.put(i,e)):(__PRIVATE_logDebug(Ee,"PUT",this.store.name,"“,e),s=this.store.put(e)),__PRIVATE_wrapRequest(s)}add(e){return __PRIVATE_logDebug(Ee,”ADD”,this.store.name,e,e),__PRIVATE_wrapRequest(this.store.add(e))}get(e){return __PRIVATE_wrapRequest(this.store.get(e)).next((i=>(void 0===i&&(i=null),__PRIVATE_logDebug(Ee,”GET”,this.store.name,e,i),i)))}delete(e){return __PRIVATE_logDebug(Ee,”DELETE”,this.store.name,e),__PRIVATE_wrapRequest(this.store.delete(e))}count(){return __PRIVATE_logDebug(Ee,”COUNT”,this.store.name),__PRIVATE_wrapRequest(this.store.count())}J(e,i){const s=this.options(e,i),o=s.index?this.store.index(s.index):this.store;if(“function”==typeof o.getAll){const e=o.getAll(s.range);return new PersistencePromise(((i,s)=>{e.onerror=e=>{s(e.target.error)},e.onsuccess=e=>{i(e.target.result)}}))}{const e=this.cursor(s),i=[];return this.Y(e,((e,s)=>{i.push(s)})).next((()=>i))}}Z(e,i){const s=this.store.getAll(e,null===i?void 0:i);return new PersistencePromise(((e,i)=>{s.onerror=e=>{i(e.target.error)},s.onsuccess=i=>{e(i.target.result)}}))}X(e,i){__PRIVATE_logDebug(Ee,”DELETE ALL”,this.store.name);const s=this.options(e,i);s.ee=!1;const o=this.cursor(s);return this.Y(o,((e,i,s)=>s.delete()))}te(e,i){let s;i?s=e:(s={},i=e);const o=this.cursor(s);return this.Y(o,i)}ne(e){const i=this.cursor({});return new PersistencePromise(((s,o)=>{i.onerror=e=>{const i=__PRIVATE_checkForAndReportiOSError(e.target.error);o(i)},i.onsuccess=i=>{const o=i.target.result;o?e(o.primaryKey,o.value).next((e=>{e?o.continue():s()})):s()}}))}Y(e,i){const s=[];return new PersistencePromise(((o,_)=>{e.onerror=e=>{_(e.target.error)},e.onsuccess=e=>{const _=e.target.result;if(!_)return void o();const h=new __PRIVATE_IterationController(_),d=i(_.primaryKey,_.value,h);if(d instanceof PersistencePromise){const e=d.catch((e=>(h.done(),PersistencePromise.reject(e))));s.push(e)}h.isDone?o():null===h.j?_.continue():_.continue(h.j)}})).next((()=>PersistencePromise.waitFor(s)))}options(e,i){let s;return void 0!==e&&(“string”==typeof e?s=e:i=e),{index:s,range:i}}cursor(e){let i=”next”;if(e.reverse&&(i=”prev”),e.index){const s=this.store.index(e.index);return e.ee?s.openKeyCursor(e.range,i):s.openCursor(e.range,i)}return this.store.openCursor(e.range,i)}}function __PRIVATE_wrapRequest(e){return new PersistencePromise(((i,s)=>{e.onsuccess=e=>{const s=e.target.result;i(s)},e.onerror=e=>{const i=__PRIVATE_checkForAndReportiOSError(e.target.error);s(i)}}))}let Pe=!1;function __PRIVATE_checkForAndReportiOSError(e){const i=__PRIVATE_SimpleDb.M(getUA());if(i>=12.2&&i<13){const i="An internal error was encountered in the Indexed Database server";if(e.message.indexOf(i)>=0){const e=new FirestoreError(“internal”,`IOS_INDEXEDDB_BUG1: IndexedDb has thrown ‘${i}’. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);return Pe||(Pe=!0,setTimeout((()=>{throw e}),0)),e}}return e}const Ae=”IndexBackfiller”;class __PRIVATE_IndexBackfillerScheduler{constructor(e,i){this.asyncQueue=e,this.re=i,this.task=null}start(){this.ie(15e3)}stop(){this.task&&(this.task.cancel(),this.task=null)}get started(){return null!==this.task}ie(e){__PRIVATE_logDebug(Ae,`Scheduled in ${e}ms`),this.task=this.asyncQueue.enqueueAfterDelay(“index_backfill”,e,(async()=>{this.task=null;try{const e=await this.re.se();__PRIVATE_logDebug(Ae,`Documents written: ${e}`)}catch(e){__PRIVATE_isIndexedDbTransactionError(e)?__PRIVATE_logDebug(Ae,”Ignoring IndexedDB error during index backfill: “,e):await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}await this.ie(6e4)}))}}class __PRIVATE_IndexBackfiller{constructor(e,i){this.localStore=e,this.persistence=i}async se(e=50){return this.persistence.runTransaction(“Backfill Indexes”,”readwrite-primary”,(i=>this.oe(i,e)))}oe(e,i){const s=new Set;let o=i,_=!0;return PersistencePromise.doWhile((()=>!0===_&&o>0),(()=>this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((i=>{if(null!==i&&!s.has(i))return __PRIVATE_logDebug(Ae,`Processing collection: ${i}`),this._e(e,i,o).next((e=>{o-=e,s.add(i)}));_=!1})))).next((()=>i-o))}_e(e,i,s){return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e,i).next((o=>this.localStore.localDocuments.getNextDocuments(e,i,o,s).next((s=>{const _=s.changes;return this.localStore.indexManager.updateIndexEntries(e,_).next((()=>this.ae(o,s))).next((s=>(__PRIVATE_logDebug(Ae,`Updating offset: ${s}`),this.localStore.indexManager.updateCollectionGroup(e,i,s)))).next((()=>_.size))}))))}ae(e,i){let s=e;return i.changes.forEach(((e,i)=>{const o=__PRIVATE_newIndexOffsetFromDocument(i);__PRIVATE_indexOffsetComparator(o,s)>0&&(s=o)})),new IndexOffset(s.readTime,s.documentKey,Math.max(i.batchId,e.largestBatchId))}}class __PRIVATE_ListenSequence{constructor(e,i){this.previousValue=e,i&&(i.sequenceNumberHandler=e=>this.ue(e),this.ce=e=>i.writeSequenceNumber(e))}ue(e){return this.previousValue=Math.max(e,this.previousValue),this.previousValue}next(){const e=++this.previousValue;return this.ce&&this.ce(e),e}}__PRIVATE_ListenSequence.le=-1;const Re=-1;function __PRIVATE_isNullOrUndefined(e){return null==e}function __PRIVATE_isNegativeZero(e){return 0===e&&1/e==-1/0}function isSafeInteger(e){return”number”==typeof e&&Number.isInteger(e)&&!__PRIVATE_isNegativeZero(e)&&e<=Number.MAX_SAFE_INTEGER&&e>=Number.MIN_SAFE_INTEGER}const ye=””;function __PRIVATE_encodeResourcePath(e){let i=””;for(let s=0;s0&&(i=__PRIVATE_encodeSeparator(i)),i=__PRIVATE_encodeSegment(e.get(s),i);return __PRIVATE_encodeSeparator(i)}function __PRIVATE_encodeSegment(e,i){let s=i;const o=e.length;for(let i=0;i=2,64408,{path:e}),2===i)return __PRIVATE_hardAssert(e.charAt(0)===ye&&””===e.charAt(1),56145,{path:e}),ResourcePath.emptyPath();const __PRIVATE_lastReasonableEscapeIndex=i-2,s=[];let o=””;for(let _=0;___PRIVATE_lastReasonableEscapeIndex)&&fail(50515,{path:e}),e.charAt(i+1)){case””:const h=e.substring(_,i);let d;0===o.length?d=h:(o+=h,d=o,o=””),s.push(d);break;case””:o+=e.substring(_,i),o+=”\0″;break;case””:o+=e.substring(_,i+1);break;default:fail(61167,{path:e})}_=i+2}return new ResourcePath(s)}const Ve=”remoteDocuments”,ve=”owner”,be=”owner”,Se=”mutationQueues”,we=”mutations”,De=”batchId”,Ce=”userMutationsIndex”,Fe=[“userId”,”batchId”];function __PRIVATE_newDbDocumentMutationPrefixForPath(e,i){return[e,__PRIVATE_encodeResourcePath(i)]}function __PRIVATE_newDbDocumentMutationKey(e,i,s){return[e,__PRIVATE_encodeResourcePath(i),s]}const xe={},Me=”documentMutations”,Ne=”remoteDocumentsV14″,ke=[“prefixPath”,”collectionGroup”,”readTime”,”documentId”],Oe=”documentKeyIndex”,Le=[“prefixPath”,”collectionGroup”,”documentId”],Be=”collectionGroupIndex”,qe=[“collectionGroup”,”readTime”,”prefixPath”,”documentId”],Ue=”remoteDocumentGlobal”,Ke=”remoteDocumentGlobalKey”,Qe=”targets”,ze=”queryTargetsIndex”,Ge=[“canonicalId”,”targetId”],je=”targetDocuments”,We=[“targetId”,”path”],$e=”documentTargetsIndex”,He=[“path”,”targetId”],Je=”targetGlobalKey”,Ye=”targetGlobal”,Xe=”collectionParents”,Ze=[“collectionId”,”parent”],et=”clientMetadata”,tt=”bundles”,nt=”namedQueries”,rt=”indexConfiguration”,it=”collectionGroupIndex”,st=”indexState”,ot=[“indexId”,”uid”],at=”sequenceNumberIndex”,ut=[“uid”,”sequenceNumber”],ct=”indexEntries”,lt=[“indexId”,”uid”,”arrayValue”,”directionalValue”,”orderedDocumentKey”,”documentKey”],_t=”documentKeyIndex”,ht=[“indexId”,”uid”,”orderedDocumentKey”],dt=”documentOverlays”,mt=[“userId”,”collectionPath”,”documentId”],ft=”collectionPathOverlayIndex”,gt=[“userId”,”collectionPath”,”largestBatchId”],pt=”collectionGroupOverlayIndex”,Tt=[“userId”,”collectionGroup”,”largestBatchId”],It=”globals”,Et=[Se,we,Me,Ve,Qe,ve,Ye,je,et,Ue,Xe,tt,nt],Pt=[…Et,dt],At=[Se,we,Me,Ne,Qe,ve,Ye,je,et,Ue,Xe,tt,nt,dt],Rt=At,yt=[…Rt,rt,st,ct],Vt=yt,vt=[…yt,It];class __PRIVATE_IndexedDbTransaction extends PersistenceTransaction{constructor(e,i){super(),this.he=e,this.currentSequenceNumber=i}}function __PRIVATE_getStore(e,i){const s=__PRIVATE_debugCast(e);return __PRIVATE_SimpleDb.N(s.he,i)}function __PRIVATE_objectSize(e){let i=0;for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i++;return i}function forEach(e,i){for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&i(s,e[s])}function __PRIVATE_mapToArray(e,i){const s=[];for(const o in e)Object.prototype.hasOwnProperty.call(e,o)&&s.push(i(e[o],o,e));return s}function isEmpty(e){for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i))return!1;return!0}class SortedMap{constructor(e,i){this.comparator=e,this.root=i||LLRBNode.EMPTY}insert(e,i){return new SortedMap(this.comparator,this.root.insert(e,i,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}remove(e){return new SortedMap(this.comparator,this.root.remove(e,this.comparator).copy(null,null,LLRBNode.BLACK,null,null))}get(e){let i=this.root;for(;!i.isEmpty();){const s=this.comparator(e,i.key);if(0===s)return i.value;s<0?i=i.left:s>0&&(i=i.right)}return null}indexOf(e){let i=0,s=this.root;for(;!s.isEmpty();){const o=this.comparator(e,s.key);if(0===o)return i+s.left.size;o<0?s=s.left:(i+=s.left.size+1,s=s.right)}return-1}isEmpty(){return this.root.isEmpty()}get size(){return this.root.size}minKey(){return this.root.minKey()}maxKey(){return this.root.maxKey()}inorderTraversal(e){return this.root.inorderTraversal(e)}forEach(e){this.inorderTraversal(((i,s)=>(e(i,s),!1)))}toString(){const e=[];return this.inorderTraversal(((i,s)=>(e.push(`${i}:${s}`),!1))),`{${e.join(“, “)}}`}reverseTraversal(e){return this.root.reverseTraversal(e)}getIterator(){return new SortedMapIterator(this.root,null,this.comparator,!1)}getIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!1)}getReverseIterator(){return new SortedMapIterator(this.root,null,this.comparator,!0)}getReverseIteratorFrom(e){return new SortedMapIterator(this.root,e,this.comparator,!0)}}class SortedMapIterator{constructor(e,i,s,o){this.isReverse=o,this.nodeStack=[];let _=1;for(;!e.isEmpty();)if(_=i?s(e.key,i):1,i&&o&&(_*=-1),_<0)e=this.isReverse?e.left:e.right;else{if(0===_){this.nodeStack.push(e);break}this.nodeStack.push(e),e=this.isReverse?e.right:e.left}}getNext(){let e=this.nodeStack.pop();const i={key:e.key,value:e.value};if(this.isReverse)for(e=e.left;!e.isEmpty();)this.nodeStack.push(e),e=e.right;else for(e=e.right;!e.isEmpty();)this.nodeStack.push(e),e=e.left;return i}hasNext(){return this.nodeStack.length>0}peek(){if(0===this.nodeStack.length)return null;const e=this.nodeStack[this.nodeStack.length-1];return{key:e.key,value:e.value}}}class LLRBNode{constructor(e,i,s,o,_){this.key=e,this.value=i,this.color=null!=s?s:LLRBNode.RED,this.left=null!=o?o:LLRBNode.EMPTY,this.right=null!=_?_:LLRBNode.EMPTY,this.size=this.left.size+1+this.right.size}copy(e,i,s,o,_){return new LLRBNode(null!=e?e:this.key,null!=i?i:this.value,null!=s?s:this.color,null!=o?o:this.left,null!=_?_:this.right)}isEmpty(){return!1}inorderTraversal(e){return this.left.inorderTraversal(e)||e(this.key,this.value)||this.right.inorderTraversal(e)}reverseTraversal(e){return this.right.reverseTraversal(e)||e(this.key,this.value)||this.left.reverseTraversal(e)}min(){return this.left.isEmpty()?this:this.left.min()}minKey(){return this.min().key}maxKey(){return this.right.isEmpty()?this.key:this.right.maxKey()}insert(e,i,s){let o=this;const _=s(e,o.key);return o=_<0?o.copy(null,null,null,o.left.insert(e,i,s),null):0===_?o.copy(null,i,null,null,null):o.copy(null,null,null,null,o.right.insert(e,i,s)),o.fixUp()}removeMin(){if(this.left.isEmpty())return LLRBNode.EMPTY;let e=this;return e.left.isRed()||e.left.left.isRed()||(e=e.moveRedLeft()),e=e.copy(null,null,null,e.left.removeMin(),null),e.fixUp()}remove(e,i){let s,o=this;if(i(e,o.key)<0)o.left.isEmpty()||o.left.isRed()||o.left.left.isRed()||(o=o.moveRedLeft()),o=o.copy(null,null,null,o.left.remove(e,i),null);else{if(o.left.isRed()&&(o=o.rotateRight()),o.right.isEmpty()||o.right.isRed()||o.right.left.isRed()||(o=o.moveRedRight()),0===i(e,o.key)){if(o.right.isEmpty())return LLRBNode.EMPTY;s=o.right.min(),o=o.copy(s.key,s.value,null,null,o.right.removeMin())}o=o.copy(null,null,null,null,o.right.remove(e,i))}return o.fixUp()}isRed(){return this.color}fixUp(){let e=this;return e.right.isRed()&&!e.left.isRed()&&(e=e.rotateLeft()),e.left.isRed()&&e.left.left.isRed()&&(e=e.rotateRight()),e.left.isRed()&&e.right.isRed()&&(e=e.colorFlip()),e}moveRedLeft(){let e=this.colorFlip();return e.right.left.isRed()&&(e=e.copy(null,null,null,null,e.right.rotateRight()),e=e.rotateLeft(),e=e.colorFlip()),e}moveRedRight(){let e=this.colorFlip();return e.left.left.isRed()&&(e=e.rotateRight(),e=e.colorFlip()),e}rotateLeft(){const e=this.copy(null,null,LLRBNode.RED,null,this.right.left);return this.right.copy(null,null,this.color,e,null)}rotateRight(){const e=this.copy(null,null,LLRBNode.RED,this.left.right,null);return this.left.copy(null,null,this.color,null,e)}colorFlip(){const e=this.left.copy(null,null,!this.left.color,null,null),i=this.right.copy(null,null,!this.right.color,null,null);return this.copy(null,null,!this.color,e,i)}checkMaxDepth(){const e=this.check();return Math.pow(2,e)<=this.size+1}check(){if(this.isRed()&&this.left.isRed())throw fail(43730,{key:this.key,value:this.value});if(this.right.isRed())throw fail(14113,{key:this.key,value:this.value});const e=this.left.check();if(e!==this.right.check())throw fail(27949);return e+(this.isRed()?0:1)}}LLRBNode.EMPTY=null,LLRBNode.RED=!0,LLRBNode.BLACK=!1,LLRBNode.EMPTY=new class LLRBEmptyNode{constructor(){this.size=0}get key(){throw fail(57766)}get value(){throw fail(16141)}get color(){throw fail(16727)}get left(){throw fail(29726)}get right(){throw fail(36894)}copy(e,i,s,o,_){return this}insert(e,i,s){return new LLRBNode(e,i)}remove(e,i){return this}isEmpty(){return!0}inorderTraversal(e){return!1}reverseTraversal(e){return!1}minKey(){return null}maxKey(){return null}isRed(){return!1}checkMaxDepth(){return!0}check(){return 0}};class SortedSet{constructor(e){this.comparator=e,this.data=new SortedMap(this.comparator)}has(e){return null!==this.data.get(e)}first(){return this.data.minKey()}last(){return this.data.maxKey()}get size(){return this.data.size}indexOf(e){return this.data.indexOf(e)}forEach(e){this.data.inorderTraversal(((i,s)=>(e(i),!1)))}forEachInRange(e,i){const s=this.data.getIteratorFrom(e[0]);for(;s.hasNext();){const o=s.getNext();if(this.comparator(o.key,e[1])>=0)return;i(o.key)}}forEachWhile(e,i){let s;for(s=void 0!==i?this.data.getIteratorFrom(i):this.data.getIterator();s.hasNext();)if(!e(s.getNext().key))return}firstAfterOrEqual(e){const i=this.data.getIteratorFrom(e);return i.hasNext()?i.getNext().key:null}getIterator(){return new SortedSetIterator(this.data.getIterator())}getIteratorFrom(e){return new SortedSetIterator(this.data.getIteratorFrom(e))}add(e){return this.copy(this.data.remove(e).insert(e,!0))}delete(e){return this.has(e)?this.copy(this.data.remove(e)):this}isEmpty(){return this.data.isEmpty()}unionWith(e){let i=this;return i.size{i=i.add(e)})),i}isEqual(e){if(!(e instanceof SortedSet))return!1;if(this.size!==e.size)return!1;const i=this.data.getIterator(),s=e.data.getIterator();for(;i.hasNext();){const e=i.getNext().key,o=s.getNext().key;if(0!==this.comparator(e,o))return!1}return!0}toArray(){const e=[];return this.forEach((i=>{e.push(i)})),e}toString(){const e=[];return this.forEach((i=>e.push(i))),”SortedSet(“+e.toString()+”)”}copy(e){const i=new SortedSet(this.comparator);return i.data=e,i}}class SortedSetIterator{constructor(e){this.iter=e}getNext(){return this.iter.getNext().key}hasNext(){return this.iter.hasNext()}}function __PRIVATE_advanceIterator(e){return e.hasNext()?e.getNext():void 0}class FieldMask{constructor(e){this.fields=e,e.sort(FieldPath$1.comparator)}static empty(){return new FieldMask([])}unionWith(e){let i=new SortedSet(FieldPath$1.comparator);for(const e of this.fields)i=i.add(e);for(const s of e)i=i.add(s);return new FieldMask(i.toArray())}covers(e){for(const i of this.fields)if(i.isPrefixOf(e))return!0;return!1}isEqual(e){return __PRIVATE_arrayEquals(this.fields,e.fields,((e,i)=>e.isEqual(i)))}}class __PRIVATE_Base64DecodeError extends Error{constructor(){super(…arguments),this.name=”Base64DecodeError”}}function __PRIVATE_isBase64Available(){return”undefined”!=typeof atob}class ByteString{constructor(e){this.binaryString=e}static fromBase64String(e){const i=function __PRIVATE_decodeBase64(e){try{return atob(e)}catch(e){throw”undefined”!=typeof DOMException&&e instanceof DOMException?new __PRIVATE_Base64DecodeError(“Invalid base64 string: “+e):e}}(e);return new ByteString(i)}static fromUint8Array(e){const i=function __PRIVATE_binaryStringFromUint8Array(e){let i=””;for(let s=0;se__PRIVATE_valueEquals(e,i)))}function __PRIVATE_valueCompare(e,i){if(e===i)return 0;const s=__PRIVATE_typeOrder(e),o=__PRIVATE_typeOrder(i);if(s!==o)return __PRIVATE_primitiveComparator(s,o);switch(s){case 0:case 9007199254740991:return 0;case 1:return __PRIVATE_primitiveComparator(e.booleanValue,i.booleanValue);case 2:return function __PRIVATE_compareNumbers(e,i){const s=__PRIVATE_normalizeNumber(e.integerValue||e.doubleValue),o=__PRIVATE_normalizeNumber(i.integerValue||i.doubleValue);return so?1:s===o?0:isNaN(s)?isNaN(o)?0:-1:1}(e,i);case 3:return __PRIVATE_compareTimestamps(e.timestampValue,i.timestampValue);case 4:return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e),__PRIVATE_getLocalWriteTime(i));case 5:return __PRIVATE_compareUtf8Strings(e.stringValue,i.stringValue);case 6:return function __PRIVATE_compareBlobs(e,i){const s=__PRIVATE_normalizeByteString(e),o=__PRIVATE_normalizeByteString(i);return s.compareTo(o)}(e.bytesValue,i.bytesValue);case 7:return function __PRIVATE_compareReferences(e,i){const s=e.split(“/”),o=i.split(“/”);for(let e=0;ee+__PRIVATE_estimateByteSize(i)),0)}(e.arrayValue);case 10:case 11:return function __PRIVATE_estimateMapByteSize(e){let i=0;return forEach(e.fields,((e,s)=>{i+=e.length+__PRIVATE_estimateByteSize(s)})),i}(e.mapValue);default:throw fail(13486,{value:e})}}function __PRIVATE_refValue(e,i){return{referenceValue:`projects/${e.projectId}/databases/${e.database}/documents/${i.path.canonicalString()}`}}function isInteger(e){return!!e&&”integerValue”in e}function isArray(e){return!!e&&”arrayValue”in e}function __PRIVATE_isNullValue(e){return!!e&&”nullValue”in e}function __PRIVATE_isNanValue(e){return!!e&&”doubleValue”in e&&isNaN(Number(e.doubleValue))}function __PRIVATE_isMapValue(e){return!!e&&”mapValue”in e}function __PRIVATE_isVectorValue(e){var i,s;return(null===(s=((null===(i=null==e?void 0:e.mapValue)||void 0===i?void 0:i.fields)||{})[xt])||void 0===s?void 0:s.stringValue)===kt}function __PRIVATE_deepClone(e){if(e.geoPointValue)return{geoPointValue:Object.assign({},e.geoPointValue)};if(e.timestampValue&&”object”==typeof e.timestampValue)return{timestampValue:Object.assign({},e.timestampValue)};if(e.mapValue){const i={mapValue:{fields:{}}};return forEach(e.mapValue.fields,((e,s)=>i.mapValue.fields[e]=__PRIVATE_deepClone(s))),i}if(e.arrayValue){const i={arrayValue:{values:[]}};for(let s=0;s<(e.arrayValue.values||[]).length;++s)i.arrayValue.values[s]=__PRIVATE_deepClone(e.arrayValue.values[s]);return i}return Object.assign({},e)}function __PRIVATE_isMaxValue(e){return(((e.mapValue||{}).fields||{}).__type__||{}).stringValue===Mt}const Bt={mapValue:{fields:{[xt]:{stringValue:kt},[Ot]:{arrayValue:{}}}}};function __PRIVATE_valuesGetLowerBound(e){return"nullValue"in e?Lt:"booleanValue"in e?{booleanValue:!1}:"integerValue"in e||"doubleValue"in e?{doubleValue:NaN}:"timestampValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"stringValue"in e?{stringValue:""}:"bytesValue"in e?{bytesValue:""}:"referenceValue"in e?__PRIVATE_refValue(DatabaseId.empty(),DocumentKey.empty()):"geoPointValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"arrayValue"in e?{arrayValue:{}}:"mapValue"in e?__PRIVATE_isVectorValue(e)?Bt:{mapValue:{}}:fail(35942,{value:e})}function __PRIVATE_valuesGetUpperBound(e){return"nullValue"in e?{booleanValue:!1}:"booleanValue"in e?{doubleValue:NaN}:"integerValue"in e||"doubleValue"in e?{timestampValue:{seconds:Number.MIN_SAFE_INTEGER}}:"timestampValue"in e?{stringValue:""}:"stringValue"in e?{bytesValue:""}:"bytesValue"in e?__PRIVATE_refValue(DatabaseId.empty(),DocumentKey.empty()):"referenceValue"in e?{geoPointValue:{latitude:-90,longitude:-180}}:"geoPointValue"in e?{arrayValue:{}}:"arrayValue"in e?Bt:"mapValue"in e?__PRIVATE_isVectorValue(e)?{mapValue:{}}:Nt:fail(61959,{value:e})}function __PRIVATE_lowerBoundCompare(e,i){const s=__PRIVATE_valueCompare(e.value,i.value);return 0!==s?s:e.inclusive&&!i.inclusive?-1:!e.inclusive&&i.inclusive?1:0}function __PRIVATE_upperBoundCompare(e,i){const s=__PRIVATE_valueCompare(e.value,i.value);return 0!==s?s:e.inclusive&&!i.inclusive?1:!e.inclusive&&i.inclusive?-1:0}class ObjectValue{constructor(e){this.value=e}static empty(){return new ObjectValue({mapValue:{}})}field(e){if(e.isEmpty())return this.value;{let i=this.value;for(let s=0;s{if(!i.isImmediateParentOf(_)){const e=this.getFieldsMap(i);this.applyChanges(e,s,o),s={},o=[],i=_.popLast()}e?s[_.lastSegment()]=__PRIVATE_deepClone(e):o.push(_.lastSegment())}));const _=this.getFieldsMap(i);this.applyChanges(_,s,o)}delete(e){const i=this.field(e.popLast());__PRIVATE_isMapValue(i)&&i.mapValue.fields&&delete i.mapValue.fields[e.lastSegment()]}isEqual(e){return __PRIVATE_valueEquals(this.value,e.value)}getFieldsMap(e){let i=this.value;i.mapValue.fields||(i.mapValue={fields:{}});for(let s=0;se[i]=s));for(const i of s)delete e[i]}clone(){return new ObjectValue(__PRIVATE_deepClone(this.value))}}function __PRIVATE_extractFieldMask(e){const i=[];return forEach(e.fields,((e,s)=>{const o=new FieldPath$1([e]);if(__PRIVATE_isMapValue(s)){const e=__PRIVATE_extractFieldMask(s.mapValue).fields;if(0===e.length)i.push(o);else for(const s of e)i.push(o.child(s))}else i.push(o)})),new FieldMask(i)}class MutableDocument{constructor(e,i,s,o,_,h,d){this.key=e,this.documentType=i,this.version=s,this.readTime=o,this.createTime=_,this.data=h,this.documentState=d}static newInvalidDocument(e){return new MutableDocument(e,0,SnapshotVersion.min(),SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newFoundDocument(e,i,s,o){return new MutableDocument(e,1,i,SnapshotVersion.min(),s,o,0)}static newNoDocument(e,i){return new MutableDocument(e,2,i,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),0)}static newUnknownDocument(e,i){return new MutableDocument(e,3,i,SnapshotVersion.min(),SnapshotVersion.min(),ObjectValue.empty(),2)}convertToFoundDocument(e,i){return!this.createTime.isEqual(SnapshotVersion.min())||2!==this.documentType&&0!==this.documentType||(this.createTime=e),this.version=e,this.documentType=1,this.data=i,this.documentState=0,this}convertToNoDocument(e){return this.version=e,this.documentType=2,this.data=ObjectValue.empty(),this.documentState=0,this}convertToUnknownDocument(e){return this.version=e,this.documentType=3,this.data=ObjectValue.empty(),this.documentState=2,this}setHasCommittedMutations(){return this.documentState=2,this}setHasLocalMutations(){return this.documentState=1,this.version=SnapshotVersion.min(),this}setReadTime(e){return this.readTime=e,this}get hasLocalMutations(){return 1===this.documentState}get hasCommittedMutations(){return 2===this.documentState}get hasPendingWrites(){return this.hasLocalMutations||this.hasCommittedMutations}isValidDocument(){return 0!==this.documentType}isFoundDocument(){return 1===this.documentType}isNoDocument(){return 2===this.documentType}isUnknownDocument(){return 3===this.documentType}isEqual(e){return e instanceof MutableDocument&&this.key.isEqual(e.key)&&this.version.isEqual(e.version)&&this.documentType===e.documentType&&this.documentState===e.documentState&&this.data.isEqual(e.data)}mutableCopy(){return new MutableDocument(this.key,this.documentType,this.version,this.readTime,this.createTime,this.data.clone(),this.documentState)}toString(){return`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`}}class Bound{constructor(e,i){this.position=e,this.inclusive=i}}function __PRIVATE_boundCompareToDocument(e,i,s){let o=0;for(let _=0;_“:return e>0;case”>=”:return e>=0;default:return fail(47266,{operator:this.op})}}isInequality(){return[“<","<=",">“,”>=”,”!=”,”not-in”].indexOf(this.op)>=0}getFlattenedFilters(){return[this]}getFilters(){return[this]}}class CompositeFilter extends Filter{constructor(e,i){super(),this.filters=e,this.op=i,this.Te=null}static create(e,i){return new CompositeFilter(e,i)}matches(e){return __PRIVATE_compositeFilterIsConjunction(this)?void 0===this.filters.find((i=>!i.matches(e))):void 0!==this.filters.find((i=>i.matches(e)))}getFlattenedFilters(){return null!==this.Te||(this.Te=this.filters.reduce(((e,i)=>e.concat(i.getFlattenedFilters())),[])),this.Te}getFilters(){return Object.assign([],this.filters)}}function __PRIVATE_compositeFilterIsConjunction(e){return”and”===e.op}function __PRIVATE_compositeFilterIsDisjunction(e){return”or”===e.op}function __PRIVATE_compositeFilterIsFlatConjunction(e){return __PRIVATE_compositeFilterIsFlat(e)&&__PRIVATE_compositeFilterIsConjunction(e)}function __PRIVATE_compositeFilterIsFlat(e){for(const i of e.filters)if(i instanceof CompositeFilter)return!1;return!0}function __PRIVATE_canonifyFilter(e){if(e instanceof FieldFilter)return e.field.canonicalString()+e.op.toString()+canonicalId(e.value);if(__PRIVATE_compositeFilterIsFlatConjunction(e))return e.filters.map((e=>__PRIVATE_canonifyFilter(e))).join(“,”);{const i=e.filters.map((e=>__PRIVATE_canonifyFilter(e))).join(“,”);return`${e.op}(${i})`}}function __PRIVATE_filterEquals(e,i){return e instanceof FieldFilter?function __PRIVATE_fieldFilterEquals(e,i){return i instanceof FieldFilter&&e.op===i.op&&e.field.isEqual(i.field)&&__PRIVATE_valueEquals(e.value,i.value)}(e,i):e instanceof CompositeFilter?function __PRIVATE_compositeFilterEquals(e,i){return i instanceof CompositeFilter&&e.op===i.op&&e.filters.length===i.filters.length&&e.filters.reduce(((e,s,o)=>e&&__PRIVATE_filterEquals(s,i.filters[o])),!0)}(e,i):void fail(19439)}function __PRIVATE_compositeFilterWithAddedFilters(e,i){const s=e.filters.concat(i);return CompositeFilter.create(s,e.op)}function __PRIVATE_stringifyFilter(e){return e instanceof FieldFilter?function __PRIVATE_stringifyFieldFilter(e){return`${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`}(e):e instanceof CompositeFilter?function __PRIVATE_stringifyCompositeFilter(e){return e.op.toString()+” {“+e.getFilters().map(__PRIVATE_stringifyFilter).join(” ,”)+”}”}(e):”Filter”}class __PRIVATE_KeyFieldFilter extends FieldFilter{constructor(e,i,s){super(e,i,s),this.key=DocumentKey.fromName(s.referenceValue)}matches(e){const i=DocumentKey.comparator(e.key,this.key);return this.matchesComparison(i)}}class __PRIVATE_KeyFieldInFilter extends FieldFilter{constructor(e,i){super(e,”in”,i),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue(“in”,i)}matches(e){return this.keys.some((i=>i.isEqual(e.key)))}}class __PRIVATE_KeyFieldNotInFilter extends FieldFilter{constructor(e,i){super(e,”not-in”,i),this.keys=__PRIVATE_extractDocumentKeysFromArrayValue(“not-in”,i)}matches(e){return!this.keys.some((i=>i.isEqual(e.key)))}}function __PRIVATE_extractDocumentKeysFromArrayValue(e,i){var s;return((null===(s=i.arrayValue)||void 0===s?void 0:s.values)||[]).map((e=>DocumentKey.fromName(e.referenceValue)))}class __PRIVATE_ArrayContainsFilter extends FieldFilter{constructor(e,i){super(e,”array-contains”,i)}matches(e){const i=e.data.field(this.field);return isArray(i)&&__PRIVATE_arrayValueContains(i.arrayValue,this.value)}}class __PRIVATE_InFilter extends FieldFilter{constructor(e,i){super(e,”in”,i)}matches(e){const i=e.data.field(this.field);return null!==i&&__PRIVATE_arrayValueContains(this.value.arrayValue,i)}}class __PRIVATE_NotInFilter extends FieldFilter{constructor(e,i){super(e,”not-in”,i)}matches(e){if(__PRIVATE_arrayValueContains(this.value.arrayValue,{nullValue:”NULL_VALUE”}))return!1;const i=e.data.field(this.field);return null!==i&&void 0===i.nullValue&&!__PRIVATE_arrayValueContains(this.value.arrayValue,i)}}class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter{constructor(e,i){super(e,”array-contains-any”,i)}matches(e){const i=e.data.field(this.field);return!(!isArray(i)||!i.arrayValue.values)&&i.arrayValue.values.some((e=>__PRIVATE_arrayValueContains(this.value.arrayValue,e)))}}class __PRIVATE_TargetImpl{constructor(e,i=null,s=[],o=[],_=null,h=null,d=null){this.path=e,this.collectionGroup=i,this.orderBy=s,this.filters=o,this.limit=_,this.startAt=h,this.endAt=d,this.Ie=null}}function __PRIVATE_newTarget(e,i=null,s=[],o=[],_=null,h=null,d=null){return new __PRIVATE_TargetImpl(e,i,s,o,_,h,d)}function __PRIVATE_canonifyTarget(e){const i=__PRIVATE_debugCast(e);if(null===i.Ie){let e=i.path.canonicalString();null!==i.collectionGroup&&(e+=”|cg:”+i.collectionGroup),e+=”|f:”,e+=i.filters.map((e=>__PRIVATE_canonifyFilter(e))).join(“,”),e+=”|ob:”,e+=i.orderBy.map((e=>function __PRIVATE_canonifyOrderBy(e){return e.field.canonicalString()+e.dir}(e))).join(“,”),__PRIVATE_isNullOrUndefined(i.limit)||(e+=”|l:”,e+=i.limit),i.startAt&&(e+=”|lb:”,e+=i.startAt.inclusive?”b:”:”a:”,e+=i.startAt.position.map((e=>canonicalId(e))).join(“,”)),i.endAt&&(e+=”|ub:”,e+=i.endAt.inclusive?”a:”:”b:”,e+=i.endAt.position.map((e=>canonicalId(e))).join(“,”)),i.Ie=e}return i.Ie}function __PRIVATE_targetEquals(e,i){if(e.limit!==i.limit)return!1;if(e.orderBy.length!==i.orderBy.length)return!1;for(let s=0;se instanceof FieldFilter&&e.field.isEqual(i)))}function __PRIVATE_targetGetAscendingBound(e,i,s){let o=Lt,_=!0;for(const s of __PRIVATE_targetGetFieldFiltersForPath(e,i)){let e=Lt,i=!0;switch(s.op){case”<":case"<=":e=__PRIVATE_valuesGetLowerBound(s.value);break;case"==":case"in":case">=”:e=s.value;break;case”>”:e=s.value,i=!1;break;case”!=”:case”not-in”:e=Lt}__PRIVATE_lowerBoundCompare({value:o,inclusive:_},{value:e,inclusive:i})<0&&(o=e,_=i)}if(null!==s)for(let h=0;h=”:case”>”:e=__PRIVATE_valuesGetUpperBound(s.value),i=!1;break;case”==”:case”in”:case”<=":e=s.value;break;case"<":e=s.value,i=!1;break;case"!=":case"not-in":e=Nt}__PRIVATE_upperBoundCompare({value:o,inclusive:_},{value:e,inclusive:i})>0&&(o=e,_=i)}if(null!==s)for(let h=0;h0&&(o=e,_=s.inclusive);break}return{value:o,inclusive:_}}class __PRIVATE_QueryImpl{constructor(e,i=null,s=[],o=[],_=null,h=”F”,d=null,f=null){this.path=e,this.collectionGroup=i,this.explicitOrderBy=s,this.filters=o,this.limit=_,this.limitType=h,this.startAt=d,this.endAt=f,this.Ee=null,this.de=null,this.Ae=null,this.startAt,this.endAt}}function __PRIVATE_newQuery(e,i,s,o,_,h,d,f){return new __PRIVATE_QueryImpl(e,i,s,o,_,h,d,f)}function __PRIVATE_newQueryForPath(e){return new __PRIVATE_QueryImpl(e)}function __PRIVATE_queryMatchesAllDocuments(e){return 0===e.filters.length&&null===e.limit&&null==e.startAt&&null==e.endAt&&(0===e.explicitOrderBy.length||1===e.explicitOrderBy.length&&e.explicitOrderBy[0].field.isKeyField())}function __PRIVATE_isCollectionGroupQuery(e){return null!==e.collectionGroup}function __PRIVATE_queryNormalizedOrderBy(e){const i=__PRIVATE_debugCast(e);if(null===i.Ee){i.Ee=[];const e=new Set;for(const s of i.explicitOrderBy)i.Ee.push(s),e.add(s.field.canonicalString());const s=i.explicitOrderBy.length>0?i.explicitOrderBy[i.explicitOrderBy.length-1].dir:”asc”,o=function __PRIVATE_getInequalityFilterFields(e){let i=new SortedSet(FieldPath$1.comparator);return e.filters.forEach((e=>{e.getFlattenedFilters().forEach((e=>{e.isInequality()&&(i=i.add(e.field))}))})),i}(i);o.forEach((o=>{e.has(o.canonicalString())||o.isKeyField()||i.Ee.push(new OrderBy(o,s))})),e.has(FieldPath$1.keyField().canonicalString())||i.Ee.push(new OrderBy(FieldPath$1.keyField(),s))}return i.Ee}function __PRIVATE_queryToTarget(e){const i=__PRIVATE_debugCast(e);return i.de||(i.de=__PRIVATE__queryToTarget(i,__PRIVATE_queryNormalizedOrderBy(e))),i.de}function __PRIVATE_queryToAggregateTarget(e){const i=__PRIVATE_debugCast(e);return i.Ae||(i.Ae=__PRIVATE__queryToTarget(i,e.explicitOrderBy)),i.Ae}function __PRIVATE__queryToTarget(e,i){if(“F”===e.limitType)return __PRIVATE_newTarget(e.path,e.collectionGroup,i,e.filters,e.limit,e.startAt,e.endAt);{i=i.map((e=>{const i=”desc”===e.dir?”asc”:”desc”;return new OrderBy(e.field,i)}));const s=e.endAt?new Bound(e.endAt.position,e.endAt.inclusive):null,o=e.startAt?new Bound(e.startAt.position,e.startAt.inclusive):null;return __PRIVATE_newTarget(e.path,e.collectionGroup,i,e.filters,e.limit,s,o)}}function __PRIVATE_queryWithAddedFilter(e,i){const s=e.filters.concat([i]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),s,e.limit,e.limitType,e.startAt,e.endAt)}function __PRIVATE_queryWithLimit(e,i,s){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),i,s,e.startAt,e.endAt)}function __PRIVATE_queryEquals(e,i){return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e),__PRIVATE_queryToTarget(i))&&e.limitType===i.limitType}function __PRIVATE_canonifyQuery(e){return`${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`}function __PRIVATE_stringifyQuery(e){return`Query(target=${function __PRIVATE_stringifyTarget(e){let i=e.path.canonicalString();return null!==e.collectionGroup&&(i+=” collectionGroup=”+e.collectionGroup),e.filters.length>0&&(i+=`, filters: [${e.filters.map((e=>__PRIVATE_stringifyFilter(e))).join(“, “)}]`),__PRIVATE_isNullOrUndefined(e.limit)||(i+=”, limit: “+e.limit),e.orderBy.length>0&&(i+=`, orderBy: [${e.orderBy.map((e=>function __PRIVATE_stringifyOrderBy(e){return`${e.field.canonicalString()} (${e.dir})`}(e))).join(“, “)}]`),e.startAt&&(i+=”, startAt: “,i+=e.startAt.inclusive?”b:”:”a:”,i+=e.startAt.position.map((e=>canonicalId(e))).join(“,”)),e.endAt&&(i+=”, endAt: “,i+=e.endAt.inclusive?”a:”:”b:”,i+=e.endAt.position.map((e=>canonicalId(e))).join(“,”)),`Target(${i})`}(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`}function __PRIVATE_queryMatches(e,i){return i.isFoundDocument()&&function __PRIVATE_queryMatchesPathAndCollectionGroup(e,i){const s=i.key.path;return null!==e.collectionGroup?i.key.hasCollectionId(e.collectionGroup)&&e.path.isPrefixOf(s):DocumentKey.isDocumentKey(e.path)?e.path.isEqual(s):e.path.isImmediateParentOf(s)}(e,i)&&function __PRIVATE_queryMatchesOrderBy(e,i){for(const s of __PRIVATE_queryNormalizedOrderBy(e))if(!s.field.isKeyField()&&null===i.data.field(s.field))return!1;return!0}(e,i)&&function __PRIVATE_queryMatchesFilters(e,i){for(const s of e.filters)if(!s.matches(i))return!1;return!0}(e,i)&&function __PRIVATE_queryMatchesBounds(e,i){return!(e.startAt&&!function __PRIVATE_boundSortsBeforeDocument(e,i,s){const o=__PRIVATE_boundCompareToDocument(e,i,s);return e.inclusive?o<=0:o<0}(e.startAt,__PRIVATE_queryNormalizedOrderBy(e),i))&&!(e.endAt&&!function __PRIVATE_boundSortsAfterDocument(e,i,s){const o=__PRIVATE_boundCompareToDocument(e,i,s);return e.inclusive?o>=0:o>0}(e.endAt,__PRIVATE_queryNormalizedOrderBy(e),i))}(e,i)}function __PRIVATE_queryCollectionGroup(e){return e.collectionGroup||(e.path.length%2==1?e.path.lastSegment():e.path.get(e.path.length-2))}function __PRIVATE_newQueryComparator(e){return(i,s)=>{let o=!1;for(const _ of __PRIVATE_queryNormalizedOrderBy(e)){const e=__PRIVATE_compareDocs(_,i,s);if(0!==e)return e;o=o||_.field.isKeyField()}return 0}}function __PRIVATE_compareDocs(e,i,s){const o=e.field.isKeyField()?DocumentKey.comparator(i.key,s.key):function __PRIVATE_compareDocumentsByField(e,i,s){const o=i.data.field(e),_=s.data.field(e);return null!==o&&null!==_?__PRIVATE_valueCompare(o,_):fail(42886)}(e.field,i,s);switch(e.dir){case”asc”:return o;case”desc”:return-1*o;default:return fail(19790,{direction:e.dir})}}class ObjectMap{constructor(e,i){this.mapKeyFn=e,this.equalsFn=i,this.inner={},this.innerSize=0}get(e){const i=this.mapKeyFn(e),s=this.inner[i];if(void 0!==s)for(const[i,o]of s)if(this.equalsFn(i,e))return o}has(e){return void 0!==this.get(e)}set(e,i){const s=this.mapKeyFn(e),o=this.inner[s];if(void 0===o)return this.inner[s]=[[e,i]],void this.innerSize++;for(let s=0;s{for(const[i,o]of s)e(i,o)}))}isEmpty(){return isEmpty(this.inner)}size(){return this.innerSize}}const qt=new SortedMap(DocumentKey.comparator);function __PRIVATE_mutableDocumentMap(){return qt}const Ut=new SortedMap(DocumentKey.comparator);function documentMap(…e){let i=Ut;for(const s of e)i=i.insert(s.key,s);return i}function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e){let i=Ut;return e.forEach(((e,s)=>i=i.insert(e,s.overlayedDocument))),i}function __PRIVATE_newOverlayMap(){return __PRIVATE_newDocumentKeyMap()}function __PRIVATE_newMutationMap(){return __PRIVATE_newDocumentKeyMap()}function __PRIVATE_newDocumentKeyMap(){return new ObjectMap((e=>e.toString()),((e,i)=>e.isEqual(i)))}const Kt=new SortedMap(DocumentKey.comparator),Qt=new SortedSet(DocumentKey.comparator);function __PRIVATE_documentKeySet(…e){let i=Qt;for(const s of e)i=i.add(s);return i}const zt=new SortedSet(__PRIVATE_primitiveComparator);function __PRIVATE_targetIdSet(){return zt}function __PRIVATE_toDouble(e,i){if(e.useProto3Json){if(isNaN(i))return{doubleValue:”NaN”};if(i===1/0)return{doubleValue:”Infinity”};if(i===-1/0)return{doubleValue:”-Infinity”}}return{doubleValue:__PRIVATE_isNegativeZero(i)?”-0″:i}}function __PRIVATE_toInteger(e){return{integerValue:””+e}}function toNumber(e,i){return isSafeInteger(i)?__PRIVATE_toInteger(i):__PRIVATE_toDouble(e,i)}class TransformOperation{constructor(){this._=void 0}}function __PRIVATE_applyTransformOperationToLocalView(e,i,s){return e instanceof __PRIVATE_ServerTimestampTransform?function serverTimestamp$1(e,i){const s={fields:{[wt]:{stringValue:St},[Ct]:{timestampValue:{seconds:e.seconds,nanos:e.nanoseconds}}}};return i&&__PRIVATE_isServerTimestamp(i)&&(i=__PRIVATE_getPreviousValue(i)),i&&(s.fields[Dt]=i),{mapValue:s}}(s,i):e instanceof __PRIVATE_ArrayUnionTransformOperation?__PRIVATE_applyArrayUnionTransformOperation(e,i):e instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_applyArrayRemoveTransformOperation(e,i):function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e,i){const s=__PRIVATE_computeTransformOperationBaseValue(e,i),o=asNumber(s)+asNumber(e.Re);return isInteger(s)&&isInteger(e.Re)?__PRIVATE_toInteger(o):__PRIVATE_toDouble(e.serializer,o)}(e,i)}function __PRIVATE_applyTransformOperationToRemoteDocument(e,i,s){return e instanceof __PRIVATE_ArrayUnionTransformOperation?__PRIVATE_applyArrayUnionTransformOperation(e,i):e instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_applyArrayRemoveTransformOperation(e,i):s}function __PRIVATE_computeTransformOperationBaseValue(e,i){return e instanceof __PRIVATE_NumericIncrementTransformOperation?function __PRIVATE_isNumber(e){return isInteger(e)||function __PRIVATE_isDouble(e){return!!e&&”doubleValue”in e}(e)}(i)?i:{integerValue:0}:null}class __PRIVATE_ServerTimestampTransform extends TransformOperation{}class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}function __PRIVATE_applyArrayUnionTransformOperation(e,i){const s=__PRIVATE_coercedFieldValuesArray(i);for(const i of e.elements)s.some((e=>__PRIVATE_valueEquals(e,i)))||s.push(i);return{arrayValue:{values:s}}}class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation{constructor(e){super(),this.elements=e}}function __PRIVATE_applyArrayRemoveTransformOperation(e,i){let s=__PRIVATE_coercedFieldValuesArray(i);for(const i of e.elements)s=s.filter((e=>!__PRIVATE_valueEquals(e,i)));return{arrayValue:{values:s}}}class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation{constructor(e,i){super(),this.serializer=e,this.Re=i}}function asNumber(e){return __PRIVATE_normalizeNumber(e.integerValue||e.doubleValue)}function __PRIVATE_coercedFieldValuesArray(e){return isArray(e)&&e.arrayValue.values?e.arrayValue.values.slice():[]}class FieldTransform{constructor(e,i){this.field=e,this.transform=i}}class MutationResult{constructor(e,i){this.version=e,this.transformResults=i}}class Precondition{constructor(e,i){this.updateTime=e,this.exists=i}static none(){return new Precondition}static exists(e){return new Precondition(void 0,e)}static updateTime(e){return new Precondition(e)}get isNone(){return void 0===this.updateTime&&void 0===this.exists}isEqual(e){return this.exists===e.exists&&(this.updateTime?!!e.updateTime&&this.updateTime.isEqual(e.updateTime):!e.updateTime)}}function __PRIVATE_preconditionIsValidForDocument(e,i){return void 0!==e.updateTime?i.isFoundDocument()&&i.version.isEqual(e.updateTime):void 0===e.exists||e.exists===i.isFoundDocument()}class Mutation{}function __PRIVATE_calculateOverlayMutation(e,i){if(!e.hasLocalMutations||i&&0===i.fields.length)return null;if(null===i)return e.isNoDocument()?new __PRIVATE_DeleteMutation(e.key,Precondition.none()):new __PRIVATE_SetMutation(e.key,e.data,Precondition.none());{const s=e.data,o=ObjectValue.empty();let _=new SortedSet(FieldPath$1.comparator);for(let e of i.fields)if(!_.has(e)){let i=s.field(e);null===i&&e.length>1&&(e=e.popLast(),i=s.field(e)),null===i?o.delete(e):o.set(e,i),_=_.add(e)}return new __PRIVATE_PatchMutation(e.key,o,new FieldMask(_.toArray()),Precondition.none())}}function __PRIVATE_mutationApplyToRemoteDocument(e,i,s){e instanceof __PRIVATE_SetMutation?function __PRIVATE_setMutationApplyToRemoteDocument(e,i,s){const o=e.value.clone(),_=__PRIVATE_serverTransformResults(e.fieldTransforms,i,s.transformResults);o.setAll(_),i.convertToFoundDocument(s.version,o).setHasCommittedMutations()}(e,i,s):e instanceof __PRIVATE_PatchMutation?function __PRIVATE_patchMutationApplyToRemoteDocument(e,i,s){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return void i.convertToUnknownDocument(s.version);const o=__PRIVATE_serverTransformResults(e.fieldTransforms,i,s.transformResults),_=i.data;_.setAll(__PRIVATE_getPatch(e)),_.setAll(o),i.convertToFoundDocument(s.version,_).setHasCommittedMutations()}(e,i,s):function __PRIVATE_deleteMutationApplyToRemoteDocument(e,i,s){i.convertToNoDocument(s.version).setHasCommittedMutations()}(0,i,s)}function __PRIVATE_mutationApplyToLocalView(e,i,s,o){return e instanceof __PRIVATE_SetMutation?function __PRIVATE_setMutationApplyToLocalView(e,i,s,o){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return s;const _=e.value.clone(),h=__PRIVATE_localTransformResults(e.fieldTransforms,o,i);return _.setAll(h),i.convertToFoundDocument(i.version,_).setHasLocalMutations(),null}(e,i,s,o):e instanceof __PRIVATE_PatchMutation?function __PRIVATE_patchMutationApplyToLocalView(e,i,s,o){if(!__PRIVATE_preconditionIsValidForDocument(e.precondition,i))return s;const _=__PRIVATE_localTransformResults(e.fieldTransforms,o,i),h=i.data;return h.setAll(__PRIVATE_getPatch(e)),h.setAll(_),i.convertToFoundDocument(i.version,h).setHasLocalMutations(),null===s?null:s.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e=>e.field)))}(e,i,s,o):function __PRIVATE_deleteMutationApplyToLocalView(e,i,s){return __PRIVATE_preconditionIsValidForDocument(e.precondition,i)?(i.convertToNoDocument(i.version).setHasLocalMutations(),null):s}(e,i,s)}function __PRIVATE_mutationExtractBaseValue(e,i){let s=null;for(const o of e.fieldTransforms){const e=i.data.field(o.field),_=__PRIVATE_computeTransformOperationBaseValue(o.transform,e||null);null!=_&&(null===s&&(s=ObjectValue.empty()),s.set(o.field,_))}return s||null}function __PRIVATE_mutationEquals(e,i){return e.type===i.type&&!!e.key.isEqual(i.key)&&!!e.precondition.isEqual(i.precondition)&&!!function __PRIVATE_fieldTransformsAreEqual(e,i){return void 0===e&&void 0===i||!(!e||!i)&&__PRIVATE_arrayEquals(e,i,((e,i)=>function __PRIVATE_fieldTransformEquals(e,i){return e.field.isEqual(i.field)&&function __PRIVATE_transformOperationEquals(e,i){return e instanceof __PRIVATE_ArrayUnionTransformOperation&&i instanceof __PRIVATE_ArrayUnionTransformOperation||e instanceof __PRIVATE_ArrayRemoveTransformOperation&&i instanceof __PRIVATE_ArrayRemoveTransformOperation?__PRIVATE_arrayEquals(e.elements,i.elements,__PRIVATE_valueEquals):e instanceof __PRIVATE_NumericIncrementTransformOperation&&i instanceof __PRIVATE_NumericIncrementTransformOperation?__PRIVATE_valueEquals(e.Re,i.Re):e instanceof __PRIVATE_ServerTimestampTransform&&i instanceof __PRIVATE_ServerTimestampTransform}(e.transform,i.transform)}(e,i)))}(e.fieldTransforms,i.fieldTransforms)&&(0===e.type?e.value.isEqual(i.value):1!==e.type||e.data.isEqual(i.data)&&e.fieldMask.isEqual(i.fieldMask))}class __PRIVATE_SetMutation extends Mutation{constructor(e,i,s,o=[]){super(),this.key=e,this.value=i,this.precondition=s,this.fieldTransforms=o,this.type=0}getFieldMask(){return null}}class __PRIVATE_PatchMutation extends Mutation{constructor(e,i,s,o,_=[]){super(),this.key=e,this.data=i,this.fieldMask=s,this.precondition=o,this.fieldTransforms=_,this.type=1}getFieldMask(){return this.fieldMask}}function __PRIVATE_getPatch(e){const i=new Map;return e.fieldMask.fields.forEach((s=>{if(!s.isEmpty()){const o=e.data.field(s);i.set(s,o)}})),i}function __PRIVATE_serverTransformResults(e,i,s){const o=new Map;__PRIVATE_hardAssert(e.length===s.length,32656,{Ve:s.length,me:e.length});for(let _=0;_{const _=e.get(o.key),h=_.overlayedDocument;let d=this.applyToLocalView(h,_.mutatedFields);d=i.has(o.key)?null:d;const f=__PRIVATE_calculateOverlayMutation(h,d);null!==f&&s.set(o.key,f),h.isValidDocument()||h.convertToNoDocument(SnapshotVersion.min())})),s}keys(){return this.mutations.reduce(((e,i)=>e.add(i.key)),__PRIVATE_documentKeySet())}isEqual(e){return this.batchId===e.batchId&&__PRIVATE_arrayEquals(this.mutations,e.mutations,((e,i)=>__PRIVATE_mutationEquals(e,i)))&&__PRIVATE_arrayEquals(this.baseMutations,e.baseMutations,((e,i)=>__PRIVATE_mutationEquals(e,i)))}}class MutationBatchResult{constructor(e,i,s,o){this.batch=e,this.commitVersion=i,this.mutationResults=s,this.docVersions=o}static from(e,i,s){__PRIVATE_hardAssert(e.mutations.length===s.length,58842,{fe:e.mutations.length,ge:s.length});let o=function __PRIVATE_documentVersionMap(){return Kt}();const _=e.mutations;for(let e=0;e<_.length;e++)o=o.insert(_[e].key,s[e].version);return new MutationBatchResult(e,i,s,o)}}class Overlay{constructor(e,i){this.largestBatchId=e,this.mutation=i}getKey(){return this.mutation.key}isEqual(e){return null!==e&&this.mutation===e.mutation}toString(){return`Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`}}class __PRIVATE_AggregateImpl{constructor(e,i,s){this.alias=e,this.aggregateType=i,this.fieldPath=s}}class ExistenceFilter{constructor(e,i){this.count=e,this.unchangedNames=i}}var Gt,jt;function __PRIVATE_isPermanentError(e){switch(e){case de.OK:return fail(64938);case de.CANCELLED:case de.UNKNOWN:case de.DEADLINE_EXCEEDED:case de.RESOURCE_EXHAUSTED:case de.INTERNAL:case de.UNAVAILABLE:case de.UNAUTHENTICATED:return!1;case de.INVALID_ARGUMENT:case de.NOT_FOUND:case de.ALREADY_EXISTS:case de.PERMISSION_DENIED:case de.FAILED_PRECONDITION:case de.ABORTED:case de.OUT_OF_RANGE:case de.UNIMPLEMENTED:case de.DATA_LOSS:return!0;default:return fail(15467,{code:e})}}function __PRIVATE_mapCodeFromRpcCode(e){if(void 0===e)return __PRIVATE_logError("GRPC error has no .code"),de.UNKNOWN;switch(e){case Gt.OK:return de.OK;case Gt.CANCELLED:return de.CANCELLED;case Gt.UNKNOWN:return de.UNKNOWN;case Gt.DEADLINE_EXCEEDED:return de.DEADLINE_EXCEEDED;case Gt.RESOURCE_EXHAUSTED:return de.RESOURCE_EXHAUSTED;case Gt.INTERNAL:return de.INTERNAL;case Gt.UNAVAILABLE:return de.UNAVAILABLE;case Gt.UNAUTHENTICATED:return de.UNAUTHENTICATED;case Gt.INVALID_ARGUMENT:return de.INVALID_ARGUMENT;case Gt.NOT_FOUND:return de.NOT_FOUND;case Gt.ALREADY_EXISTS:return de.ALREADY_EXISTS;case Gt.PERMISSION_DENIED:return de.PERMISSION_DENIED;case Gt.FAILED_PRECONDITION:return de.FAILED_PRECONDITION;case Gt.ABORTED:return de.ABORTED;case Gt.OUT_OF_RANGE:return de.OUT_OF_RANGE;case Gt.UNIMPLEMENTED:return de.UNIMPLEMENTED;case Gt.DATA_LOSS:return de.DATA_LOSS;default:return fail(39323,{code:e})}}(jt=Gt||(Gt={}))[jt.OK=0]="OK",jt[jt.CANCELLED=1]="CANCELLED",jt[jt.UNKNOWN=2]="UNKNOWN",jt[jt.INVALID_ARGUMENT=3]="INVALID_ARGUMENT",jt[jt.DEADLINE_EXCEEDED=4]="DEADLINE_EXCEEDED",jt[jt.NOT_FOUND=5]="NOT_FOUND",jt[jt.ALREADY_EXISTS=6]="ALREADY_EXISTS",jt[jt.PERMISSION_DENIED=7]="PERMISSION_DENIED",jt[jt.UNAUTHENTICATED=16]="UNAUTHENTICATED",jt[jt.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",jt[jt.FAILED_PRECONDITION=9]="FAILED_PRECONDITION",jt[jt.ABORTED=10]="ABORTED",jt[jt.OUT_OF_RANGE=11]="OUT_OF_RANGE",jt[jt.UNIMPLEMENTED=12]="UNIMPLEMENTED",jt[jt.INTERNAL=13]="INTERNAL",jt[jt.UNAVAILABLE=14]="UNAVAILABLE",jt[jt.DATA_LOSS=15]="DATA_LOSS";let Wt=null;const $t=new q([4294967295,4294967295],0);function __PRIVATE_getMd5HashValue(e){const i=__PRIVATE_newTextEncoder().encode(e),s=new j;return s.update(i),new Uint8Array(s.digest())}function __PRIVATE_get64BitUints(e){const i=new DataView(e.buffer),s=i.getUint32(0,!0),o=i.getUint32(4,!0),_=i.getUint32(8,!0),h=i.getUint32(12,!0);return[new q([s,o],0),new q([_,h],0)]}class BloomFilter{constructor(e,i,s){if(this.bitmap=e,this.padding=i,this.hashCount=s,i<0||i>=8)throw new __PRIVATE_BloomFilterError(`Invalid padding: ${i}`);if(s<0)throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${s}`);if(e.length>0&&0===this.hashCount)throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${s}`);if(0===e.length&&0!==i)throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${i}`);this.pe=8*e.length-i,this.ye=q.fromNumber(this.pe)}we(e,i,s){let o=e.add(i.multiply(q.fromNumber(s)));return 1===o.compare($t)&&(o=new q([o.getBits(0),o.getBits(1)],0)),o.modulo(this.ye).toNumber()}be(e){return!!(this.bitmap[Math.floor(e/8)]&1<h.insert(e))),h}insert(e){if(0===this.pe)return;const i=__PRIVATE_getMd5HashValue(e),[s,o]=__PRIVATE_get64BitUints(i);for(let e=0;e0&&(this.Ne=!0,this.xe=e)}qe(){let e=__PRIVATE_documentKeySet(),i=__PRIVATE_documentKeySet(),s=__PRIVATE_documentKeySet();return this.Me.forEach(((o,_)=>{switch(_){case 0:e=e.add(o);break;case 2:i=i.add(o);break;case 1:s=s.add(o);break;default:fail(38017,{changeType:_})}})),new TargetChange(this.xe,this.Oe,e,i,s)}Qe(){this.Ne=!1,this.Me=__PRIVATE_snapshotChangesMap()}$e(e,i){this.Ne=!0,this.Me=this.Me.insert(e,i)}Ue(e){this.Ne=!0,this.Me=this.Me.remove(e)}Ke(){this.Fe+=1}We(){this.Fe-=1,__PRIVATE_hardAssert(this.Fe>=0,3241,{Fe:this.Fe})}Ge(){this.Ne=!0,this.Oe=!0}}class __PRIVATE_WatchChangeAggregator{constructor(e){this.ze=e,this.je=new Map,this.He=__PRIVATE_mutableDocumentMap(),this.Je=__PRIVATE_documentTargetMap(),this.Ye=__PRIVATE_documentTargetMap(),this.Ze=new SortedMap(__PRIVATE_primitiveComparator)}Xe(e){for(const i of e.De)e.ve&&e.ve.isFoundDocument()?this.et(i,e.ve):this.tt(i,e.key,e.ve);for(const i of e.removedTargetIds)this.tt(i,e.key,e.ve)}nt(e){this.forEachTarget(e,(i=>{const s=this.rt(i);switch(e.state){case 0:this.it(i)&&s.ke(e.resumeToken);break;case 1:s.We(),s.Be||s.Qe(),s.ke(e.resumeToken);break;case 2:s.We(),s.Be||this.removeTarget(i);break;case 3:this.it(i)&&(s.Ge(),s.ke(e.resumeToken));break;case 4:this.it(i)&&(this.st(i),s.ke(e.resumeToken));break;default:fail(56790,{state:e.state})}}))}forEachTarget(e,i){e.targetIds.length>0?e.targetIds.forEach(i):this.je.forEach(((e,s)=>{this.it(s)&&i(s)}))}ot(e){const i=e.targetId,s=e.Ce.count,o=this._t(i);if(o){const _=o.target;if(__PRIVATE_targetIsDocumentTarget(_))if(0===s){const e=new DocumentKey(_.path);this.tt(i,e,MutableDocument.newNoDocument(e,SnapshotVersion.min()))}else __PRIVATE_hardAssert(1===s,20013,{expectedCount:s});else{const o=this.ut(i);if(o!==s){const s=this.ct(e),_=s?this.lt(s,e,o):1;if(0!==_){this.st(i);const e=2===_?”TargetPurposeExistenceFilterMismatchBloom”:”TargetPurposeExistenceFilterMismatch”;this.Ze=this.Ze.insert(i,e)}null==Wt||Wt.ht(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e,i,s,o,_){var h,d,f,g,b,w;const O={localCacheCount:e,existenceFilterCount:i.count,databaseId:s.database,projectId:s.projectId},q=i.unchangedNames;return q&&(O.bloomFilter={applied:0===_,hashCount:null!==(h=null==q?void 0:q.hashCount)&&void 0!==h?h:0,bitmapLength:null!==(g=null===(f=null===(d=null==q?void 0:q.bits)||void 0===d?void 0:d.bitmap)||void 0===f?void 0:f.length)&&void 0!==g?g:0,padding:null!==(w=null===(b=null==q?void 0:q.bits)||void 0===b?void 0:b.padding)&&void 0!==w?w:0,mightContain:e=>{var i;return null!==(i=null==o?void 0:o.mightContain(e))&&void 0!==i&&i}}),O}(o,e.Ce,this.ze.Pt(),s,_))}}}}ct(e){const i=e.Ce.unchangedNames;if(!i||!i.bits)return null;const{bits:{bitmap:s=””,padding:o=0},hashCount:_=0}=i;let h,d;try{h=__PRIVATE_normalizeByteString(s).toUint8Array()}catch(e){if(e instanceof __PRIVATE_Base64DecodeError)return __PRIVATE_logWarn(“Decoding the base64 bloom filter in existence filter failed (“+e.message+”); ignoring the bloom filter and falling back to full re-query.”),null;throw e}try{d=new BloomFilter(h,o,_)}catch(e){return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError?”BloomFilter error: “:”Applying bloom filter failed: “,e),null}return 0===d.pe?null:d}lt(e,i,s){return i.Ce.count===s-this.Tt(e,i.targetId)?0:2}Tt(e,i){const s=this.ze.getRemoteKeysForTarget(i);let o=0;return s.forEach((s=>{const _=this.ze.Pt(),h=`projects/${_.projectId}/databases/${_.database}/documents/${s.path.canonicalString()}`;e.mightContain(h)||(this.tt(i,s,null),o++)})),o}It(e){const i=new Map;this.je.forEach(((s,o)=>{const _=this._t(o);if(_){if(s.current&&__PRIVATE_targetIsDocumentTarget(_.target)){const i=new DocumentKey(_.target.path);this.Et(i).has(o)||this.dt(o,i)||this.tt(o,i,MutableDocument.newNoDocument(i,e))}s.Le&&(i.set(o,s.qe()),s.Qe())}}));let s=__PRIVATE_documentKeySet();this.Ye.forEach(((e,i)=>{let o=!0;i.forEachWhile((e=>{const i=this._t(e);return!i||”TargetPurposeLimboResolution”===i.purpose||(o=!1,!1)})),o&&(s=s.add(e))})),this.He.forEach(((i,s)=>s.setReadTime(e)));const o=new RemoteEvent(e,i,this.Ze,this.He,s);return this.He=__PRIVATE_mutableDocumentMap(),this.Je=__PRIVATE_documentTargetMap(),this.Ye=__PRIVATE_documentTargetMap(),this.Ze=new SortedMap(__PRIVATE_primitiveComparator),o}et(e,i){if(!this.it(e))return;const s=this.dt(e,i.key)?2:0;this.rt(e).$e(i.key,s),this.He=this.He.insert(i.key,i),this.Je=this.Je.insert(i.key,this.Et(i.key).add(e)),this.Ye=this.Ye.insert(i.key,this.At(i.key).add(e))}tt(e,i,s){if(!this.it(e))return;const o=this.rt(e);this.dt(e,i)?o.$e(i,1):o.Ue(i),this.Ye=this.Ye.insert(i,this.At(i).delete(e)),this.Ye=this.Ye.insert(i,this.At(i).add(e)),s&&(this.He=this.He.insert(i,s))}removeTarget(e){this.je.delete(e)}ut(e){const i=this.rt(e).qe();return this.ze.getRemoteKeysForTarget(e).size+i.addedDocuments.size-i.removedDocuments.size}Ke(e){this.rt(e).Ke()}rt(e){let i=this.je.get(e);return i||(i=new __PRIVATE_TargetState,this.je.set(e,i)),i}At(e){let i=this.Ye.get(e);return i||(i=new SortedSet(__PRIVATE_primitiveComparator),this.Ye=this.Ye.insert(e,i)),i}Et(e){let i=this.Je.get(e);return i||(i=new SortedSet(__PRIVATE_primitiveComparator),this.Je=this.Je.insert(e,i)),i}it(e){const i=null!==this._t(e);return i||__PRIVATE_logDebug(“WatchChangeAggregator”,”Detected inactive target”,e),i}_t(e){const i=this.je.get(e);return i&&i.Be?null:this.ze.Rt(e)}st(e){this.je.set(e,new __PRIVATE_TargetState),this.ze.getRemoteKeysForTarget(e).forEach((i=>{this.tt(e,i,null)}))}dt(e,i){return this.ze.getRemoteKeysForTarget(e).has(i)}}function __PRIVATE_documentTargetMap(){return new SortedMap(DocumentKey.comparator)}function __PRIVATE_snapshotChangesMap(){return new SortedMap(DocumentKey.comparator)}const Ht={asc:”ASCENDING”,desc:”DESCENDING”},Jt={“<":"LESS_THAN","<=":"LESS_THAN_OR_EQUAL",">“:”GREATER_THAN”,”>=”:”GREATER_THAN_OR_EQUAL”,”==”:”EQUAL”,”!=”:”NOT_EQUAL”,”array-contains”:”ARRAY_CONTAINS”,in:”IN”,”not-in”:”NOT_IN”,”array-contains-any”:”ARRAY_CONTAINS_ANY”},Yt={and:”AND”,or:”OR”};class JsonProtoSerializer{constructor(e,i){this.databaseId=e,this.useProto3Json=i}}function __PRIVATE_toInt32Proto(e,i){return e.useProto3Json||__PRIVATE_isNullOrUndefined(i)?i:{value:i}}function toTimestamp(e,i){return e.useProto3Json?`${new Date(1e3*i.seconds).toISOString().replace(/\.\d*/,””).replace(“Z”,””)}.${(“000000000″+i.nanoseconds).slice(-9)}Z`:{seconds:””+i.seconds,nanos:i.nanoseconds}}function __PRIVATE_toBytes(e,i){return e.useProto3Json?i.toBase64():i.toUint8Array()}function __PRIVATE_toVersion(e,i){return toTimestamp(e,i.toTimestamp())}function __PRIVATE_fromVersion(e){return __PRIVATE_hardAssert(!!e,49232),SnapshotVersion.fromTimestamp(function fromTimestamp(e){const i=__PRIVATE_normalizeTimestamp(e);return new Timestamp(i.seconds,i.nanos)}(e))}function __PRIVATE_toResourceName(e,i){return __PRIVATE_toResourcePath(e,i).canonicalString()}function __PRIVATE_toResourcePath(e,i){const s=function __PRIVATE_fullyQualifiedPrefixPath(e){return new ResourcePath([“projects”,e.projectId,”databases”,e.database])}(e).child(“documents”);return void 0===i?s:s.child(i)}function __PRIVATE_fromResourceName(e){const i=ResourcePath.fromString(e);return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(i),10190,{key:i.toString()}),i}function __PRIVATE_toName(e,i){return __PRIVATE_toResourceName(e.databaseId,i.path)}function fromName(e,i){const s=__PRIVATE_fromResourceName(i);if(s.get(1)!==e.databaseId.projectId)throw new FirestoreError(de.INVALID_ARGUMENT,”Tried to deserialize key from different project: “+s.get(1)+” vs “+e.databaseId.projectId);if(s.get(3)!==e.databaseId.database)throw new FirestoreError(de.INVALID_ARGUMENT,”Tried to deserialize key from different database: “+s.get(3)+” vs “+e.databaseId.database);return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(s))}function __PRIVATE_toQueryPath(e,i){return __PRIVATE_toResourceName(e.databaseId,i)}function __PRIVATE_fromQueryPath(e){const i=__PRIVATE_fromResourceName(e);return 4===i.length?ResourcePath.emptyPath():__PRIVATE_extractLocalPathFromResourceName(i)}function __PRIVATE_getEncodedDatabaseId(e){return new ResourcePath([“projects”,e.databaseId.projectId,”databases”,e.databaseId.database]).canonicalString()}function __PRIVATE_extractLocalPathFromResourceName(e){return __PRIVATE_hardAssert(e.length>4&&”documents”===e.get(4),29091,{key:e.toString()}),e.popFirst(5)}function __PRIVATE_toMutationDocument(e,i,s){return{name:__PRIVATE_toName(e,i),fields:s.value.mapValue.fields}}function __PRIVATE_fromDocument(e,i,s){const o=fromName(e,i.name),_=__PRIVATE_fromVersion(i.updateTime),h=i.createTime?__PRIVATE_fromVersion(i.createTime):SnapshotVersion.min(),d=new ObjectValue({mapValue:{fields:i.fields}}),f=MutableDocument.newFoundDocument(o,_,h,d);return s&&f.setHasCommittedMutations(),s?f.setHasCommittedMutations():f}function toMutation(e,i){let s;if(i instanceof __PRIVATE_SetMutation)s={update:__PRIVATE_toMutationDocument(e,i.key,i.value)};else if(i instanceof __PRIVATE_DeleteMutation)s={delete:__PRIVATE_toName(e,i.key)};else if(i instanceof __PRIVATE_PatchMutation)s={update:__PRIVATE_toMutationDocument(e,i.key,i.data),updateMask:__PRIVATE_toDocumentMask(i.fieldMask)};else{if(!(i instanceof __PRIVATE_VerifyMutation))return fail(16599,{ft:i.type});s={verify:__PRIVATE_toName(e,i.key)}}return i.fieldTransforms.length>0&&(s.updateTransforms=i.fieldTransforms.map((e=>function __PRIVATE_toFieldTransform(e,i){const s=i.transform;if(s instanceof __PRIVATE_ServerTimestampTransform)return{fieldPath:i.field.canonicalString(),setToServerValue:”REQUEST_TIME”};if(s instanceof __PRIVATE_ArrayUnionTransformOperation)return{fieldPath:i.field.canonicalString(),appendMissingElements:{values:s.elements}};if(s instanceof __PRIVATE_ArrayRemoveTransformOperation)return{fieldPath:i.field.canonicalString(),removeAllFromArray:{values:s.elements}};if(s instanceof __PRIVATE_NumericIncrementTransformOperation)return{fieldPath:i.field.canonicalString(),increment:s.Re};throw fail(20930,{transform:i.transform})}(0,e)))),i.precondition.isNone||(s.currentDocument=function __PRIVATE_toPrecondition(e,i){return void 0!==i.updateTime?{updateTime:__PRIVATE_toVersion(e,i.updateTime)}:void 0!==i.exists?{exists:i.exists}:fail(27497)}(e,i.precondition)),s}function __PRIVATE_fromMutation(e,i){const s=i.currentDocument?function __PRIVATE_fromPrecondition(e){return void 0!==e.updateTime?Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)):void 0!==e.exists?Precondition.exists(e.exists):Precondition.none()}(i.currentDocument):Precondition.none(),o=i.updateTransforms?i.updateTransforms.map((i=>function __PRIVATE_fromFieldTransform(e,i){let s=null;if(“setToServerValue”in i)__PRIVATE_hardAssert(“REQUEST_TIME”===i.setToServerValue,16630,{proto:i}),s=new __PRIVATE_ServerTimestampTransform;else if(“appendMissingElements”in i){const e=i.appendMissingElements.values||[];s=new __PRIVATE_ArrayUnionTransformOperation(e)}else if(“removeAllFromArray”in i){const e=i.removeAllFromArray.values||[];s=new __PRIVATE_ArrayRemoveTransformOperation(e)}else”increment”in i?s=new __PRIVATE_NumericIncrementTransformOperation(e,i.increment):fail(16584,{proto:i});const o=FieldPath$1.fromServerFormat(i.fieldPath);return new FieldTransform(o,s)}(e,i))):[];if(i.update){i.update.name;const _=fromName(e,i.update.name),h=new ObjectValue({mapValue:{fields:i.update.fields}});if(i.updateMask){const e=function __PRIVATE_fromDocumentMask(e){const i=e.fieldPaths||[];return new FieldMask(i.map((e=>FieldPath$1.fromServerFormat(e))))}(i.updateMask);return new __PRIVATE_PatchMutation(_,h,e,s,o)}return new __PRIVATE_SetMutation(_,h,s,o)}if(i.delete){const o=fromName(e,i.delete);return new __PRIVATE_DeleteMutation(o,s)}if(i.verify){const o=fromName(e,i.verify);return new __PRIVATE_VerifyMutation(o,s)}return fail(1463,{proto:i})}function __PRIVATE_toDocumentsTarget(e,i){return{documents:[__PRIVATE_toQueryPath(e,i.path)]}}function __PRIVATE_toQueryTarget(e,i){const s={structuredQuery:{}},o=i.path;let _;null!==i.collectionGroup?(_=o,s.structuredQuery.from=[{collectionId:i.collectionGroup,allDescendants:!0}]):(_=o.popLast(),s.structuredQuery.from=[{collectionId:o.lastSegment()}]),s.parent=__PRIVATE_toQueryPath(e,_);const h=function __PRIVATE_toFilters(e){if(0!==e.length)return __PRIVATE_toFilter(CompositeFilter.create(e,”and”))}(i.filters);h&&(s.structuredQuery.where=h);const d=function __PRIVATE_toOrder(e){if(0!==e.length)return e.map((e=>function __PRIVATE_toPropertyOrder(e){return{field:__PRIVATE_toFieldPathReference(e.field),direction:__PRIVATE_toDirection(e.dir)}}(e)))}(i.orderBy);d&&(s.structuredQuery.orderBy=d);const f=__PRIVATE_toInt32Proto(e,i.limit);return null!==f&&(s.structuredQuery.limit=f),i.startAt&&(s.structuredQuery.startAt=function __PRIVATE_toStartAtCursor(e){return{before:e.inclusive,values:e.position}}(i.startAt)),i.endAt&&(s.structuredQuery.endAt=function __PRIVATE_toEndAtCursor(e){return{before:!e.inclusive,values:e.position}}(i.endAt)),{gt:s,parent:_}}function __PRIVATE_toRunAggregationQueryRequest(e,i,s,o){const{gt:_,parent:h}=__PRIVATE_toQueryTarget(e,i),d={},f=[];let g=0;return s.forEach((e=>{const i=o?e.alias:”aggregate_”+g++;d[i]=e.alias,”count”===e.aggregateType?f.push({alias:i,count:{}}):”avg”===e.aggregateType?f.push({alias:i,avg:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}}):”sum”===e.aggregateType&&f.push({alias:i,sum:{field:__PRIVATE_toFieldPathReference(e.fieldPath)}})})),{request:{structuredAggregationQuery:{aggregations:f,structuredQuery:_.structuredQuery},parent:_.parent},yt:d,parent:h}}function __PRIVATE_convertQueryTargetToQuery(e){let i=__PRIVATE_fromQueryPath(e.parent);const s=e.structuredQuery,o=s.from?s.from.length:0;let _=null;if(o>0){__PRIVATE_hardAssert(1===o,65062);const e=s.from[0];e.allDescendants?_=e.collectionId:i=i.child(e.collectionId)}let h=[];s.where&&(h=function __PRIVATE_fromFilters(e){const i=__PRIVATE_fromFilter(e);return i instanceof CompositeFilter&&__PRIVATE_compositeFilterIsFlatConjunction(i)?i.getFilters():[i]}(s.where));let d=[];s.orderBy&&(d=function __PRIVATE_fromOrder(e){return e.map((e=>function __PRIVATE_fromPropertyOrder(e){return new OrderBy(__PRIVATE_fromFieldPathReference(e.field),function __PRIVATE_fromDirection(e){switch(e){case”ASCENDING”:return”asc”;case”DESCENDING”:return”desc”;default:return}}(e.direction))}(e)))}(s.orderBy));let f=null;s.limit&&(f=function __PRIVATE_fromInt32Proto(e){let i;return i=”object”==typeof e?e.value:e,__PRIVATE_isNullOrUndefined(i)?null:i}(s.limit));let g=null;s.startAt&&(g=function __PRIVATE_fromStartAtCursor(e){const i=!!e.before,s=e.values||[];return new Bound(s,i)}(s.startAt));let b=null;return s.endAt&&(b=function __PRIVATE_fromEndAtCursor(e){const i=!e.before,s=e.values||[];return new Bound(s,i)}(s.endAt)),__PRIVATE_newQuery(i,_,d,h,f,”F”,g,b)}function __PRIVATE_fromFilter(e){return void 0!==e.unaryFilter?function __PRIVATE_fromUnaryFilter(e){switch(e.unaryFilter.op){case”IS_NAN”:const i=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(i,”==”,{doubleValue:NaN});case”IS_NULL”:const s=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(s,”==”,{nullValue:”NULL_VALUE”});case”IS_NOT_NAN”:const o=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(o,”!=”,{doubleValue:NaN});case”IS_NOT_NULL”:const _=__PRIVATE_fromFieldPathReference(e.unaryFilter.field);return FieldFilter.create(_,”!=”,{nullValue:”NULL_VALUE”});case”OPERATOR_UNSPECIFIED”:return fail(61313);default:return fail(60726)}}(e):void 0!==e.fieldFilter?function __PRIVATE_fromFieldFilter(e){return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field),function __PRIVATE_fromOperatorName(e){switch(e){case”EQUAL”:return”==”;case”NOT_EQUAL”:return”!=”;case”GREATER_THAN”:return”>”;case”GREATER_THAN_OR_EQUAL”:return”>=”;case”LESS_THAN”:return”<";case"LESS_THAN_OR_EQUAL":return"<=";case"ARRAY_CONTAINS":return"array-contains";case"IN":return"in";case"NOT_IN":return"not-in";case"ARRAY_CONTAINS_ANY":return"array-contains-any";case"OPERATOR_UNSPECIFIED":return fail(58110);default:return fail(50506)}}(e.fieldFilter.op),e.fieldFilter.value)}(e):void 0!==e.compositeFilter?function __PRIVATE_fromCompositeFilter(e){return CompositeFilter.create(e.compositeFilter.filters.map((e=>__PRIVATE_fromFilter(e))),function __PRIVATE_fromCompositeOperatorName(e){switch(e){case”AND”:return”and”;case”OR”:return”or”;default:return fail(1026)}}(e.compositeFilter.op))}(e):fail(30097,{filter:e})}function __PRIVATE_toDirection(e){return Ht[e]}function __PRIVATE_toOperatorName(e){return Jt[e]}function __PRIVATE_toCompositeOperatorName(e){return Yt[e]}function __PRIVATE_toFieldPathReference(e){return{fieldPath:e.canonicalString()}}function __PRIVATE_fromFieldPathReference(e){return FieldPath$1.fromServerFormat(e.fieldPath)}function __PRIVATE_toFilter(e){return e instanceof FieldFilter?function __PRIVATE_toUnaryOrFieldFilter(e){if(“==”===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:”IS_NAN”}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:”IS_NULL”}}}else if(“!=”===e.op){if(__PRIVATE_isNanValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:”IS_NOT_NAN”}};if(__PRIVATE_isNullValue(e.value))return{unaryFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:”IS_NOT_NULL”}}}return{fieldFilter:{field:__PRIVATE_toFieldPathReference(e.field),op:__PRIVATE_toOperatorName(e.op),value:e.value}}}(e):e instanceof CompositeFilter?function __PRIVATE_toCompositeFilter(e){const i=e.getFilters().map((e=>__PRIVATE_toFilter(e)));return 1===i.length?i[0]:{compositeFilter:{op:__PRIVATE_toCompositeOperatorName(e.op),filters:i}}}(e):fail(54877,{filter:e})}function __PRIVATE_toDocumentMask(e){const i=[];return e.fields.forEach((e=>i.push(e.canonicalString()))),{fieldPaths:i}}function __PRIVATE_isValidResourceName(e){return e.length>=4&&”projects”===e.get(0)&&”databases”===e.get(2)}class TargetData{constructor(e,i,s,o,_=SnapshotVersion.min(),h=SnapshotVersion.min(),d=ByteString.EMPTY_BYTE_STRING,f=null){this.target=e,this.targetId=i,this.purpose=s,this.sequenceNumber=o,this.snapshotVersion=_,this.lastLimboFreeSnapshotVersion=h,this.resumeToken=d,this.expectedCount=f}withSequenceNumber(e){return new TargetData(this.target,this.targetId,this.purpose,e,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,this.expectedCount)}withResumeToken(e,i){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,i,this.lastLimboFreeSnapshotVersion,e,null)}withExpectedCount(e){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,this.lastLimboFreeSnapshotVersion,this.resumeToken,e)}withLastLimboFreeSnapshotVersion(e){return new TargetData(this.target,this.targetId,this.purpose,this.sequenceNumber,this.snapshotVersion,e,this.resumeToken,this.expectedCount)}}class __PRIVATE_LocalSerializer{constructor(e){this.wt=e}}function __PRIVATE_toDbRemoteDocument(e,i){const s=i.key,o={prefixPath:s.getCollectionPath().popLast().toArray(),collectionGroup:s.collectionGroup,documentId:s.path.lastSegment(),readTime:__PRIVATE_toDbTimestampKey(i.readTime),hasCommittedMutations:i.hasCommittedMutations};if(i.isFoundDocument())o.document=function __PRIVATE_toDocument(e,i){return{name:__PRIVATE_toName(e,i.key),fields:i.data.value.mapValue.fields,updateTime:toTimestamp(e,i.version.toTimestamp()),createTime:toTimestamp(e,i.createTime.toTimestamp())}}(e.wt,i);else if(i.isNoDocument())o.noDocument={path:s.path.toArray(),readTime:__PRIVATE_toDbTimestamp(i.version)};else{if(!i.isUnknownDocument())return fail(57904,{document:i});o.unknownDocument={path:s.path.toArray(),version:__PRIVATE_toDbTimestamp(i.version)}}return o}function __PRIVATE_toDbTimestampKey(e){const i=e.toTimestamp();return[i.seconds,i.nanoseconds]}function __PRIVATE_toDbTimestamp(e){const i=e.toTimestamp();return{seconds:i.seconds,nanoseconds:i.nanoseconds}}function __PRIVATE_fromDbTimestamp(e){const i=new Timestamp(e.seconds,e.nanoseconds);return SnapshotVersion.fromTimestamp(i)}function __PRIVATE_fromDbMutationBatch(e,i){const s=(i.baseMutations||[]).map((i=>__PRIVATE_fromMutation(e.wt,i)));for(let e=0;e__PRIVATE_fromMutation(e.wt,i))),_=Timestamp.fromMillis(i.localWriteTimeMs);return new MutationBatch(i.batchId,_,s,o)}function __PRIVATE_fromDbTarget(e){const i=__PRIVATE_fromDbTimestamp(e.readTime),s=void 0!==e.lastLimboFreeSnapshotVersion?__PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion):SnapshotVersion.min();let o;return o=function __PRIVATE_isDocumentQuery(e){return void 0!==e.documents}(e.query)?function __PRIVATE_fromDocumentsTarget(e){const i=e.documents.length;return __PRIVATE_hardAssert(1===i,1966,{count:i}),__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0])))}(e.query):function __PRIVATE_fromQueryTarget(e){return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e))}(e.query),new TargetData(o,e.targetId,”TargetPurposeListen”,e.lastListenSequenceNumber,i,s,ByteString.fromBase64String(e.resumeToken))}function __PRIVATE_toDbTarget(e,i){const s=__PRIVATE_toDbTimestamp(i.snapshotVersion),o=__PRIVATE_toDbTimestamp(i.lastLimboFreeSnapshotVersion);let _;_=__PRIVATE_targetIsDocumentTarget(i.target)?__PRIVATE_toDocumentsTarget(e.wt,i.target):__PRIVATE_toQueryTarget(e.wt,i.target).gt;const h=i.resumeToken.toBase64();return{targetId:i.targetId,canonicalId:__PRIVATE_canonifyTarget(i.target),readTime:s,resumeToken:h,lastListenSequenceNumber:i.sequenceNumber,lastLimboFreeSnapshotVersion:o,query:_}}function __PRIVATE_fromBundledQuery(e){const i=__PRIVATE_convertQueryTargetToQuery({parent:e.parent,structuredQuery:e.structuredQuery});return”LAST”===e.limitType?__PRIVATE_queryWithLimit(i,i.limit,”L”):i}function __PRIVATE_fromDbDocumentOverlay(e,i){return new Overlay(i.largestBatchId,__PRIVATE_fromMutation(e.wt,i.overlayMutation))}function __PRIVATE_toDbDocumentOverlayKey(e,i){const s=i.path.lastSegment();return[e,__PRIVATE_encodeResourcePath(i.path.popLast()),s]}function __PRIVATE_toDbIndexState(e,i,s,o){return{indexId:e,uid:i,sequenceNumber:s,readTime:__PRIVATE_toDbTimestamp(o.readTime),documentKey:__PRIVATE_encodeResourcePath(o.documentKey.path),largestBatchId:o.largestBatchId}}class __PRIVATE_IndexedDbBundleCache{getBundleMetadata(e,i){return __PRIVATE_bundlesStore(e).get(i).next((e=>{if(e)return function __PRIVATE_fromDbBundle(e){return{id:e.bundleId,createTime:__PRIVATE_fromDbTimestamp(e.createTime),version:e.version}}(e)}))}saveBundleMetadata(e,i){return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e){return{bundleId:e.id,createTime:__PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)),version:e.version}}(i))}getNamedQuery(e,i){return __PRIVATE_namedQueriesStore(e).get(i).next((e=>{if(e)return function __PRIVATE_fromDbNamedQuery(e){return{name:e.name,query:__PRIVATE_fromBundledQuery(e.bundledQuery),readTime:__PRIVATE_fromDbTimestamp(e.readTime)}}(e)}))}saveNamedQuery(e,i){return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e){return{name:e.name,readTime:__PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)),bundledQuery:e.bundledQuery}}(i))}}function __PRIVATE_bundlesStore(e){return __PRIVATE_getStore(e,tt)}function __PRIVATE_namedQueriesStore(e){return __PRIVATE_getStore(e,nt)}class __PRIVATE_IndexedDbDocumentOverlayCache{constructor(e,i){this.serializer=e,this.userId=i}static bt(e,i){const s=i.uid||””;return new __PRIVATE_IndexedDbDocumentOverlayCache(e,s)}getOverlay(e,i){return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId,i)).next((e=>e?__PRIVATE_fromDbDocumentOverlay(this.serializer,e):null))}getOverlays(e,i){const s=__PRIVATE_newOverlayMap();return PersistencePromise.forEach(i,(i=>this.getOverlay(e,i).next((e=>{null!==e&&s.set(i,e)})))).next((()=>s))}saveOverlays(e,i,s){const o=[];return s.forEach(((s,_)=>{const h=new Overlay(i,_);o.push(this.St(e,h))})),PersistencePromise.waitFor(o)}removeOverlaysForBatchId(e,i,s){const o=new Set;i.forEach((e=>o.add(__PRIVATE_encodeResourcePath(e.getCollectionPath()))));const _=[];return o.forEach((i=>{const o=IDBKeyRange.bound([this.userId,i,s],[this.userId,i,s+1],!1,!0);_.push(__PRIVATE_documentOverlayStore(e).X(ft,o))})),PersistencePromise.waitFor(_)}getOverlaysForCollection(e,i,s){const o=__PRIVATE_newOverlayMap(),_=__PRIVATE_encodeResourcePath(i),h=IDBKeyRange.bound([this.userId,_,s],[this.userId,_,Number.POSITIVE_INFINITY],!0);return __PRIVATE_documentOverlayStore(e).J(ft,h).next((e=>{for(const i of e){const e=__PRIVATE_fromDbDocumentOverlay(this.serializer,i);o.set(e.getKey(),e)}return o}))}getOverlaysForCollectionGroup(e,i,s,o){const _=__PRIVATE_newOverlayMap();let h;const d=IDBKeyRange.bound([this.userId,i,s],[this.userId,i,Number.POSITIVE_INFINITY],!0);return __PRIVATE_documentOverlayStore(e).te({index:pt,range:d},((e,i,s)=>{const d=__PRIVATE_fromDbDocumentOverlay(this.serializer,i);_.size()_))}St(e,i){return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e,i,s){const[o,_,h]=__PRIVATE_toDbDocumentOverlayKey(i,s.mutation.key);return{userId:i,collectionPath:_,documentId:h,collectionGroup:s.mutation.key.getCollectionGroup(),largestBatchId:s.largestBatchId,overlayMutation:toMutation(e.wt,s.mutation)}}(this.serializer,this.userId,i))}}function __PRIVATE_documentOverlayStore(e){return __PRIVATE_getStore(e,dt)}class __PRIVATE_IndexedDbGlobalsCache{Dt(e){return __PRIVATE_getStore(e,It)}getSessionToken(e){return this.Dt(e).get(“sessionToken”).next((e=>{const i=null==e?void 0:e.value;return i?ByteString.fromUint8Array(i):ByteString.EMPTY_BYTE_STRING}))}setSessionToken(e,i){return this.Dt(e).put({name:”sessionToken”,value:i.toUint8Array()})}}class __PRIVATE_FirestoreIndexValueWriter{constructor(){}vt(e,i){this.Ct(e,i),i.Ft()}Ct(e,i){if(“nullValue”in e)this.Mt(i,5);else if(“booleanValue”in e)this.Mt(i,10),i.xt(e.booleanValue?1:0);else if(“integerValue”in e)this.Mt(i,15),i.xt(__PRIVATE_normalizeNumber(e.integerValue));else if(“doubleValue”in e){const s=__PRIVATE_normalizeNumber(e.doubleValue);isNaN(s)?this.Mt(i,13):(this.Mt(i,15),__PRIVATE_isNegativeZero(s)?i.xt(0):i.xt(s))}else if(“timestampValue”in e){let s=e.timestampValue;this.Mt(i,20),”string”==typeof s&&(s=__PRIVATE_normalizeTimestamp(s)),i.Ot(`${s.seconds||””}`),i.xt(s.nanos||0)}else if(“stringValue”in e)this.Nt(e.stringValue,i),this.Bt(i);else if(“bytesValue”in e)this.Mt(i,30),i.Lt(__PRIVATE_normalizeByteString(e.bytesValue)),this.Bt(i);else if(“referenceValue”in e)this.kt(e.referenceValue,i);else if(“geoPointValue”in e){const s=e.geoPointValue;this.Mt(i,45),i.xt(s.latitude||0),i.xt(s.longitude||0)}else”mapValue”in e?__PRIVATE_isMaxValue(e)?this.Mt(i,Number.MAX_SAFE_INTEGER):__PRIVATE_isVectorValue(e)?this.qt(e.mapValue,i):(this.Qt(e.mapValue,i),this.Bt(i)):”arrayValue”in e?(this.$t(e.arrayValue,i),this.Bt(i)):fail(19022,{Ut:e})}Nt(e,i){this.Mt(i,25),this.Kt(e,i)}Kt(e,i){i.Ot(e)}Qt(e,i){const s=e.fields||{};this.Mt(i,55);for(const e of Object.keys(s))this.Nt(e,i),this.Ct(s[e],i)}qt(e,i){var s,o;const _=e.fields||{};this.Mt(i,53);const h=Ot,d=(null===(o=null===(s=_[h].arrayValue)||void 0===s?void 0:s.values)||void 0===o?void 0:o.length)||0;this.Mt(i,15),i.xt(__PRIVATE_normalizeNumber(d)),this.Nt(h,i),this.Ct(_[h],i)}$t(e,i){const s=e.values||[];this.Mt(i,50);for(const e of s)this.Ct(e,i)}kt(e,i){this.Mt(i,37),DocumentKey.fromName(e).path.forEach((e=>{this.Mt(i,60),this.Kt(e,i)}))}Mt(e,i){e.xt(i)}Bt(e){e.xt(2)}}__PRIVATE_FirestoreIndexValueWriter.Wt=new __PRIVATE_FirestoreIndexValueWriter;const Xt=255;function __PRIVATE_numberOfLeadingZerosInByte(e){if(0===e)return 8;let i=0;return e>>4||(i+=4,e<<=4),e>>6||(i+=2,e<<=2),e>>7||(i+=1),i}function __PRIVATE_unsignedNumLength(e){const i=64-function __PRIVATE_numberOfLeadingZeros(e){let i=0;for(let s=0;s<8;++s){const o=__PRIVATE_numberOfLeadingZerosInByte(255&e[s]);if(i+=o,8!==o)break}return i}(e);return Math.ceil(i/8)}class __PRIVATE_OrderedCodeWriter{constructor(){this.buffer=new Uint8Array(1024),this.position=0}Gt(e){const i=e[Symbol.iterator]();let s=i.next();for(;!s.done;)this.zt(s.value),s=i.next();this.jt()}Ht(e){const i=e[Symbol.iterator]();let s=i.next();for(;!s.done;)this.Jt(s.value),s=i.next();this.Yt()}Zt(e){for(const i of e){const e=i.charCodeAt(0);if(e<128)this.zt(e);else if(e<2048)this.zt(960|e>>>6),this.zt(128|63&e);else if(i<"\ud800"||"\udbff">>12),this.zt(128|63&e>>>6),this.zt(128|63&e);else{const e=i.codePointAt(0);this.zt(240|e>>>18),this.zt(128|63&e>>>12),this.zt(128|63&e>>>6),this.zt(128|63&e)}}this.jt()}Xt(e){for(const i of e){const e=i.charCodeAt(0);if(e<128)this.Jt(e);else if(e<2048)this.Jt(960|e>>>6),this.Jt(128|63&e);else if(i<"\ud800"||"\udbff">>12),this.Jt(128|63&e>>>6),this.Jt(128|63&e);else{const e=i.codePointAt(0);this.Jt(240|e>>>18),this.Jt(128|63&e>>>12),this.Jt(128|63&e>>>6),this.Jt(128|63&e)}}this.Yt()}en(e){const i=this.tn(e),s=__PRIVATE_unsignedNumLength(i);this.nn(1+s),this.buffer[this.position++]=255&s;for(let e=i.length-s;eFieldPath$1.comparator(e.field,i.field))),this.collectionId=null!=e.collectionGroup?e.collectionGroup:e.path.lastSegment(),this.dn=e.orderBy,this.An=[];for(const i of e.filters){const e=i;e.isInequality()?this.En=this.En.add(e):this.An.push(e)}}get Rn(){return this.En.size>1}Vn(e){if(__PRIVATE_hardAssert(e.collectionGroup===this.collectionId,49279),this.Rn)return!1;const i=__PRIVATE_fieldIndexGetArraySegment(e);if(void 0!==i&&!this.mn(i))return!1;const s=__PRIVATE_fieldIndexGetDirectionalSegments(e);let o=new Set,_=0,h=0;for(;_0){const e=this.En.getIterator().getNext();if(!o.has(e.field.canonicalString())){const i=s[_];if(!this.fn(e,i)||!this.gn(this.dn[h++],i))return!1}++_}for(;_=this.dn.length||!this.gn(this.dn[h++],e))return!1}return!0}pn(){if(this.Rn)return null;let e=new SortedSet(FieldPath$1.comparator);const i=[];for(const s of this.An)if(!s.field.isKeyField())if(“array-contains”===s.op||”array-contains-any”===s.op)i.push(new IndexSegment(s.field,2));else{if(e.has(s.field))continue;e=e.add(s.field),i.push(new IndexSegment(s.field,0))}for(const s of this.dn)s.field.isKeyField()||e.has(s.field)||(e=e.add(s.field),i.push(new IndexSegment(s.field,”asc”===s.dir?0:1)));return new FieldIndex(FieldIndex.UNKNOWN_ID,this.collectionId,i,IndexState.empty())}mn(e){for(const i of this.An)if(this.fn(i,e))return!0;return!1}fn(e,i){if(void 0===e||!e.field.isEqual(i.fieldPath))return!1;const s=”array-contains”===e.op||”array-contains-any”===e.op;return 2===i.kind===s}gn(e,i){return!!e.field.isEqual(i.fieldPath)&&(0===i.kind&&”asc”===e.dir||1===i.kind&&”desc”===e.dir)}}function __PRIVATE_computeInExpansion(e){var i,s;if(__PRIVATE_hardAssert(e instanceof FieldFilter||e instanceof CompositeFilter,20012),e instanceof FieldFilter){if(e instanceof __PRIVATE_InFilter){const o=(null===(s=null===(i=e.value.arrayValue)||void 0===i?void 0:i.values)||void 0===s?void 0:s.map((i=>FieldFilter.create(e.field,”==”,i))))||[];return CompositeFilter.create(o,”or”)}return e}const o=e.filters.map((e=>__PRIVATE_computeInExpansion(e)));return CompositeFilter.create(o,e.op)}function __PRIVATE_getDnfTerms(e){if(0===e.getFilters().length)return[];const i=__PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e));return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(i),7391),__PRIVATE_isSingleFieldFilter(i)||__PRIVATE_isFlatConjunction(i)?[i]:i.getFilters()}function __PRIVATE_isSingleFieldFilter(e){return e instanceof FieldFilter}function __PRIVATE_isFlatConjunction(e){return e instanceof CompositeFilter&&__PRIVATE_compositeFilterIsFlatConjunction(e)}function __PRIVATE_isDisjunctiveNormalForm(e){return __PRIVATE_isSingleFieldFilter(e)||__PRIVATE_isFlatConjunction(e)||function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e){if(e instanceof CompositeFilter&&__PRIVATE_compositeFilterIsDisjunction(e)){for(const i of e.getFilters())if(!__PRIVATE_isSingleFieldFilter(i)&&!__PRIVATE_isFlatConjunction(i))return!1;return!0}return!1}(e)}function __PRIVATE_computeDistributedNormalForm(e){if(__PRIVATE_hardAssert(e instanceof FieldFilter||e instanceof CompositeFilter,34018),e instanceof FieldFilter)return e;if(1===e.filters.length)return __PRIVATE_computeDistributedNormalForm(e.filters[0]);const i=e.filters.map((e=>__PRIVATE_computeDistributedNormalForm(e)));let s=CompositeFilter.create(i,e.op);return s=__PRIVATE_applyAssociation(s),__PRIVATE_isDisjunctiveNormalForm(s)?s:(__PRIVATE_hardAssert(s instanceof CompositeFilter,64498),__PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(s),40251),__PRIVATE_hardAssert(s.filters.length>1,57927),s.filters.reduce(((e,i)=>__PRIVATE_applyDistribution(e,i))))}function __PRIVATE_applyDistribution(e,i){let s;return __PRIVATE_hardAssert(e instanceof FieldFilter||e instanceof CompositeFilter,38388),__PRIVATE_hardAssert(i instanceof FieldFilter||i instanceof CompositeFilter,25473),s=e instanceof FieldFilter?i instanceof FieldFilter?function __PRIVATE_applyDistributionFieldFilters(e,i){return CompositeFilter.create([e,i],”and”)}(e,i):__PRIVATE_applyDistributionFieldAndCompositeFilters(e,i):i instanceof FieldFilter?__PRIVATE_applyDistributionFieldAndCompositeFilters(i,e):function __PRIVATE_applyDistributionCompositeFilters(e,i){if(__PRIVATE_hardAssert(e.filters.length>0&&i.filters.length>0,48005),__PRIVATE_compositeFilterIsConjunction(e)&&__PRIVATE_compositeFilterIsConjunction(i))return __PRIVATE_compositeFilterWithAddedFilters(e,i.getFilters());const s=__PRIVATE_compositeFilterIsDisjunction(e)?e:i,o=__PRIVATE_compositeFilterIsDisjunction(e)?i:e,_=s.filters.map((e=>__PRIVATE_applyDistribution(e,o)));return CompositeFilter.create(_,”or”)}(e,i),__PRIVATE_applyAssociation(s)}function __PRIVATE_applyDistributionFieldAndCompositeFilters(e,i){if(__PRIVATE_compositeFilterIsConjunction(i))return __PRIVATE_compositeFilterWithAddedFilters(i,e.getFilters());{const s=i.filters.map((i=>__PRIVATE_applyDistribution(e,i)));return CompositeFilter.create(s,”or”)}}function __PRIVATE_applyAssociation(e){if(__PRIVATE_hardAssert(e instanceof FieldFilter||e instanceof CompositeFilter,11850),e instanceof FieldFilter)return e;const i=e.getFilters();if(1===i.length)return __PRIVATE_applyAssociation(i[0]);if(__PRIVATE_compositeFilterIsFlat(e))return e;const s=i.map((e=>__PRIVATE_applyAssociation(e))),o=[];return s.forEach((i=>{i instanceof FieldFilter?o.push(i):i instanceof CompositeFilter&&(i.op===e.op?o.push(…i.filters):o.push(i))})),1===o.length?o[0]:CompositeFilter.create(o,e.op)}class __PRIVATE_MemoryIndexManager{constructor(){this.yn=new __PRIVATE_MemoryCollectionParentIndex}addToCollectionParentIndex(e,i){return this.yn.add(i),PersistencePromise.resolve()}getCollectionParents(e,i){return PersistencePromise.resolve(this.yn.getEntries(i))}addFieldIndex(e,i){return PersistencePromise.resolve()}deleteFieldIndex(e,i){return PersistencePromise.resolve()}deleteAllFieldIndexes(e){return PersistencePromise.resolve()}createTargetIndexes(e,i){return PersistencePromise.resolve()}getDocumentsMatchingTarget(e,i){return PersistencePromise.resolve(null)}getIndexType(e,i){return PersistencePromise.resolve(0)}getFieldIndexes(e,i){return PersistencePromise.resolve([])}getNextCollectionGroupToUpdate(e){return PersistencePromise.resolve(null)}getMinOffset(e,i){return PersistencePromise.resolve(IndexOffset.min())}getMinOffsetFromCollectionGroup(e,i){return PersistencePromise.resolve(IndexOffset.min())}updateCollectionGroup(e,i,s){return PersistencePromise.resolve()}updateIndexEntries(e,i){return PersistencePromise.resolve()}}class __PRIVATE_MemoryCollectionParentIndex{constructor(){this.index={}}add(e){const i=e.lastSegment(),s=e.popLast(),o=this.index[i]||new SortedSet(ResourcePath.comparator),_=!o.has(s);return this.index[i]=o.add(s),_}has(e){const i=e.lastSegment(),s=e.popLast(),o=this.index[i];return o&&o.has(s)}getEntries(e){return(this.index[e]||new SortedSet(ResourcePath.comparator)).toArray()}}const Zt=”IndexedDbIndexManager”,en=new Uint8Array(0);class __PRIVATE_IndexedDbIndexManager{constructor(e,i){this.databaseId=i,this.wn=new __PRIVATE_MemoryCollectionParentIndex,this.bn=new ObjectMap((e=>__PRIVATE_canonifyTarget(e)),((e,i)=>__PRIVATE_targetEquals(e,i))),this.uid=e.uid||””}addToCollectionParentIndex(e,i){if(!this.wn.has(i)){const s=i.lastSegment(),o=i.popLast();e.addOnCommittedListener((()=>{this.wn.add(i)}));const _={collectionId:s,parent:__PRIVATE_encodeResourcePath(o)};return __PRIVATE_collectionParentsStore(e).put(_)}return PersistencePromise.resolve()}getCollectionParents(e,i){const s=[],o=IDBKeyRange.bound([i,””],[__PRIVATE_immediateSuccessor(i),””],!1,!0);return __PRIVATE_collectionParentsStore(e).J(o).next((e=>{for(const o of e){if(o.collectionId!==i)break;s.push(__PRIVATE_decodeResourcePath(o.parent))}return s}))}addFieldIndex(e,i){const s=__PRIVATE_indexConfigurationStore(e),o=function __PRIVATE_toDbIndexConfiguration(e){return{indexId:e.indexId,collectionGroup:e.collectionGroup,fields:e.fields.map((e=>[e.fieldPath.canonicalString(),e.kind]))}}(i);delete o.indexId;const _=s.add(o);if(i.indexState){const s=__PRIVATE_indexStateStore(e);return _.next((e=>{s.put(__PRIVATE_toDbIndexState(e,this.uid,i.indexState.sequenceNumber,i.indexState.offset))}))}return _.next()}deleteFieldIndex(e,i){const s=__PRIVATE_indexConfigurationStore(e),o=__PRIVATE_indexStateStore(e),_=__PRIVATE_indexEntriesStore(e);return s.delete(i.indexId).next((()=>o.delete(IDBKeyRange.bound([i.indexId],[i.indexId+1],!1,!0)))).next((()=>_.delete(IDBKeyRange.bound([i.indexId],[i.indexId+1],!1,!0))))}deleteAllFieldIndexes(e){const i=__PRIVATE_indexConfigurationStore(e),s=__PRIVATE_indexEntriesStore(e),o=__PRIVATE_indexStateStore(e);return i.X().next((()=>s.X())).next((()=>o.X()))}createTargetIndexes(e,i){return PersistencePromise.forEach(this.Sn(i),(i=>this.getIndexType(e,i).next((s=>{if(0===s||1===s){const s=new __PRIVATE_TargetIndexMatcher(i).pn();if(null!=s)return this.addFieldIndex(e,s)}}))))}getDocumentsMatchingTarget(e,i){const s=__PRIVATE_indexEntriesStore(e);let o=!0;const _=new Map;return PersistencePromise.forEach(this.Sn(i),(i=>this.Dn(e,i).next((e=>{o&&(o=!!e),_.set(i,e)})))).next((()=>{if(o){let e=__PRIVATE_documentKeySet();const o=[];return PersistencePromise.forEach(_,((_,h)=>{__PRIVATE_logDebug(Zt,`Using index ${function __PRIVATE_fieldIndexToString(e){return`id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e=>`${e.fieldPath}:${e.kind}`)).join(“,”)}`}(_)} to execute ${__PRIVATE_canonifyTarget(i)}`);const d=function __PRIVATE_targetGetArrayValues(e,i){const s=__PRIVATE_fieldIndexGetArraySegment(i);if(void 0===s)return null;for(const i of __PRIVATE_targetGetFieldFiltersForPath(e,s.fieldPath))switch(i.op){case”array-contains-any”:return i.value.arrayValue.values||[];case”array-contains”:return[i.value]}return null}(h,_),f=function __PRIVATE_targetGetNotInValues(e,i){const s=new Map;for(const o of __PRIVATE_fieldIndexGetDirectionalSegments(i))for(const i of __PRIVATE_targetGetFieldFiltersForPath(e,o.fieldPath))switch(i.op){case”==”:case”in”:s.set(o.fieldPath.canonicalString(),i.value);break;case”not-in”:case”!=”:return s.set(o.fieldPath.canonicalString(),i.value),Array.from(s.values())}return null}(h,_),g=function __PRIVATE_targetGetLowerBound(e,i){const s=[];let o=!0;for(const _ of __PRIVATE_fieldIndexGetDirectionalSegments(i)){const i=0===_.kind?__PRIVATE_targetGetAscendingBound(e,_.fieldPath,e.startAt):__PRIVATE_targetGetDescendingBound(e,_.fieldPath,e.startAt);s.push(i.value),o&&(o=i.inclusive)}return new Bound(s,o)}(h,_),b=function __PRIVATE_targetGetUpperBound(e,i){const s=[];let o=!0;for(const _ of __PRIVATE_fieldIndexGetDirectionalSegments(i)){const i=0===_.kind?__PRIVATE_targetGetDescendingBound(e,_.fieldPath,e.endAt):__PRIVATE_targetGetAscendingBound(e,_.fieldPath,e.endAt);s.push(i.value),o&&(o=i.inclusive)}return new Bound(s,o)}(h,_),w=this.vn(_,h,g),O=this.vn(_,h,b),q=this.Cn(_,h,f),j=this.Fn(_.indexId,d,w,g.inclusive,O,b.inclusive,q);return PersistencePromise.forEach(j,(_=>s.Z(_,i.limit).next((i=>{i.forEach((i=>{const s=DocumentKey.fromSegments(i.documentKey);e.has(s)||(e=e.add(s),o.push(s))}))}))))})).next((()=>o))}return PersistencePromise.resolve(null)}))}Sn(e){let i=this.bn.get(e);return i||(i=0===e.filters.length?[e]:__PRIVATE_getDnfTerms(CompositeFilter.create(e.filters,”and”)).map((i=>__PRIVATE_newTarget(e.path,e.collectionGroup,e.orderBy,i.getFilters(),e.limit,e.startAt,e.endAt))),this.bn.set(e,i),i)}Fn(e,i,s,o,_,h,d){const f=(null!=i?i.length:1)*Math.max(s.length,_.length),g=f/(null!=i?i.length:1),b=[];for(let w=0;wthis.xn(e,f,i,!0)));b.push(…this.createRange(O,q,j))}return b}xn(e,i,s,o){const _=new __PRIVATE_IndexEntry(e,DocumentKey.empty(),i,s);return o?_:_.In()}On(e,i,s,o){const _=new __PRIVATE_IndexEntry(e,DocumentKey.empty(),i,s);return o?_.In():_}Dn(e,i){const s=new __PRIVATE_TargetIndexMatcher(i),o=null!=i.collectionGroup?i.collectionGroup:i.path.lastSegment();return this.getFieldIndexes(e,o).next((e=>{let i=null;for(const o of e)s.Vn(o)&&(!i||o.fields.length>i.fields.length)&&(i=o);return i}))}getIndexType(e,i){let s=2;const o=this.Sn(i);return PersistencePromise.forEach(o,(i=>this.Dn(e,i).next((e=>{e?0!==s&&e.fields.lengthfunction __PRIVATE_targetHasLimit(e){return null!==e.limit}(i)&&o.length>1&&2===s?1:s))}Nn(e,i){const s=new __PRIVATE_IndexByteEncoder;for(const o of __PRIVATE_fieldIndexGetDirectionalSegments(e)){const e=i.data.field(o.fieldPath);if(null==e)return null;const _=s.Tn(o.kind);__PRIVATE_FirestoreIndexValueWriter.Wt.vt(e,_)}return s.cn()}Mn(e){const i=new __PRIVATE_IndexByteEncoder;return __PRIVATE_FirestoreIndexValueWriter.Wt.vt(e,i.Tn(0)),i.cn()}Bn(e,i){const s=new __PRIVATE_IndexByteEncoder;return __PRIVATE_FirestoreIndexValueWriter.Wt.vt(__PRIVATE_refValue(this.databaseId,i),s.Tn(function __PRIVATE_fieldIndexGetKeyOrder(e){const i=__PRIVATE_fieldIndexGetDirectionalSegments(e);return 0===i.length?0:i[i.length-1].kind}(e))),s.cn()}Cn(e,i,s){if(null===s)return[];let o=[];o.push(new __PRIVATE_IndexByteEncoder);let _=0;for(const h of __PRIVATE_fieldIndexGetDirectionalSegments(e)){const e=s[_++];for(const s of o)if(this.Ln(i,h.fieldPath)&&isArray(e))o=this.kn(o,h,e);else{const i=s.Tn(h.kind);__PRIVATE_FirestoreIndexValueWriter.Wt.vt(e,i)}}return this.qn(o)}vn(e,i,s){return this.Cn(e,i,s.position)}qn(e){const i=[];for(let s=0;se instanceof FieldFilter&&e.field.isEqual(i)&&(“in”===e.op||”not-in”===e.op)))}getFieldIndexes(e,i){const s=__PRIVATE_indexConfigurationStore(e),o=__PRIVATE_indexStateStore(e);return(i?s.J(it,IDBKeyRange.bound(i,i)):s.J()).next((e=>{const i=[];return PersistencePromise.forEach(e,(e=>o.get([e.indexId,this.uid]).next((s=>{i.push(function __PRIVATE_fromDbIndexConfiguration(e,i){const s=i?new IndexState(i.sequenceNumber,new IndexOffset(__PRIVATE_fromDbTimestamp(i.readTime),new DocumentKey(__PRIVATE_decodeResourcePath(i.documentKey)),i.largestBatchId)):IndexState.empty(),o=e.fields.map((([e,i])=>new IndexSegment(FieldPath$1.fromServerFormat(e),i)));return new FieldIndex(e.indexId,e.collectionGroup,o,s)}(e,s))})))).next((()=>i))}))}getNextCollectionGroupToUpdate(e){return this.getFieldIndexes(e).next((e=>0===e.length?null:(e.sort(((e,i)=>{const s=e.indexState.sequenceNumber-i.indexState.sequenceNumber;return 0!==s?s:__PRIVATE_primitiveComparator(e.collectionGroup,i.collectionGroup)})),e[0].collectionGroup)))}updateCollectionGroup(e,i,s){const o=__PRIVATE_indexConfigurationStore(e),_=__PRIVATE_indexStateStore(e);return this.Qn(e).next((e=>o.J(it,IDBKeyRange.bound(i,i)).next((i=>PersistencePromise.forEach(i,(i=>_.put(__PRIVATE_toDbIndexState(i.indexId,this.uid,e,s))))))))}updateIndexEntries(e,i){const s=new Map;return PersistencePromise.forEach(i,((i,o)=>{const _=s.get(i.collectionGroup);return(_?PersistencePromise.resolve(_):this.getFieldIndexes(e,i.collectionGroup)).next((_=>(s.set(i.collectionGroup,_),PersistencePromise.forEach(_,(s=>this.$n(e,i,s).next((i=>{const _=this.Un(o,s);return i.isEqual(_)?PersistencePromise.resolve():this.Kn(e,o,s,i,_)})))))))}))}Wn(e,i,s,o){return __PRIVATE_indexEntriesStore(e).put({indexId:o.indexId,uid:this.uid,arrayValue:o.arrayValue,directionalValue:o.directionalValue,orderedDocumentKey:this.Bn(s,i.key),documentKey:i.key.path.toArray()})}Gn(e,i,s,o){return __PRIVATE_indexEntriesStore(e).delete([o.indexId,this.uid,o.arrayValue,o.directionalValue,this.Bn(s,i.key),i.key.path.toArray()])}$n(e,i,s){const o=__PRIVATE_indexEntriesStore(e);let _=new SortedSet(__PRIVATE_indexEntryComparator);return o.te({index:_t,range:IDBKeyRange.only([s.indexId,this.uid,this.Bn(s,i)])},((e,o)=>{_=_.add(new __PRIVATE_IndexEntry(s.indexId,i,o.arrayValue,o.directionalValue))})).next((()=>_))}Un(e,i){let s=new SortedSet(__PRIVATE_indexEntryComparator);const o=this.Nn(i,e);if(null==o)return s;const _=__PRIVATE_fieldIndexGetArraySegment(i);if(null!=_){const h=e.data.field(_.fieldPath);if(isArray(h))for(const _ of h.arrayValue.values||[])s=s.add(new __PRIVATE_IndexEntry(i.indexId,e.key,this.Mn(_),o))}else s=s.add(new __PRIVATE_IndexEntry(i.indexId,e.key,en,o));return s}Kn(e,i,s,o,_){__PRIVATE_logDebug(Zt,”Updating index entries for document ‘%s'”,i.key);const h=[];return function __PRIVATE_diffSortedSets(e,i,s,o,_){const h=e.getIterator(),d=i.getIterator();let f=__PRIVATE_advanceIterator(h),g=__PRIVATE_advanceIterator(d);for(;f||g;){let e=!1,i=!1;if(f&&g){const o=s(f,g);o<0?i=!0:o>0&&(e=!0)}else null!=f?i=!0:e=!0;e?(o(g),g=__PRIVATE_advanceIterator(d)):i?(_(f),f=__PRIVATE_advanceIterator(h)):(f=__PRIVATE_advanceIterator(h),g=__PRIVATE_advanceIterator(d))}}(o,_,__PRIVATE_indexEntryComparator,(o=>{h.push(this.Wn(e,i,s,o))}),(o=>{h.push(this.Gn(e,i,s,o))})),PersistencePromise.waitFor(h)}Qn(e){let i=1;return __PRIVATE_indexStateStore(e).te({index:at,reverse:!0,range:IDBKeyRange.upperBound([this.uid,Number.MAX_SAFE_INTEGER])},((e,s,o)=>{o.done(),i=s.sequenceNumber+1})).next((()=>i))}createRange(e,i,s){s=s.sort(((e,i)=>__PRIVATE_indexEntryComparator(e,i))).filter(((e,i,s)=>!i||0!==__PRIVATE_indexEntryComparator(e,s[i-1])));const o=[];o.push(e);for(const _ of s){const s=__PRIVATE_indexEntryComparator(_,e),h=__PRIVATE_indexEntryComparator(_,i);if(0===s)o[0]=e.In();else if(s>0&&h<0)o.push(_),o.push(_.In());else if(h>0)break}o.push(i);const _=[];for(let e=0;e0}getMinOffsetFromCollectionGroup(e,i){return this.getFieldIndexes(e,i).next(__PRIVATE_getMinOffsetFromFieldIndexes)}getMinOffset(e,i){return PersistencePromise.mapArray(this.Sn(i),(i=>this.Dn(e,i).next((e=>e||fail(44426))))).next(__PRIVATE_getMinOffsetFromFieldIndexes)}}function __PRIVATE_collectionParentsStore(e){return __PRIVATE_getStore(e,Xe)}function __PRIVATE_indexEntriesStore(e){return __PRIVATE_getStore(e,ct)}function __PRIVATE_indexConfigurationStore(e){return __PRIVATE_getStore(e,rt)}function __PRIVATE_indexStateStore(e){return __PRIVATE_getStore(e,st)}function __PRIVATE_getMinOffsetFromFieldIndexes(e){__PRIVATE_hardAssert(0!==e.length,28825);let i=e[0].indexState.offset,s=i.largestBatchId;for(let o=1;o(f++,s.delete())));h.push(g.next((()=>{__PRIVATE_hardAssert(1===f,47070,{batchId:s.batchId})})));const b=[];for(const e of s.mutations){const o=__PRIVATE_newDbDocumentMutationKey(i,e.key.path,s.batchId);h.push(_.delete(o)),b.push(e.key)}return PersistencePromise.waitFor(h).next((()=>b))}function __PRIVATE_dbDocumentSize(e){if(!e)return 0;let i;if(e.document)i=e.document;else if(e.unknownDocument)i=e.unknownDocument;else{if(!e.noDocument)throw fail(14731);i=e.noDocument}return JSON.stringify(i).length}LruParams.DEFAULT_COLLECTION_PERCENTILE=10,LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT=1e3,LruParams.DEFAULT=new LruParams(nn,LruParams.DEFAULT_COLLECTION_PERCENTILE,LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT),LruParams.DISABLED=new LruParams(-1,0,0);class __PRIVATE_IndexedDbMutationQueue{constructor(e,i,s,o){this.userId=e,this.serializer=i,this.indexManager=s,this.referenceDelegate=o,this.jn={}}static bt(e,i,s,o){__PRIVATE_hardAssert(“”!==e.uid,64387);const _=e.isAuthenticated()?e.uid:””;return new __PRIVATE_IndexedDbMutationQueue(_,i,s,o)}checkEmpty(e){let i=!0;const s=IDBKeyRange.bound([this.userId,Number.NEGATIVE_INFINITY],[this.userId,Number.POSITIVE_INFINITY]);return __PRIVATE_mutationsStore(e).te({index:Ce,range:s},((e,s,o)=>{i=!1,o.done()})).next((()=>i))}addMutationBatch(e,i,s,o){const _=__PRIVATE_documentMutationsStore(e),h=__PRIVATE_mutationsStore(e);return h.add({}).next((d=>{__PRIVATE_hardAssert(“number”==typeof d,49019);const f=new MutationBatch(d,i,s,o),g=function __PRIVATE_toDbMutationBatch(e,i,s){const o=s.baseMutations.map((i=>toMutation(e.wt,i))),_=s.mutations.map((i=>toMutation(e.wt,i)));return{userId:i,batchId:s.batchId,localWriteTimeMs:s.localWriteTime.toMillis(),baseMutations:o,mutations:_}}(this.serializer,this.userId,f),b=[];let w=new SortedSet(((e,i)=>__PRIVATE_primitiveComparator(e.canonicalString(),i.canonicalString())));for(const e of o){const i=__PRIVATE_newDbDocumentMutationKey(this.userId,e.key.path,d);w=w.add(e.key.path.popLast()),b.push(h.put(g)),b.push(_.put(i,xe))}return w.forEach((i=>{b.push(this.indexManager.addToCollectionParentIndex(e,i))})),e.addOnCommittedListener((()=>{this.jn[d]=f.keys()})),PersistencePromise.waitFor(b).next((()=>f))}))}lookupMutationBatch(e,i){return __PRIVATE_mutationsStore(e).get(i).next((e=>e?(__PRIVATE_hardAssert(e.userId===this.userId,48,”Unexpected user for mutation batch”,{userId:e.userId,batchId:i}),__PRIVATE_fromDbMutationBatch(this.serializer,e)):null))}Hn(e,i){return this.jn[i]?PersistencePromise.resolve(this.jn[i]):this.lookupMutationBatch(e,i).next((e=>{if(e){const s=e.keys();return this.jn[i]=s,s}return null}))}getNextMutationBatchAfterBatchId(e,i){const s=i+1,o=IDBKeyRange.lowerBound([this.userId,s]);let _=null;return __PRIVATE_mutationsStore(e).te({index:Ce,range:o},((e,i,o)=>{i.userId===this.userId&&(__PRIVATE_hardAssert(i.batchId>=s,47524,{Jn:s}),_=__PRIVATE_fromDbMutationBatch(this.serializer,i)),o.done()})).next((()=>_))}getHighestUnacknowledgedBatchId(e){const i=IDBKeyRange.upperBound([this.userId,Number.POSITIVE_INFINITY]);let s=Re;return __PRIVATE_mutationsStore(e).te({index:Ce,range:i,reverse:!0},((e,i,o)=>{s=i.batchId,o.done()})).next((()=>s))}getAllMutationBatches(e){const i=IDBKeyRange.bound([this.userId,Re],[this.userId,Number.POSITIVE_INFINITY]);return __PRIVATE_mutationsStore(e).J(Ce,i).next((e=>e.map((e=>__PRIVATE_fromDbMutationBatch(this.serializer,e)))))}getAllMutationBatchesAffectingDocumentKey(e,i){const s=__PRIVATE_newDbDocumentMutationPrefixForPath(this.userId,i.path),o=IDBKeyRange.lowerBound(s),_=[];return __PRIVATE_documentMutationsStore(e).te({range:o},((s,o,h)=>{const[d,f,g]=s,b=__PRIVATE_decodeResourcePath(f);if(d===this.userId&&i.path.isEqual(b))return __PRIVATE_mutationsStore(e).get(g).next((e=>{if(!e)throw fail(61480,{Yn:s,batchId:g});__PRIVATE_hardAssert(e.userId===this.userId,10503,”Unexpected user for mutation batch”,{userId:e.userId,batchId:g}),_.push(__PRIVATE_fromDbMutationBatch(this.serializer,e))}));h.done()})).next((()=>_))}getAllMutationBatchesAffectingDocumentKeys(e,i){let s=new SortedSet(__PRIVATE_primitiveComparator);const o=[];return i.forEach((i=>{const _=__PRIVATE_newDbDocumentMutationPrefixForPath(this.userId,i.path),h=IDBKeyRange.lowerBound(_),d=__PRIVATE_documentMutationsStore(e).te({range:h},((e,o,_)=>{const[h,d,f]=e,g=__PRIVATE_decodeResourcePath(d);h===this.userId&&i.path.isEqual(g)?s=s.add(f):_.done()}));o.push(d)})),PersistencePromise.waitFor(o).next((()=>this.Zn(e,s)))}getAllMutationBatchesAffectingQuery(e,i){const s=i.path,o=s.length+1,_=__PRIVATE_newDbDocumentMutationPrefixForPath(this.userId,s),h=IDBKeyRange.lowerBound(_);let d=new SortedSet(__PRIVATE_primitiveComparator);return __PRIVATE_documentMutationsStore(e).te({range:h},((e,i,_)=>{const[h,f,g]=e,b=__PRIVATE_decodeResourcePath(f);h===this.userId&&s.isPrefixOf(b)?b.length===o&&(d=d.add(g)):_.done()})).next((()=>this.Zn(e,d)))}Zn(e,i){const s=[],o=[];return i.forEach((i=>{o.push(__PRIVATE_mutationsStore(e).get(i).next((e=>{if(null===e)throw fail(35274,{batchId:i});__PRIVATE_hardAssert(e.userId===this.userId,9748,”Unexpected user for mutation batch”,{userId:e.userId,batchId:i}),s.push(__PRIVATE_fromDbMutationBatch(this.serializer,e))})))})),PersistencePromise.waitFor(o).next((()=>s))}removeMutationBatch(e,i){return removeMutationBatch(e.he,this.userId,i).next((s=>(e.addOnCommittedListener((()=>{this.Xn(i.batchId)})),PersistencePromise.forEach(s,(i=>this.referenceDelegate.markPotentiallyOrphaned(e,i))))))}Xn(e){delete this.jn[e]}performConsistencyCheck(e){return this.checkEmpty(e).next((i=>{if(!i)return PersistencePromise.resolve();const s=IDBKeyRange.lowerBound(function __PRIVATE_newDbDocumentMutationPrefixForUser(e){return[e]}(this.userId)),o=[];return __PRIVATE_documentMutationsStore(e).te({range:s},((e,i,s)=>{if(e[0]===this.userId){const i=__PRIVATE_decodeResourcePath(e[1]);o.push(i)}else s.done()})).next((()=>{__PRIVATE_hardAssert(0===o.length,56720,{er:o.map((e=>e.canonicalString()))})}))}))}containsKey(e,i){return __PRIVATE_mutationQueueContainsKey(e,this.userId,i)}tr(e){return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e=>e||{userId:this.userId,lastAcknowledgedBatchId:Re,lastStreamToken:””}))}}function __PRIVATE_mutationQueueContainsKey(e,i,s){const o=__PRIVATE_newDbDocumentMutationPrefixForPath(i,s.path),_=o[1],h=IDBKeyRange.lowerBound(o);let d=!1;return __PRIVATE_documentMutationsStore(e).te({range:h,ee:!0},((e,s,o)=>{const[h,f,g]=e;h===i&&f===_&&(d=!0),o.done()})).next((()=>d))}function __PRIVATE_mutationsStore(e){return __PRIVATE_getStore(e,we)}function __PRIVATE_documentMutationsStore(e){return __PRIVATE_getStore(e,Me)}function __PRIVATE_mutationQueuesStore(e){return __PRIVATE_getStore(e,Se)}class __PRIVATE_TargetIdGenerator{constructor(e){this.nr=e}next(){return this.nr+=2,this.nr}static rr(){return new __PRIVATE_TargetIdGenerator(0)}static ir(){return new __PRIVATE_TargetIdGenerator(-1)}}class __PRIVATE_IndexedDbTargetCache{constructor(e,i){this.referenceDelegate=e,this.serializer=i}allocateTargetId(e){return this.sr(e).next((i=>{const s=new __PRIVATE_TargetIdGenerator(i.highestTargetId);return i.highestTargetId=s.next(),this._r(e,i).next((()=>i.highestTargetId))}))}getLastRemoteSnapshotVersion(e){return this.sr(e).next((e=>SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds,e.lastRemoteSnapshotVersion.nanoseconds))))}getHighestSequenceNumber(e){return this.sr(e).next((e=>e.highestListenSequenceNumber))}setTargetsMetadata(e,i,s){return this.sr(e).next((o=>(o.highestListenSequenceNumber=i,s&&(o.lastRemoteSnapshotVersion=s.toTimestamp()),i>o.highestListenSequenceNumber&&(o.highestListenSequenceNumber=i),this._r(e,o))))}addTargetData(e,i){return this.ar(e,i).next((()=>this.sr(e).next((s=>(s.targetCount+=1,this.ur(i,s),this._r(e,s))))))}updateTargetData(e,i){return this.ar(e,i)}removeTargetData(e,i){return this.removeMatchingKeysForTargetId(e,i.targetId).next((()=>__PRIVATE_targetsStore(e).delete(i.targetId))).next((()=>this.sr(e))).next((i=>(__PRIVATE_hardAssert(i.targetCount>0,8065),i.targetCount-=1,this._r(e,i))))}removeTargets(e,i,s){let o=0;const _=[];return __PRIVATE_targetsStore(e).te(((h,d)=>{const f=__PRIVATE_fromDbTarget(d);f.sequenceNumber<=i&&null===s.get(f.targetId)&&(o++,_.push(this.removeTargetData(e,f)))})).next((()=>PersistencePromise.waitFor(_))).next((()=>o))}forEachTarget(e,i){return __PRIVATE_targetsStore(e).te(((e,s)=>{const o=__PRIVATE_fromDbTarget(s);i(o)}))}sr(e){return __PRIVATE_globalTargetStore(e).get(Je).next((e=>(__PRIVATE_hardAssert(null!==e,2888),e)))}_r(e,i){return __PRIVATE_globalTargetStore(e).put(Je,i)}ar(e,i){return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer,i))}ur(e,i){let s=!1;return e.targetId>i.highestTargetId&&(i.highestTargetId=e.targetId,s=!0),e.sequenceNumber>i.highestListenSequenceNumber&&(i.highestListenSequenceNumber=e.sequenceNumber,s=!0),s}getTargetCount(e){return this.sr(e).next((e=>e.targetCount))}getTargetData(e,i){const s=__PRIVATE_canonifyTarget(i),o=IDBKeyRange.bound([s,Number.NEGATIVE_INFINITY],[s,Number.POSITIVE_INFINITY]);let _=null;return __PRIVATE_targetsStore(e).te({range:o,index:ze},((e,s,o)=>{const h=__PRIVATE_fromDbTarget(s);__PRIVATE_targetEquals(i,h.target)&&(_=h,o.done())})).next((()=>_))}addMatchingKeys(e,i,s){const o=[],_=__PRIVATE_documentTargetStore(e);return i.forEach((i=>{const h=__PRIVATE_encodeResourcePath(i.path);o.push(_.put({targetId:s,path:h})),o.push(this.referenceDelegate.addReference(e,s,i))})),PersistencePromise.waitFor(o)}removeMatchingKeys(e,i,s){const o=__PRIVATE_documentTargetStore(e);return PersistencePromise.forEach(i,(i=>{const _=__PRIVATE_encodeResourcePath(i.path);return PersistencePromise.waitFor([o.delete([s,_]),this.referenceDelegate.removeReference(e,s,i)])}))}removeMatchingKeysForTargetId(e,i){const s=__PRIVATE_documentTargetStore(e),o=IDBKeyRange.bound([i],[i+1],!1,!0);return s.delete(o)}getMatchingKeysForTargetId(e,i){const s=IDBKeyRange.bound([i],[i+1],!1,!0),o=__PRIVATE_documentTargetStore(e);let _=__PRIVATE_documentKeySet();return o.te({range:s,ee:!0},((e,i,s)=>{const o=__PRIVATE_decodeResourcePath(e[1]),h=new DocumentKey(o);_=_.add(h)})).next((()=>_))}containsKey(e,i){const s=__PRIVATE_encodeResourcePath(i.path),o=IDBKeyRange.bound([s],[__PRIVATE_immediateSuccessor(s)],!1,!0);let _=0;return __PRIVATE_documentTargetStore(e).te({index:$e,ee:!0,range:o},(([e,i],s,o)=>{0!==e&&(_++,o.done())})).next((()=>_>0))}Rt(e,i){return __PRIVATE_targetsStore(e).get(i).next((e=>e?__PRIVATE_fromDbTarget(e):null))}}function __PRIVATE_targetsStore(e){return __PRIVATE_getStore(e,Qe)}function __PRIVATE_globalTargetStore(e){return __PRIVATE_getStore(e,Ye)}function __PRIVATE_documentTargetStore(e){return __PRIVATE_getStore(e,je)}const rn=”LruGarbageCollector”,sn=1048576;function __PRIVATE_bufferEntryComparator([e,i],[s,o]){const _=__PRIVATE_primitiveComparator(e,s);return 0===_?__PRIVATE_primitiveComparator(i,o):_}class __PRIVATE_RollingSequenceNumberBuffer{constructor(e){this.cr=e,this.buffer=new SortedSet(__PRIVATE_bufferEntryComparator),this.lr=0}hr(){return++this.lr}Pr(e){const i=[e,this.hr()];if(this.buffer.size{this.Tr=null;try{await this.localStore.collectGarbage(this.garbageCollector)}catch(e){__PRIVATE_isIndexedDbTransactionError(e)?__PRIVATE_logDebug(rn,”Ignoring IndexedDB error during garbage collection: “,e):await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}await this.Ir(3e5)}))}}class __PRIVATE_LruGarbageCollectorImpl{constructor(e,i){this.Er=e,this.params=i}calculateTargetCount(e,i){return this.Er.dr(e).next((e=>Math.floor(i/100*e)))}nthSequenceNumber(e,i){if(0===i)return PersistencePromise.resolve(__PRIVATE_ListenSequence.le);const s=new __PRIVATE_RollingSequenceNumberBuffer(i);return this.Er.forEachTarget(e,(e=>s.Pr(e.sequenceNumber))).next((()=>this.Er.Ar(e,(e=>s.Pr(e))))).next((()=>s.maxValue))}removeTargets(e,i,s){return this.Er.removeTargets(e,i,s)}removeOrphanedDocuments(e,i){return this.Er.removeOrphanedDocuments(e,i)}collect(e,i){return-1===this.params.cacheSizeCollectionThreshold?(__PRIVATE_logDebug(“LruGarbageCollector”,”Garbage collection skipped; disabled”),PersistencePromise.resolve(tn)):this.getCacheSize(e).next((s=>s(i>this.params.maximumSequenceNumbersToCollect?(__PRIVATE_logDebug(“LruGarbageCollector”,`Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${i}`),o=this.params.maximumSequenceNumbersToCollect):o=i,h=Date.now(),this.nthSequenceNumber(e,o)))).next((o=>(s=o,d=Date.now(),this.removeTargets(e,s,i)))).next((i=>(_=i,f=Date.now(),this.removeOrphanedDocuments(e,s)))).next((e=>(b=Date.now(),__PRIVATE_getLogLevel()<=g.DEBUG&&__PRIVATE_logDebug("LruGarbageCollector",`LRU Garbage Collection\n\tCounted targets in ${h-w}ms\n\tDetermined least recently used ${o} in `+(d-h)+"ms\n"+`\tRemoved ${_} targets in `+(f-d)+"ms\n"+`\tRemoved ${e} documents in `+(b-f)+"ms\n"+`Total Duration: ${b-w}ms`),PersistencePromise.resolve({didRun:!0,sequenceNumbersCollected:o,targetsRemoved:_,documentsRemoved:e}))))}}function __PRIVATE_newLruGarbageCollector(e,i){return new __PRIVATE_LruGarbageCollectorImpl(e,i)}class __PRIVATE_IndexedDbLruDelegateImpl{constructor(e,i){this.db=e,this.garbageCollector=__PRIVATE_newLruGarbageCollector(this,i)}dr(e){const i=this.Vr(e);return this.db.getTargetCache().getTargetCount(e).next((e=>i.next((i=>e+i))))}Vr(e){let i=0;return this.Ar(e,(e=>{i++})).next((()=>i))}forEachTarget(e,i){return this.db.getTargetCache().forEachTarget(e,i)}Ar(e,i){return this.mr(e,((e,s)=>i(s)))}addReference(e,i,s){return __PRIVATE_writeSentinelKey(e,s)}removeReference(e,i,s){return __PRIVATE_writeSentinelKey(e,s)}removeTargets(e,i,s){return this.db.getTargetCache().removeTargets(e,i,s)}markPotentiallyOrphaned(e,i){return __PRIVATE_writeSentinelKey(e,i)}gr(e,i){return function __PRIVATE_mutationQueuesContainKey(e,i){let s=!1;return __PRIVATE_mutationQueuesStore(e).ne((o=>__PRIVATE_mutationQueueContainsKey(e,o,i).next((e=>(e&&(s=!0),PersistencePromise.resolve(!e)))))).next((()=>s))}(e,i)}removeOrphanedDocuments(e,i){const s=this.db.getRemoteDocumentCache().newChangeBuffer(),o=[];let _=0;return this.mr(e,((h,d)=>{if(d<=i){const i=this.gr(e,h).next((i=>{if(!i)return _++,s.getEntry(e,h).next((()=>(s.removeEntry(h,SnapshotVersion.min()),__PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e){return[0,__PRIVATE_encodeResourcePath(e.path)]}(h)))))}));o.push(i)}})).next((()=>PersistencePromise.waitFor(o))).next((()=>s.apply(e))).next((()=>_))}removeTarget(e,i){const s=i.withSequenceNumber(e.currentSequenceNumber);return this.db.getTargetCache().updateTargetData(e,s)}updateLimboDocument(e,i){return __PRIVATE_writeSentinelKey(e,i)}mr(e,i){const s=__PRIVATE_documentTargetStore(e);let o,_=__PRIVATE_ListenSequence.le;return s.te({index:$e},(([e,s],{path:h,sequenceNumber:d})=>{0===e?(_!==__PRIVATE_ListenSequence.le&&i(new DocumentKey(__PRIVATE_decodeResourcePath(o)),_),_=d,o=h):_=__PRIVATE_ListenSequence.le})).next((()=>{_!==__PRIVATE_ListenSequence.le&&i(new DocumentKey(__PRIVATE_decodeResourcePath(o)),_)}))}getCacheSize(e){return this.db.getRemoteDocumentCache().getSize(e)}}function __PRIVATE_writeSentinelKey(e,i){return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e,i){return{targetId:0,path:__PRIVATE_encodeResourcePath(e.path),sequenceNumber:i}}(i,e.currentSequenceNumber))}class RemoteDocumentChangeBuffer{constructor(){this.changes=new ObjectMap((e=>e.toString()),((e,i)=>e.isEqual(i))),this.changesApplied=!1}addEntry(e){this.assertNotApplied(),this.changes.set(e.key,e)}removeEntry(e,i){this.assertNotApplied(),this.changes.set(e,MutableDocument.newInvalidDocument(e).setReadTime(i))}getEntry(e,i){this.assertNotApplied();const s=this.changes.get(i);return void 0!==s?PersistencePromise.resolve(s):this.getFromCache(e,i)}getEntries(e,i){return this.getAllFromCache(e,i)}apply(e){return this.assertNotApplied(),this.changesApplied=!0,this.applyChanges(e)}assertNotApplied(){}}class __PRIVATE_IndexedDbRemoteDocumentCacheImpl{constructor(e){this.serializer=e}setIndexManager(e){this.indexManager=e}addEntry(e,i,s){return __PRIVATE_remoteDocumentsStore(e).put(s)}removeEntry(e,i,s){return __PRIVATE_remoteDocumentsStore(e).delete(function __PRIVATE_dbReadTimeKey(e,i){const s=e.path.toArray();return[s.slice(0,s.length-2),s[s.length-2],__PRIVATE_toDbTimestampKey(i),s[s.length-1]]}(i,s))}updateMetadata(e,i){return this.getMetadata(e).next((s=>(s.byteSize+=i,this.pr(e,s))))}getEntry(e,i){let s=MutableDocument.newInvalidDocument(i);return __PRIVATE_remoteDocumentsStore(e).te({index:Oe,range:IDBKeyRange.only(__PRIVATE_dbKey(i))},((e,o)=>{s=this.yr(i,o)})).next((()=>s))}wr(e,i){let s={size:0,document:MutableDocument.newInvalidDocument(i)};return __PRIVATE_remoteDocumentsStore(e).te({index:Oe,range:IDBKeyRange.only(__PRIVATE_dbKey(i))},((e,o)=>{s={document:this.yr(i,o),size:__PRIVATE_dbDocumentSize(o)}})).next((()=>s))}getEntries(e,i){let s=__PRIVATE_mutableDocumentMap();return this.br(e,i,((e,i)=>{const o=this.yr(e,i);s=s.insert(e,o)})).next((()=>s))}Sr(e,i){let s=__PRIVATE_mutableDocumentMap(),o=new SortedMap(DocumentKey.comparator);return this.br(e,i,((e,i)=>{const _=this.yr(e,i);s=s.insert(e,_),o=o.insert(e,__PRIVATE_dbDocumentSize(i))})).next((()=>({documents:s,Dr:o})))}br(e,i,s){if(i.isEmpty())return PersistencePromise.resolve();let o=new SortedSet(__PRIVATE_dbKeyComparator);i.forEach((e=>o=o.add(e)));const _=IDBKeyRange.bound(__PRIVATE_dbKey(o.first()),__PRIVATE_dbKey(o.last())),h=o.getIterator();let d=h.getNext();return __PRIVATE_remoteDocumentsStore(e).te({index:Oe,range:_},((e,i,o)=>{const _=DocumentKey.fromSegments([…i.prefixPath,i.collectionGroup,i.documentId]);for(;d&&__PRIVATE_dbKeyComparator(d,_)<0;)s(d,null),d=h.getNext();d&&d.isEqual(_)&&(s(d,i),d=h.hasNext()?h.getNext():null),d?o.H(__PRIVATE_dbKey(d)):o.done()})).next((()=>{for(;d;)s(d,null),d=h.hasNext()?h.getNext():null}))}getDocumentsMatchingQuery(e,i,s,o,_){const h=i.path,d=[h.popLast().toArray(),h.lastSegment(),__PRIVATE_toDbTimestampKey(s.readTime),s.documentKey.path.isEmpty()?””:s.documentKey.path.lastSegment()],f=[h.popLast().toArray(),h.lastSegment(),[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],””];return __PRIVATE_remoteDocumentsStore(e).J(IDBKeyRange.bound(d,f,!0)).next((e=>{null==_||_.incrementDocumentReadCount(e.length);let s=__PRIVATE_mutableDocumentMap();for(const _ of e){const e=this.yr(DocumentKey.fromSegments(_.prefixPath.concat(_.collectionGroup,_.documentId)),_);e.isFoundDocument()&&(__PRIVATE_queryMatches(i,e)||o.has(e.key))&&(s=s.insert(e.key,e))}return s}))}getAllFromCollectionGroup(e,i,s,o){let _=__PRIVATE_mutableDocumentMap();const h=__PRIVATE_dbCollectionGroupKey(i,s),d=__PRIVATE_dbCollectionGroupKey(i,IndexOffset.max());return __PRIVATE_remoteDocumentsStore(e).te({index:Be,range:IDBKeyRange.bound(h,d,!0)},((e,i,s)=>{const h=this.yr(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup,i.documentId)),i);_=_.insert(h.key,h),_.size===o&&s.done()})).next((()=>_))}newChangeBuffer(e){return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this,!!e&&e.trackRemovals)}getSize(e){return this.getMetadata(e).next((e=>e.byteSize))}getMetadata(e){return __PRIVATE_documentGlobalStore(e).get(Ke).next((e=>(__PRIVATE_hardAssert(!!e,20021),e)))}pr(e,i){return __PRIVATE_documentGlobalStore(e).put(Ke,i)}yr(e,i){if(i){const e=function __PRIVATE_fromDbRemoteDocument(e,i){let s;if(i.document)s=__PRIVATE_fromDocument(e.wt,i.document,!!i.hasCommittedMutations);else if(i.noDocument){const e=DocumentKey.fromSegments(i.noDocument.path),o=__PRIVATE_fromDbTimestamp(i.noDocument.readTime);s=MutableDocument.newNoDocument(e,o),i.hasCommittedMutations&&s.setHasCommittedMutations()}else{if(!i.unknownDocument)return fail(56709);{const e=DocumentKey.fromSegments(i.unknownDocument.path),o=__PRIVATE_fromDbTimestamp(i.unknownDocument.version);s=MutableDocument.newUnknownDocument(e,o)}}return i.readTime&&s.setReadTime(function __PRIVATE_fromDbTimestampKey(e){const i=new Timestamp(e[0],e[1]);return SnapshotVersion.fromTimestamp(i)}(i.readTime)),s}(this.serializer,i);if(!e.isNoDocument()||!e.version.isEqual(SnapshotVersion.min()))return e}return MutableDocument.newInvalidDocument(e)}}function __PRIVATE_newIndexedDbRemoteDocumentCache(e){return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e)}class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer{constructor(e,i){super(),this.vr=e,this.trackRemovals=i,this.Cr=new ObjectMap((e=>e.toString()),((e,i)=>e.isEqual(i)))}applyChanges(e){const i=[];let s=0,o=new SortedSet(((e,i)=>__PRIVATE_primitiveComparator(e.canonicalString(),i.canonicalString())));return this.changes.forEach(((_,h)=>{const d=this.Cr.get(_);if(i.push(this.vr.removeEntry(e,_,d.readTime)),h.isValidDocument()){const f=__PRIVATE_toDbRemoteDocument(this.vr.serializer,h);o=o.add(_.path.popLast());const g=__PRIVATE_dbDocumentSize(f);s+=g-d.size,i.push(this.vr.addEntry(e,_,f))}else if(s-=d.size,this.trackRemovals){const s=__PRIVATE_toDbRemoteDocument(this.vr.serializer,h.convertToNoDocument(SnapshotVersion.min()));i.push(this.vr.addEntry(e,_,s))}})),o.forEach((s=>{i.push(this.vr.indexManager.addToCollectionParentIndex(e,s))})),i.push(this.vr.updateMetadata(e,s)),PersistencePromise.waitFor(i)}getFromCache(e,i){return this.vr.wr(e,i).next((e=>(this.Cr.set(i,{size:e.size,readTime:e.document.readTime}),e.document)))}getAllFromCache(e,i){return this.vr.Sr(e,i).next((({documents:e,Dr:i})=>(i.forEach(((i,s)=>{this.Cr.set(i,{size:s,readTime:e.get(i).readTime})})),e)))}}function __PRIVATE_documentGlobalStore(e){return __PRIVATE_getStore(e,Ue)}function __PRIVATE_remoteDocumentsStore(e){return __PRIVATE_getStore(e,Ne)}function __PRIVATE_dbKey(e){const i=e.path.toArray();return[i.slice(0,i.length-2),i[i.length-2],i[i.length-1]]}function __PRIVATE_dbCollectionGroupKey(e,i){const s=i.documentKey.path.toArray();return[e,__PRIVATE_toDbTimestampKey(i.readTime),s.slice(0,s.length-2),s.length>0?s[s.length-1]:””]}function __PRIVATE_dbKeyComparator(e,i){const s=e.path.toArray(),o=i.path.toArray();let _=0;for(let e=0;e(s=o,this.remoteDocumentCache.getEntry(e,i)))).next((e=>(null!==s&&__PRIVATE_mutationApplyToLocalView(s.mutation,e,FieldMask.empty(),Timestamp.now()),e)))}getDocuments(e,i){return this.remoteDocumentCache.getEntries(e,i).next((i=>this.getLocalViewOfDocuments(e,i,__PRIVATE_documentKeySet()).next((()=>i))))}getLocalViewOfDocuments(e,i,s=__PRIVATE_documentKeySet()){const o=__PRIVATE_newOverlayMap();return this.populateOverlays(e,o,i).next((()=>this.computeViews(e,i,o,s).next((e=>{let i=documentMap();return e.forEach(((e,s)=>{i=i.insert(e,s.overlayedDocument)})),i}))))}getOverlayedDocuments(e,i){const s=__PRIVATE_newOverlayMap();return this.populateOverlays(e,s,i).next((()=>this.computeViews(e,i,s,__PRIVATE_documentKeySet())))}populateOverlays(e,i,s){const o=[];return s.forEach((e=>{i.has(e)||o.push(e)})),this.documentOverlayCache.getOverlays(e,o).next((e=>{e.forEach(((e,s)=>{i.set(e,s)}))}))}computeViews(e,i,s,o){let _=__PRIVATE_mutableDocumentMap();const h=__PRIVATE_newDocumentKeyMap(),d=function __PRIVATE_newOverlayedDocumentMap(){return __PRIVATE_newDocumentKeyMap()}();return i.forEach(((e,i)=>{const d=s.get(i.key);o.has(i.key)&&(void 0===d||d.mutation instanceof __PRIVATE_PatchMutation)?_=_.insert(i.key,i):void 0!==d?(h.set(i.key,d.mutation.getFieldMask()),__PRIVATE_mutationApplyToLocalView(d.mutation,i,d.mutation.getFieldMask(),Timestamp.now())):h.set(i.key,FieldMask.empty())})),this.recalculateAndSaveOverlays(e,_).next((e=>(e.forEach(((e,i)=>h.set(e,i))),i.forEach(((e,i)=>{var s;return d.set(e,new OverlayedDocument(i,null!==(s=h.get(e))&&void 0!==s?s:null))})),d)))}recalculateAndSaveOverlays(e,i){const s=__PRIVATE_newDocumentKeyMap();let o=new SortedMap(((e,i)=>e-i)),_=__PRIVATE_documentKeySet();return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e,i).next((e=>{for(const _ of e)_.keys().forEach((e=>{const h=i.get(e);if(null===h)return;let d=s.get(e)||FieldMask.empty();d=_.applyToLocalView(h,d),s.set(e,d);const f=(o.get(_.batchId)||__PRIVATE_documentKeySet()).add(e);o=o.insert(_.batchId,f)}))})).next((()=>{const h=[],d=o.getReverseIterator();for(;d.hasNext();){const o=d.getNext(),f=o.key,g=o.value,b=__PRIVATE_newMutationMap();g.forEach((e=>{if(!_.has(e)){const o=__PRIVATE_calculateOverlayMutation(i.get(e),s.get(e));null!==o&&b.set(e,o),_=_.add(e)}})),h.push(this.documentOverlayCache.saveOverlays(e,f,b))}return PersistencePromise.waitFor(h)})).next((()=>s))}recalculateAndSaveOverlaysForDocumentKeys(e,i){return this.remoteDocumentCache.getEntries(e,i).next((i=>this.recalculateAndSaveOverlays(e,i)))}getDocumentsMatchingQuery(e,i,s,o){return function __PRIVATE_isDocumentQuery$1(e){return DocumentKey.isDocumentKey(e.path)&&null===e.collectionGroup&&0===e.filters.length}(i)?this.getDocumentsMatchingDocumentQuery(e,i.path):__PRIVATE_isCollectionGroupQuery(i)?this.getDocumentsMatchingCollectionGroupQuery(e,i,s,o):this.getDocumentsMatchingCollectionQuery(e,i,s,o)}getNextDocuments(e,i,s,o){return this.remoteDocumentCache.getAllFromCollectionGroup(e,i,s,o).next((_=>{const h=o-_.size>0?this.documentOverlayCache.getOverlaysForCollectionGroup(e,i,s.largestBatchId,o-_.size):PersistencePromise.resolve(__PRIVATE_newOverlayMap());let d=Te,f=_;return h.next((i=>PersistencePromise.forEach(i,((i,s)=>(d{f=f.insert(i,e)}))))).next((()=>this.populateOverlays(e,i,_))).next((()=>this.computeViews(e,f,i,__PRIVATE_documentKeySet()))).next((e=>({batchId:d,changes:__PRIVATE_convertOverlayedDocumentMapToDocumentMap(e)})))))}))}getDocumentsMatchingDocumentQuery(e,i){return this.getDocument(e,new DocumentKey(i)).next((e=>{let i=documentMap();return e.isFoundDocument()&&(i=i.insert(e.key,e)),i}))}getDocumentsMatchingCollectionGroupQuery(e,i,s,o){const _=i.collectionGroup;let h=documentMap();return this.indexManager.getCollectionParents(e,_).next((d=>PersistencePromise.forEach(d,(d=>{const f=function __PRIVATE_asCollectionQueryAtPath(e,i){return new __PRIVATE_QueryImpl(i,null,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(i,d.child(_));return this.getDocumentsMatchingCollectionQuery(e,f,s,o).next((e=>{e.forEach(((e,i)=>{h=h.insert(e,i)}))}))})).next((()=>h))))}getDocumentsMatchingCollectionQuery(e,i,s,o){let _;return this.documentOverlayCache.getOverlaysForCollection(e,i.path,s.largestBatchId).next((h=>(_=h,this.remoteDocumentCache.getDocumentsMatchingQuery(e,i,s,_,o)))).next((e=>{_.forEach(((i,s)=>{const o=s.getKey();null===e.get(o)&&(e=e.insert(o,MutableDocument.newInvalidDocument(o)))}));let s=documentMap();return e.forEach(((e,o)=>{const h=_.get(e);void 0!==h&&__PRIVATE_mutationApplyToLocalView(h.mutation,o,FieldMask.empty(),Timestamp.now()),__PRIVATE_queryMatches(i,o)&&(s=s.insert(e,o))})),s}))}}class __PRIVATE_MemoryBundleCache{constructor(e){this.serializer=e,this.Fr=new Map,this.Mr=new Map}getBundleMetadata(e,i){return PersistencePromise.resolve(this.Fr.get(i))}saveBundleMetadata(e,i){return this.Fr.set(i.id,function __PRIVATE_fromBundleMetadata(e){return{id:e.id,version:e.version,createTime:__PRIVATE_fromVersion(e.createTime)}}(i)),PersistencePromise.resolve()}getNamedQuery(e,i){return PersistencePromise.resolve(this.Mr.get(i))}saveNamedQuery(e,i){return this.Mr.set(i.name,function __PRIVATE_fromProtoNamedQuery(e){return{name:e.name,query:__PRIVATE_fromBundledQuery(e.bundledQuery),readTime:__PRIVATE_fromVersion(e.readTime)}}(i)),PersistencePromise.resolve()}}class __PRIVATE_MemoryDocumentOverlayCache{constructor(){this.overlays=new SortedMap(DocumentKey.comparator),this.Or=new Map}getOverlay(e,i){return PersistencePromise.resolve(this.overlays.get(i))}getOverlays(e,i){const s=__PRIVATE_newOverlayMap();return PersistencePromise.forEach(i,(i=>this.getOverlay(e,i).next((e=>{null!==e&&s.set(i,e)})))).next((()=>s))}saveOverlays(e,i,s){return s.forEach(((s,o)=>{this.St(e,i,o)})),PersistencePromise.resolve()}removeOverlaysForBatchId(e,i,s){const o=this.Or.get(s);return void 0!==o&&(o.forEach((e=>this.overlays=this.overlays.remove(e))),this.Or.delete(s)),PersistencePromise.resolve()}getOverlaysForCollection(e,i,s){const o=__PRIVATE_newOverlayMap(),_=i.length+1,h=new DocumentKey(i.child(“”)),d=this.overlays.getIteratorFrom(h);for(;d.hasNext();){const e=d.getNext().value,h=e.getKey();if(!i.isPrefixOf(h.path))break;h.path.length===_&&e.largestBatchId>s&&o.set(e.getKey(),e)}return PersistencePromise.resolve(o)}getOverlaysForCollectionGroup(e,i,s,o){let _=new SortedMap(((e,i)=>e-i));const h=this.overlays.getIterator();for(;h.hasNext();){const e=h.getNext().value;if(e.getKey().getCollectionGroup()===i&&e.largestBatchId>s){let i=_.get(e.largestBatchId);null===i&&(i=__PRIVATE_newOverlayMap(),_=_.insert(e.largestBatchId,i)),i.set(e.getKey(),e)}}const d=__PRIVATE_newOverlayMap(),f=_.getIterator();for(;f.hasNext()&&(f.getNext().value.forEach(((e,i)=>d.set(e,i))),!(d.size()>=o)););return PersistencePromise.resolve(d)}St(e,i,s){const o=this.overlays.get(s.key);if(null!==o){const e=this.Or.get(o.largestBatchId).delete(s.key);this.Or.set(o.largestBatchId,e)}this.overlays=this.overlays.insert(s.key,new Overlay(i,s));let _=this.Or.get(i);void 0===_&&(_=__PRIVATE_documentKeySet(),this.Or.set(i,_)),this.Or.set(i,_.add(s.key))}}class __PRIVATE_MemoryGlobalsCache{constructor(){this.sessionToken=ByteString.EMPTY_BYTE_STRING}getSessionToken(e){return PersistencePromise.resolve(this.sessionToken)}setSessionToken(e,i){return this.sessionToken=i,PersistencePromise.resolve()}}class __PRIVATE_ReferenceSet{constructor(){this.Nr=new SortedSet(__PRIVATE_DocReference.Br),this.Lr=new SortedSet(__PRIVATE_DocReference.kr)}isEmpty(){return this.Nr.isEmpty()}addReference(e,i){const s=new __PRIVATE_DocReference(e,i);this.Nr=this.Nr.add(s),this.Lr=this.Lr.add(s)}qr(e,i){e.forEach((e=>this.addReference(e,i)))}removeReference(e,i){this.Qr(new __PRIVATE_DocReference(e,i))}$r(e,i){e.forEach((e=>this.removeReference(e,i)))}Ur(e){const i=new DocumentKey(new ResourcePath([])),s=new __PRIVATE_DocReference(i,e),o=new __PRIVATE_DocReference(i,e+1),_=[];return this.Lr.forEachInRange([s,o],(e=>{this.Qr(e),_.push(e.key)})),_}Kr(){this.Nr.forEach((e=>this.Qr(e)))}Qr(e){this.Nr=this.Nr.delete(e),this.Lr=this.Lr.delete(e)}Wr(e){const i=new DocumentKey(new ResourcePath([])),s=new __PRIVATE_DocReference(i,e),o=new __PRIVATE_DocReference(i,e+1);let _=__PRIVATE_documentKeySet();return this.Lr.forEachInRange([s,o],(e=>{_=_.add(e.key)})),_}containsKey(e){const i=new __PRIVATE_DocReference(e,0),s=this.Nr.firstAfterOrEqual(i);return null!==s&&e.isEqual(s.key)}}class __PRIVATE_DocReference{constructor(e,i){this.key=e,this.Gr=i}static Br(e,i){return DocumentKey.comparator(e.key,i.key)||__PRIVATE_primitiveComparator(e.Gr,i.Gr)}static kr(e,i){return __PRIVATE_primitiveComparator(e.Gr,i.Gr)||DocumentKey.comparator(e.key,i.key)}}class __PRIVATE_MemoryMutationQueue{constructor(e,i){this.indexManager=e,this.referenceDelegate=i,this.mutationQueue=[],this.Jn=1,this.zr=new SortedSet(__PRIVATE_DocReference.Br)}checkEmpty(e){return PersistencePromise.resolve(0===this.mutationQueue.length)}addMutationBatch(e,i,s,o){const _=this.Jn;this.Jn++,this.mutationQueue.length>0&&this.mutationQueue[this.mutationQueue.length-1];const h=new MutationBatch(_,i,s,o);this.mutationQueue.push(h);for(const i of o)this.zr=this.zr.add(new __PRIVATE_DocReference(i.key,_)),this.indexManager.addToCollectionParentIndex(e,i.key.path.popLast());return PersistencePromise.resolve(h)}lookupMutationBatch(e,i){return PersistencePromise.resolve(this.jr(i))}getNextMutationBatchAfterBatchId(e,i){const s=i+1,o=this.Hr(s),_=o<0?0:o;return PersistencePromise.resolve(this.mutationQueue.length>_?this.mutationQueue[_]:null)}getHighestUnacknowledgedBatchId(){return PersistencePromise.resolve(0===this.mutationQueue.length?Re:this.Jn-1)}getAllMutationBatches(e){return PersistencePromise.resolve(this.mutationQueue.slice())}getAllMutationBatchesAffectingDocumentKey(e,i){const s=new __PRIVATE_DocReference(i,0),o=new __PRIVATE_DocReference(i,Number.POSITIVE_INFINITY),_=[];return this.zr.forEachInRange([s,o],(e=>{const i=this.jr(e.Gr);_.push(i)})),PersistencePromise.resolve(_)}getAllMutationBatchesAffectingDocumentKeys(e,i){let s=new SortedSet(__PRIVATE_primitiveComparator);return i.forEach((e=>{const i=new __PRIVATE_DocReference(e,0),o=new __PRIVATE_DocReference(e,Number.POSITIVE_INFINITY);this.zr.forEachInRange([i,o],(e=>{s=s.add(e.Gr)}))})),PersistencePromise.resolve(this.Jr(s))}getAllMutationBatchesAffectingQuery(e,i){const s=i.path,o=s.length+1;let _=s;DocumentKey.isDocumentKey(_)||(_=_.child(“”));const h=new __PRIVATE_DocReference(new DocumentKey(_),0);let d=new SortedSet(__PRIVATE_primitiveComparator);return this.zr.forEachWhile((e=>{const i=e.key.path;return!!s.isPrefixOf(i)&&(i.length===o&&(d=d.add(e.Gr)),!0)}),h),PersistencePromise.resolve(this.Jr(d))}Jr(e){const i=[];return e.forEach((e=>{const s=this.jr(e);null!==s&&i.push(s)})),i}removeMutationBatch(e,i){__PRIVATE_hardAssert(0===this.Yr(i.batchId,”removed”),55003),this.mutationQueue.shift();let s=this.zr;return PersistencePromise.forEach(i.mutations,(o=>{const _=new __PRIVATE_DocReference(o.key,i.batchId);return s=s.delete(_),this.referenceDelegate.markPotentiallyOrphaned(e,o.key)})).next((()=>{this.zr=s}))}Xn(e){}containsKey(e,i){const s=new __PRIVATE_DocReference(i,0),o=this.zr.firstAfterOrEqual(s);return PersistencePromise.resolve(i.isEqual(o&&o.key))}performConsistencyCheck(e){return this.mutationQueue.length,PersistencePromise.resolve()}Yr(e,i){return this.Hr(e)}Hr(e){return 0===this.mutationQueue.length?0:e-this.mutationQueue[0].batchId}jr(e){const i=this.Hr(e);return i<0||i>=this.mutationQueue.length?null:this.mutationQueue[i]}}class __PRIVATE_MemoryRemoteDocumentCacheImpl{constructor(e){this.Zr=e,this.docs=function __PRIVATE_documentEntryMap(){return new SortedMap(DocumentKey.comparator)}(),this.size=0}setIndexManager(e){this.indexManager=e}addEntry(e,i){const s=i.key,o=this.docs.get(s),_=o?o.size:0,h=this.Zr(i);return this.docs=this.docs.insert(s,{document:i.mutableCopy(),size:h}),this.size+=h-_,this.indexManager.addToCollectionParentIndex(e,s.path.popLast())}removeEntry(e){const i=this.docs.get(e);i&&(this.docs=this.docs.remove(e),this.size-=i.size)}getEntry(e,i){const s=this.docs.get(i);return PersistencePromise.resolve(s?s.document.mutableCopy():MutableDocument.newInvalidDocument(i))}getEntries(e,i){let s=__PRIVATE_mutableDocumentMap();return i.forEach((e=>{const i=this.docs.get(e);s=s.insert(e,i?i.document.mutableCopy():MutableDocument.newInvalidDocument(e))})),PersistencePromise.resolve(s)}getDocumentsMatchingQuery(e,i,s,o){let _=__PRIVATE_mutableDocumentMap();const h=i.path,d=new DocumentKey(h.child(“__id-9223372036854775808__”)),f=this.docs.getIteratorFrom(d);for(;f.hasNext();){const{key:e,value:{document:d}}=f.getNext();if(!h.isPrefixOf(e.path))break;e.path.length>h.length+1||__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(d),s)<=0||(o.has(d.key)||__PRIVATE_queryMatches(i,d))&&(_=_.insert(d.key,d.mutableCopy()))}return PersistencePromise.resolve(_)}getAllFromCollectionGroup(e,i,s,o){fail(9500)}Xr(e,i){return PersistencePromise.forEach(this.docs,(e=>i(e)))}newChangeBuffer(e){return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this)}getSize(e){return PersistencePromise.resolve(this.size)}}class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer{constructor(e){super(),this.vr=e}applyChanges(e){const i=[];return this.changes.forEach(((s,o)=>{o.isValidDocument()?i.push(this.vr.addEntry(e,o)):this.vr.removeEntry(s)})),PersistencePromise.waitFor(i)}getFromCache(e,i){return this.vr.getEntry(e,i)}getAllFromCache(e,i){return this.vr.getEntries(e,i)}}class __PRIVATE_MemoryTargetCache{constructor(e){this.persistence=e,this.ei=new ObjectMap((e=>__PRIVATE_canonifyTarget(e)),__PRIVATE_targetEquals),this.lastRemoteSnapshotVersion=SnapshotVersion.min(),this.highestTargetId=0,this.ti=0,this.ni=new __PRIVATE_ReferenceSet,this.targetCount=0,this.ri=__PRIVATE_TargetIdGenerator.rr()}forEachTarget(e,i){return this.ei.forEach(((e,s)=>i(s))),PersistencePromise.resolve()}getLastRemoteSnapshotVersion(e){return PersistencePromise.resolve(this.lastRemoteSnapshotVersion)}getHighestSequenceNumber(e){return PersistencePromise.resolve(this.ti)}allocateTargetId(e){return this.highestTargetId=this.ri.next(),PersistencePromise.resolve(this.highestTargetId)}setTargetsMetadata(e,i,s){return s&&(this.lastRemoteSnapshotVersion=s),i>this.ti&&(this.ti=i),PersistencePromise.resolve()}ar(e){this.ei.set(e.target,e);const i=e.targetId;i>this.highestTargetId&&(this.ri=new __PRIVATE_TargetIdGenerator(i),this.highestTargetId=i),e.sequenceNumber>this.ti&&(this.ti=e.sequenceNumber)}addTargetData(e,i){return this.ar(i),this.targetCount+=1,PersistencePromise.resolve()}updateTargetData(e,i){return this.ar(i),PersistencePromise.resolve()}removeTargetData(e,i){return this.ei.delete(i.target),this.ni.Ur(i.targetId),this.targetCount-=1,PersistencePromise.resolve()}removeTargets(e,i,s){let o=0;const _=[];return this.ei.forEach(((h,d)=>{d.sequenceNumber<=i&&null===s.get(d.targetId)&&(this.ei.delete(h),_.push(this.removeMatchingKeysForTargetId(e,d.targetId)),o++)})),PersistencePromise.waitFor(_).next((()=>o))}getTargetCount(e){return PersistencePromise.resolve(this.targetCount)}getTargetData(e,i){const s=this.ei.get(i)||null;return PersistencePromise.resolve(s)}addMatchingKeys(e,i,s){return this.ni.qr(i,s),PersistencePromise.resolve()}removeMatchingKeys(e,i,s){this.ni.$r(i,s);const o=this.persistence.referenceDelegate,_=[];return o&&i.forEach((i=>{_.push(o.markPotentiallyOrphaned(e,i))})),PersistencePromise.waitFor(_)}removeMatchingKeysForTargetId(e,i){return this.ni.Ur(i),PersistencePromise.resolve()}getMatchingKeysForTargetId(e,i){const s=this.ni.Wr(i);return PersistencePromise.resolve(s)}containsKey(e,i){return PersistencePromise.resolve(this.ni.containsKey(i))}}class __PRIVATE_MemoryPersistence{constructor(e,i){this.ii={},this.overlays={},this.si=new __PRIVATE_ListenSequence(0),this.oi=!1,this.oi=!0,this._i=new __PRIVATE_MemoryGlobalsCache,this.referenceDelegate=e(this),this.ai=new __PRIVATE_MemoryTargetCache(this),this.indexManager=new __PRIVATE_MemoryIndexManager,this.remoteDocumentCache=function __PRIVATE_newMemoryRemoteDocumentCache(e){return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e)}((e=>this.referenceDelegate.ui(e))),this.serializer=new __PRIVATE_LocalSerializer(i),this.ci=new __PRIVATE_MemoryBundleCache(this.serializer)}start(){return Promise.resolve()}shutdown(){return this.oi=!1,Promise.resolve()}get started(){return this.oi}setDatabaseDeletedListener(){}setNetworkEnabled(){}getIndexManager(e){return this.indexManager}getDocumentOverlayCache(e){let i=this.overlays[e.toKey()];return i||(i=new __PRIVATE_MemoryDocumentOverlayCache,this.overlays[e.toKey()]=i),i}getMutationQueue(e,i){let s=this.ii[e.toKey()];return s||(s=new __PRIVATE_MemoryMutationQueue(i,this.referenceDelegate),this.ii[e.toKey()]=s),s}getGlobalsCache(){return this._i}getTargetCache(){return this.ai}getRemoteDocumentCache(){return this.remoteDocumentCache}getBundleCache(){return this.ci}runTransaction(e,i,s){__PRIVATE_logDebug(“MemoryPersistence”,”Starting transaction:”,e);const o=new __PRIVATE_MemoryTransaction(this.si.next());return this.referenceDelegate.li(),s(o).next((e=>this.referenceDelegate.hi(o).next((()=>e)))).toPromise().then((e=>(o.raiseOnCommittedEvent(),e)))}Pi(e,i){return PersistencePromise.or(Object.values(this.ii).map((s=>()=>s.containsKey(e,i))))}}class __PRIVATE_MemoryTransaction extends PersistenceTransaction{constructor(e){super(),this.currentSequenceNumber=e}}class __PRIVATE_MemoryEagerDelegate{constructor(e){this.persistence=e,this.Ti=new __PRIVATE_ReferenceSet,this.Ii=null}static Ei(e){return new __PRIVATE_MemoryEagerDelegate(e)}get di(){if(this.Ii)return this.Ii;throw fail(60996)}addReference(e,i,s){return this.Ti.addReference(s,i),this.di.delete(s.toString()),PersistencePromise.resolve()}removeReference(e,i,s){return this.Ti.removeReference(s,i),this.di.add(s.toString()),PersistencePromise.resolve()}markPotentiallyOrphaned(e,i){return this.di.add(i.toString()),PersistencePromise.resolve()}removeTarget(e,i){this.Ti.Ur(i.targetId).forEach((e=>this.di.add(e.toString())));const s=this.persistence.getTargetCache();return s.getMatchingKeysForTargetId(e,i.targetId).next((e=>{e.forEach((e=>this.di.add(e.toString())))})).next((()=>s.removeTargetData(e,i)))}li(){this.Ii=new Set}hi(e){const i=this.persistence.getRemoteDocumentCache().newChangeBuffer();return PersistencePromise.forEach(this.di,(s=>{const o=DocumentKey.fromPath(s);return this.Ai(e,o).next((e=>{e||i.removeEntry(o,SnapshotVersion.min())}))})).next((()=>(this.Ii=null,i.apply(e))))}updateLimboDocument(e,i){return this.Ai(e,i).next((e=>{e?this.di.delete(i.toString()):this.di.add(i.toString())}))}ui(e){return 0}Ai(e,i){return PersistencePromise.or([()=>PersistencePromise.resolve(this.Ti.containsKey(i)),()=>this.persistence.getTargetCache().containsKey(e,i),()=>this.persistence.Pi(e,i)])}}class __PRIVATE_MemoryLruDelegate{constructor(e,i){this.persistence=e,this.Ri=new ObjectMap((e=>__PRIVATE_encodeResourcePath(e.path)),((e,i)=>e.isEqual(i))),this.garbageCollector=__PRIVATE_newLruGarbageCollector(this,i)}static Ei(e,i){return new __PRIVATE_MemoryLruDelegate(e,i)}li(){}hi(e){return PersistencePromise.resolve()}forEachTarget(e,i){return this.persistence.getTargetCache().forEachTarget(e,i)}dr(e){const i=this.Vr(e);return this.persistence.getTargetCache().getTargetCount(e).next((e=>i.next((i=>e+i))))}Vr(e){let i=0;return this.Ar(e,(e=>{i++})).next((()=>i))}Ar(e,i){return PersistencePromise.forEach(this.Ri,((s,o)=>this.gr(e,s,o).next((e=>e?PersistencePromise.resolve():i(o)))))}removeTargets(e,i,s){return this.persistence.getTargetCache().removeTargets(e,i,s)}removeOrphanedDocuments(e,i){let s=0;const o=this.persistence.getRemoteDocumentCache(),_=o.newChangeBuffer();return o.Xr(e,(o=>this.gr(e,o,i).next((e=>{e||(s++,_.removeEntry(o,SnapshotVersion.min()))})))).next((()=>_.apply(e))).next((()=>s))}markPotentiallyOrphaned(e,i){return this.Ri.set(i,e.currentSequenceNumber),PersistencePromise.resolve()}removeTarget(e,i){const s=i.withSequenceNumber(e.currentSequenceNumber);return this.persistence.getTargetCache().updateTargetData(e,s)}addReference(e,i,s){return this.Ri.set(s,e.currentSequenceNumber),PersistencePromise.resolve()}removeReference(e,i,s){return this.Ri.set(s,e.currentSequenceNumber),PersistencePromise.resolve()}updateLimboDocument(e,i){return this.Ri.set(i,e.currentSequenceNumber),PersistencePromise.resolve()}ui(e){let i=e.key.toString().length;return e.isFoundDocument()&&(i+=__PRIVATE_estimateByteSize(e.data.value)),i}gr(e,i,s){return PersistencePromise.or([()=>this.persistence.Pi(e,i),()=>this.persistence.getTargetCache().containsKey(e,i),()=>{const e=this.Ri.get(i);return PersistencePromise.resolve(void 0!==e&&e>s)}])}getCacheSize(e){return this.persistence.getRemoteDocumentCache().getSize(e)}}class __PRIVATE_SchemaConverter{constructor(e){this.serializer=e}q(e,i,s,o){const _=new __PRIVATE_SimpleDbTransaction(“createOrUpgrade”,i);s<1&&o>=1&&(function __PRIVATE_createPrimaryClientStore(e){e.createObjectStore(ve)}(e),function __PRIVATE_createMutationQueue(e){e.createObjectStore(Se,{keyPath:”userId”});e.createObjectStore(we,{keyPath:De,autoIncrement:!0}).createIndex(Ce,Fe,{unique:!0}),e.createObjectStore(Me)}(e),__PRIVATE_createQueryCache(e),function __PRIVATE_createLegacyRemoteDocumentCache(e){e.createObjectStore(Ve)}(e));let h=PersistencePromise.resolve();return s<3&&o>=3&&(0!==s&&(function __PRIVATE_dropQueryCache(e){e.deleteObjectStore(je),e.deleteObjectStore(Qe),e.deleteObjectStore(Ye)}(e),__PRIVATE_createQueryCache(e)),h=h.next((()=>function __PRIVATE_writeEmptyTargetGlobalEntry(e){const i=e.store(Ye),s={highestTargetId:0,highestListenSequenceNumber:0,lastRemoteSnapshotVersion:SnapshotVersion.min().toTimestamp(),targetCount:0};return i.put(Je,s)}(_)))),s<4&&o>=4&&(0!==s&&(h=h.next((()=>function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e,i){return i.store(we).J().next((s=>{e.deleteObjectStore(we),e.createObjectStore(we,{keyPath:De,autoIncrement:!0}).createIndex(Ce,Fe,{unique:!0});const o=i.store(we),_=s.map((e=>o.put(e)));return PersistencePromise.waitFor(_)}))}(e,_)))),h=h.next((()=>{!function __PRIVATE_createClientMetadataStore(e){e.createObjectStore(et,{keyPath:”clientId”})}(e)}))),s<5&&o>=5&&(h=h.next((()=>this.Vi(_)))),s<6&&o>=6&&(h=h.next((()=>(function __PRIVATE_createDocumentGlobalStore(e){e.createObjectStore(Ue)}(e),this.mi(_))))),s<7&&o>=7&&(h=h.next((()=>this.fi(_)))),s<8&&o>=8&&(h=h.next((()=>this.gi(e,_)))),s<9&&o>=9&&(h=h.next((()=>{!function __PRIVATE_dropRemoteDocumentChangesStore(e){e.objectStoreNames.contains(“remoteDocumentChanges”)&&e.deleteObjectStore(“remoteDocumentChanges”)}(e)}))),s<10&&o>=10&&(h=h.next((()=>this.pi(_)))),s<11&&o>=11&&(h=h.next((()=>{!function __PRIVATE_createBundlesStore(e){e.createObjectStore(tt,{keyPath:”bundleId”})}(e),function __PRIVATE_createNamedQueriesStore(e){e.createObjectStore(nt,{keyPath:”name”})}(e)}))),s<12&&o>=12&&(h=h.next((()=>{!function __PRIVATE_createDocumentOverlayStore(e){const i=e.createObjectStore(dt,{keyPath:mt});i.createIndex(ft,gt,{unique:!1}),i.createIndex(pt,Tt,{unique:!1})}(e)}))),s<13&&o>=13&&(h=h.next((()=>function __PRIVATE_createRemoteDocumentCache(e){const i=e.createObjectStore(Ne,{keyPath:ke});i.createIndex(Oe,Le),i.createIndex(Be,qe)}(e))).next((()=>this.yi(e,_))).next((()=>e.deleteObjectStore(Ve)))),s<14&&o>=14&&(h=h.next((()=>this.wi(e,_)))),s<15&&o>=15&&(h=h.next((()=>function __PRIVATE_createFieldIndex(e){e.createObjectStore(rt,{keyPath:”indexId”,autoIncrement:!0}).createIndex(it,”collectionGroup”,{unique:!1});e.createObjectStore(st,{keyPath:ot}).createIndex(at,ut,{unique:!1});e.createObjectStore(ct,{keyPath:lt}).createIndex(_t,ht,{unique:!1})}(e)))),s<16&&o>=16&&(h=h.next((()=>{i.objectStore(st).clear()})).next((()=>{i.objectStore(ct).clear()}))),s<17&&o>=17&&(h=h.next((()=>{!function __PRIVATE_createGlobalsStore(e){e.createObjectStore(It,{keyPath:”name”})}(e)}))),h}mi(e){let i=0;return e.store(Ve).te(((e,s)=>{i+=__PRIVATE_dbDocumentSize(s)})).next((()=>{const s={byteSize:i};return e.store(Ue).put(Ke,s)}))}Vi(e){const i=e.store(Se),s=e.store(we);return i.J().next((i=>PersistencePromise.forEach(i,(i=>{const o=IDBKeyRange.bound([i.userId,Re],[i.userId,i.lastAcknowledgedBatchId]);return s.J(Ce,o).next((s=>PersistencePromise.forEach(s,(s=>{__PRIVATE_hardAssert(s.userId===i.userId,18650,”Cannot process batch from unexpected user”,{batchId:s.batchId});const o=__PRIVATE_fromDbMutationBatch(this.serializer,s);return removeMutationBatch(e,i.userId,o).next((()=>{}))}))))}))))}fi(e){const i=e.store(je),s=e.store(Ve);return e.store(Ye).get(Je).next((e=>{const o=[];return s.te(((s,_)=>{const h=new ResourcePath(s),d=function __PRIVATE_sentinelKey(e){return[0,__PRIVATE_encodeResourcePath(e)]}(h);o.push(i.get(d).next((s=>s?PersistencePromise.resolve():(s=>i.put({targetId:0,path:__PRIVATE_encodeResourcePath(s),sequenceNumber:e.highestListenSequenceNumber}))(h))))})).next((()=>PersistencePromise.waitFor(o)))}))}gi(e,i){e.createObjectStore(Xe,{keyPath:Ze});const s=i.store(Xe),o=new __PRIVATE_MemoryCollectionParentIndex,addEntry=e=>{if(o.add(e)){const i=e.lastSegment(),o=e.popLast();return s.put({collectionId:i,parent:__PRIVATE_encodeResourcePath(o)})}};return i.store(Ve).te({ee:!0},((e,i)=>{const s=new ResourcePath(e);return addEntry(s.popLast())})).next((()=>i.store(Me).te({ee:!0},(([e,i,s],o)=>{const _=__PRIVATE_decodeResourcePath(i);return addEntry(_.popLast())}))))}pi(e){const i=e.store(Qe);return i.te(((e,s)=>{const o=__PRIVATE_fromDbTarget(s),_=__PRIVATE_toDbTarget(this.serializer,o);return i.put(_)}))}yi(e,i){const s=i.store(Ve),o=[];return s.te(((e,s)=>{const _=i.store(Ne),h=function __PRIVATE_extractKey(e){return e.document?new DocumentKey(ResourcePath.fromString(e.document.name).popFirst(5)):e.noDocument?DocumentKey.fromSegments(e.noDocument.path):e.unknownDocument?DocumentKey.fromSegments(e.unknownDocument.path):fail(36783)}(s).path.toArray(),d={prefixPath:h.slice(0,h.length-2),collectionGroup:h[h.length-2],documentId:h[h.length-1],readTime:s.readTime||[0,0],unknownDocument:s.unknownDocument,noDocument:s.noDocument,document:s.document,hasCommittedMutations:!!s.hasCommittedMutations};o.push(_.put(d))})).next((()=>PersistencePromise.waitFor(o)))}wi(e,i){const s=i.store(we),o=__PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer),_=new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Ei,this.serializer.wt);return s.J().next((e=>{const s=new Map;return e.forEach((e=>{var i;let o=null!==(i=s.get(e.userId))&&void 0!==i?i:__PRIVATE_documentKeySet();__PRIVATE_fromDbMutationBatch(this.serializer,e).keys().forEach((e=>o=o.add(e))),s.set(e.userId,o)})),PersistencePromise.forEach(s,((e,s)=>{const h=new User(s),d=__PRIVATE_IndexedDbDocumentOverlayCache.bt(this.serializer,h),f=_.getIndexManager(h),g=__PRIVATE_IndexedDbMutationQueue.bt(h,this.serializer,f,_.referenceDelegate);return new LocalDocumentsView(o,g,d,f).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(i,__PRIVATE_ListenSequence.le),e).next()}))}))}}function __PRIVATE_createQueryCache(e){e.createObjectStore(je,{keyPath:We}).createIndex($e,He,{unique:!0}),e.createObjectStore(Qe,{keyPath:”targetId”}).createIndex(ze,Ge,{unique:!0}),e.createObjectStore(Ye)}const on=”IndexedDbPersistence”,an=18e5,un=5e3,cn=”Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.”,ln=”main”;class __PRIVATE_IndexedDbPersistence{constructor(e,i,s,o,_,h,d,f,g,b,w=17){if(this.allowTabSynchronization=e,this.persistenceKey=i,this.clientId=s,this.bi=_,this.window=h,this.document=d,this.Si=g,this.Di=b,this.Ci=w,this.si=null,this.oi=!1,this.isPrimary=!1,this.networkEnabled=!0,this.Fi=null,this.inForeground=!1,this.Mi=null,this.xi=null,this.Oi=Number.NEGATIVE_INFINITY,this.Ni=e=>Promise.resolve(),!__PRIVATE_IndexedDbPersistence.C())throw new FirestoreError(de.UNIMPLEMENTED,”This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.”);this.referenceDelegate=new __PRIVATE_IndexedDbLruDelegateImpl(this,o),this.Bi=i+ln,this.serializer=new __PRIVATE_LocalSerializer(f),this.Li=new __PRIVATE_SimpleDb(this.Bi,this.Ci,new __PRIVATE_SchemaConverter(this.serializer)),this._i=new __PRIVATE_IndexedDbGlobalsCache,this.ai=new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate,this.serializer),this.remoteDocumentCache=__PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer),this.ci=new __PRIVATE_IndexedDbBundleCache,this.window&&this.window.localStorage?this.ki=this.window.localStorage:(this.ki=null,!1===b&&__PRIVATE_logError(on,”LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.”))}start(){return this.qi().then((()=>{if(!this.isPrimary&&!this.allowTabSynchronization)throw new FirestoreError(de.FAILED_PRECONDITION,cn);return this.Qi(),this.$i(),this.Ui(),this.runTransaction(“getHighestListenSequenceNumber”,”readonly”,(e=>this.ai.getHighestSequenceNumber(e)))})).then((e=>{this.si=new __PRIVATE_ListenSequence(e,this.Si)})).then((()=>{this.oi=!0})).catch((e=>(this.Li&&this.Li.close(),Promise.reject(e))))}Ki(e){return this.Ni=async i=>{if(this.started)return e(i)},e(this.isPrimary)}setDatabaseDeletedListener(e){this.Li.U((async i=>{null===i.newVersion&&await e()}))}setNetworkEnabled(e){this.networkEnabled!==e&&(this.networkEnabled=e,this.bi.enqueueAndForget((async()=>{this.started&&await this.qi()})))}qi(){return this.runTransaction(“updateClientMetadataAndTryBecomePrimary”,”readwrite”,(e=>__PRIVATE_clientMetadataStore(e).put({clientId:this.clientId,updateTimeMs:Date.now(),networkEnabled:this.networkEnabled,inForeground:this.inForeground}).next((()=>{if(this.isPrimary)return this.Wi(e).next((e=>{e||(this.isPrimary=!1,this.bi.enqueueRetryable((()=>this.Ni(!1))))}))})).next((()=>this.Gi(e))).next((i=>this.isPrimary&&!i?this.zi(e).next((()=>!1)):!!i&&this.ji(e).next((()=>!0)))))).catch((e=>{if(__PRIVATE_isIndexedDbTransactionError(e))return __PRIVATE_logDebug(on,”Failed to extend owner lease: “,e),this.isPrimary;if(!this.allowTabSynchronization)throw e;return __PRIVATE_logDebug(on,”Releasing owner lease after error during lease refresh”,e),!1})).then((e=>{this.isPrimary!==e&&this.bi.enqueueRetryable((()=>this.Ni(e))),this.isPrimary=e}))}Wi(e){return __PRIVATE_primaryClientStore(e).get(be).next((e=>PersistencePromise.resolve(this.Hi(e))))}Ji(e){return __PRIVATE_clientMetadataStore(e).delete(this.clientId)}async Yi(){if(this.isPrimary&&!this.Zi(this.Oi,an)){this.Oi=Date.now();const e=await this.runTransaction(“maybeGarbageCollectMultiClientState”,”readwrite-primary”,(e=>{const i=__PRIVATE_getStore(e,et);return i.J().next((e=>{const s=this.Xi(e,an),o=e.filter((e=>-1===s.indexOf(e)));return PersistencePromise.forEach(o,(e=>i.delete(e.clientId))).next((()=>o))}))})).catch((()=>[]));if(this.ki)for(const i of e)this.ki.removeItem(this.es(i.clientId))}}Ui(){this.xi=this.bi.enqueueAfterDelay(“client_metadata_refresh”,4e3,(()=>this.qi().then((()=>this.Yi())).then((()=>this.Ui()))))}Hi(e){return!!e&&e.ownerId===this.clientId}Gi(e){return this.Di?PersistencePromise.resolve(!0):__PRIVATE_primaryClientStore(e).get(be).next((i=>{if(null!==i&&this.Zi(i.leaseTimestampMs,un)&&!this.ts(i.ownerId)){if(this.Hi(i)&&this.networkEnabled)return!0;if(!this.Hi(i)){if(!i.allowTabSynchronization)throw new FirestoreError(de.FAILED_PRECONDITION,cn);return!1}}return!(!this.networkEnabled||!this.inForeground)||__PRIVATE_clientMetadataStore(e).J().next((e=>void 0===this.Xi(e,un).find((e=>{if(this.clientId!==e.clientId){const i=!this.networkEnabled&&e.networkEnabled,s=!this.inForeground&&e.inForeground,o=this.networkEnabled===e.networkEnabled;if(i||s&&o)return!0}return!1}))))})).next((e=>(this.isPrimary!==e&&__PRIVATE_logDebug(on,`Client ${e?”is”:”is not”} eligible for a primary lease.`),e)))}async shutdown(){this.oi=!1,this.ns(),this.xi&&(this.xi.cancel(),this.xi=null),this.rs(),this.ss(),await this.Li.runTransaction(“shutdown”,”readwrite”,[ve,et],(e=>{const i=new __PRIVATE_IndexedDbTransaction(e,__PRIVATE_ListenSequence.le);return this.zi(i).next((()=>this.Ji(i)))})),this.Li.close(),this._s()}Xi(e,i){return e.filter((e=>this.Zi(e.updateTimeMs,i)&&!this.ts(e.clientId)))}us(){return this.runTransaction(“getActiveClients”,”readonly”,(e=>__PRIVATE_clientMetadataStore(e).J().next((e=>this.Xi(e,an).map((e=>e.clientId))))))}get started(){return this.oi}getGlobalsCache(){return this._i}getMutationQueue(e,i){return __PRIVATE_IndexedDbMutationQueue.bt(e,this.serializer,i,this.referenceDelegate)}getTargetCache(){return this.ai}getRemoteDocumentCache(){return this.remoteDocumentCache}getIndexManager(e){return new __PRIVATE_IndexedDbIndexManager(e,this.serializer.wt.databaseId)}getDocumentOverlayCache(e){return __PRIVATE_IndexedDbDocumentOverlayCache.bt(this.serializer,e)}getBundleCache(){return this.ci}runTransaction(e,i,s){__PRIVATE_logDebug(on,”Starting transaction:”,e);const o=”readonly”===i?”readonly”:”readwrite”,_=function __PRIVATE_getObjectStores(e){return 17===e?vt:16===e?Vt:15===e?yt:14===e?Rt:13===e?At:12===e?Pt:11===e?Et:void fail(60245)}(this.Ci);let h;return this.Li.runTransaction(e,o,_,(o=>(h=new __PRIVATE_IndexedDbTransaction(o,this.si?this.si.next():__PRIVATE_ListenSequence.le),”readwrite-primary”===i?this.Wi(h).next((e=>!!e||this.Gi(h))).next((i=>{if(!i)throw __PRIVATE_logError(`Failed to obtain primary lease for action ‘${e}’.`),this.isPrimary=!1,this.bi.enqueueRetryable((()=>this.Ni(!1))),new FirestoreError(de.FAILED_PRECONDITION,Ie);return s(h)})).next((e=>this.ji(h).next((()=>e)))):this.cs(h).next((()=>s(h)))))).then((e=>(h.raiseOnCommittedEvent(),e)))}cs(e){return __PRIVATE_primaryClientStore(e).get(be).next((e=>{if(null!==e&&this.Zi(e.leaseTimestampMs,un)&&!this.ts(e.ownerId)&&!this.Hi(e)&&!(this.Di||this.allowTabSynchronization&&e.allowTabSynchronization))throw new FirestoreError(de.FAILED_PRECONDITION,cn)}))}ji(e){const i={ownerId:this.clientId,allowTabSynchronization:this.allowTabSynchronization,leaseTimestampMs:Date.now()};return __PRIVATE_primaryClientStore(e).put(be,i)}static C(){return __PRIVATE_SimpleDb.C()}zi(e){const i=__PRIVATE_primaryClientStore(e);return i.get(be).next((e=>this.Hi(e)?(__PRIVATE_logDebug(on,”Releasing primary lease.”),i.delete(be)):PersistencePromise.resolve()))}Zi(e,i){const s=Date.now();return!(es&&(__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${s}`),1))}Qi(){null!==this.document&&”function”==typeof this.document.addEventListener&&(this.Mi=()=>{this.bi.enqueueAndForget((()=>(this.inForeground=”visible”===this.document.visibilityState,this.qi())))},this.document.addEventListener(“visibilitychange”,this.Mi),this.inForeground=”visible”===this.document.visibilityState)}rs(){this.Mi&&(this.document.removeEventListener(“visibilitychange”,this.Mi),this.Mi=null)}$i(){var e;”function”==typeof(null===(e=this.window)||void 0===e?void 0:e.addEventListener)&&(this.Fi=()=>{this.ns();const e=/(?:Version|Mobile)\/1[456]/;isSafari()&&(navigator.appVersion.match(e)||navigator.userAgent.match(e))&&this.bi.enterRestrictedMode(!0),this.bi.enqueueAndForget((()=>this.shutdown()))},this.window.addEventListener(“pagehide”,this.Fi))}ss(){this.Fi&&(this.window.removeEventListener(“pagehide”,this.Fi),this.Fi=null)}ts(e){var i;try{const s=null!==(null===(i=this.ki)||void 0===i?void 0:i.getItem(this.es(e)));return __PRIVATE_logDebug(on,`Client ‘${e}’ ${s?”is”:”is not”} zombied in LocalStorage`),s}catch(e){return __PRIVATE_logError(on,”Failed to get zombied client id.”,e),!1}}ns(){if(this.ki)try{this.ki.setItem(this.es(this.clientId),String(Date.now()))}catch(e){__PRIVATE_logError(“Failed to set zombie client id.”,e)}}_s(){if(this.ki)try{this.ki.removeItem(this.es(this.clientId))}catch(e){}}es(e){return`firestore_zombie_${this.persistenceKey}_${e}`}}function __PRIVATE_primaryClientStore(e){return __PRIVATE_getStore(e,ve)}function __PRIVATE_clientMetadataStore(e){return __PRIVATE_getStore(e,et)}function __PRIVATE_indexedDbStoragePrefix(e,i){let s=e.projectId;return e.isDefaultDatabase||(s+=”.”+e.database),”firestore/”+i+”/”+s+”/”}class __PRIVATE_LocalViewChanges{constructor(e,i,s,o){this.targetId=e,this.fromCache=i,this.ls=s,this.hs=o}static Ps(e,i){let s=__PRIVATE_documentKeySet(),o=__PRIVATE_documentKeySet();for(const e of i.docChanges)switch(e.type){case 0:s=s.add(e.doc.key);break;case 1:o=o.add(e.doc.key)}return new __PRIVATE_LocalViewChanges(e,i.fromCache,s,o)}}class QueryContext{constructor(){this._documentReadCount=0}get documentReadCount(){return this._documentReadCount}incrementDocumentReadCount(e){this._documentReadCount+=e}}class __PRIVATE_QueryEngine{constructor(){this.Ts=!1,this.Is=!1,this.Es=100,this.ds=function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument(){return isSafari()?8:__PRIVATE_getAndroidVersion(getUA())>0?6:4}()}initialize(e,i){this.As=e,this.indexManager=i,this.Ts=!0}getDocumentsMatchingQuery(e,i,s,o){const _={result:null};return this.Rs(e,i).next((e=>{_.result=e})).next((()=>{if(!_.result)return this.Vs(e,i,o,s).next((e=>{_.result=e}))})).next((()=>{if(_.result)return;const s=new QueryContext;return this.fs(e,i,s).next((o=>{if(_.result=o,this.Is)return this.gs(e,i,s,o.size)}))})).next((()=>_.result))}gs(e,i,s,o){return s.documentReadCountthis.ds*o?(__PRIVATE_getLogLevel()<=g.DEBUG&&__PRIVATE_logDebug("QueryEngine","The SDK decides to create cache indexes for query:",__PRIVATE_stringifyQuery(i),"as using cache indexes may help improve performance."),this.indexManager.createTargetIndexes(e,__PRIVATE_queryToTarget(i))):PersistencePromise.resolve())}Rs(e,i){if(__PRIVATE_queryMatchesAllDocuments(i))return PersistencePromise.resolve(null);let s=__PRIVATE_queryToTarget(i);return this.indexManager.getIndexType(e,s).next((o=>0===o?null:(null!==i.limit&&1===o&&(i=__PRIVATE_queryWithLimit(i,null,”F”),s=__PRIVATE_queryToTarget(i)),this.indexManager.getDocumentsMatchingTarget(e,s).next((o=>{const _=__PRIVATE_documentKeySet(…o);return this.As.getDocuments(e,_).next((o=>this.indexManager.getMinOffset(e,s).next((s=>{const h=this.ps(i,o);return this.ys(i,h,_,s.readTime)?this.Rs(e,__PRIVATE_queryWithLimit(i,null,”F”)):this.ws(e,h,i,s)}))))})))))}Vs(e,i,s,o){return __PRIVATE_queryMatchesAllDocuments(i)||o.isEqual(SnapshotVersion.min())?PersistencePromise.resolve(null):this.As.getDocuments(e,s).next((_=>{const h=this.ps(i,_);return this.ys(i,h,s,o)?PersistencePromise.resolve(null):(__PRIVATE_getLogLevel()<=g.DEBUG&&__PRIVATE_logDebug("QueryEngine","Re-using previous result from %s to execute query: %s",o.toString(),__PRIVATE_stringifyQuery(i)),this.ws(e,h,i,__PRIVATE_newIndexOffsetSuccessorFromReadTime(o,Te)).next((e=>e)))}))}ps(e,i){let s=new SortedSet(__PRIVATE_newQueryComparator(e));return i.forEach(((i,o)=>{__PRIVATE_queryMatches(e,o)&&(s=s.add(o))})),s}ys(e,i,s,o){if(null===e.limit)return!1;if(s.size!==i.size)return!0;const _=”F”===e.limitType?i.last():i.first();return!!_&&(_.hasPendingWrites||_.version.compareTo(o)>0)}fs(e,i,s){return __PRIVATE_getLogLevel()<=g.DEBUG&&__PRIVATE_logDebug("QueryEngine","Using full collection scan to execute query:",__PRIVATE_stringifyQuery(i)),this.As.getDocumentsMatchingQuery(e,i,IndexOffset.min(),s)}ws(e,i,s,o){return this.As.getDocumentsMatchingQuery(e,s,o).next((e=>(i.forEach((i=>{e=e.insert(i.key,i)})),e)))}}const _n=”LocalStore”;class __PRIVATE_LocalStoreImpl{constructor(e,i,s,o){this.persistence=e,this.bs=i,this.serializer=o,this.Ss=new SortedMap(__PRIVATE_primitiveComparator),this.Ds=new ObjectMap((e=>__PRIVATE_canonifyTarget(e)),__PRIVATE_targetEquals),this.vs=new Map,this.Cs=e.getRemoteDocumentCache(),this.ai=e.getTargetCache(),this.ci=e.getBundleCache(),this.Fs(s)}Fs(e){this.documentOverlayCache=this.persistence.getDocumentOverlayCache(e),this.indexManager=this.persistence.getIndexManager(e),this.mutationQueue=this.persistence.getMutationQueue(e,this.indexManager),this.localDocuments=new LocalDocumentsView(this.Cs,this.mutationQueue,this.documentOverlayCache,this.indexManager),this.Cs.setIndexManager(this.indexManager),this.bs.initialize(this.localDocuments,this.indexManager)}collectGarbage(e){return this.persistence.runTransaction(“Collect garbage”,”readwrite-primary”,(i=>e.collect(i,this.Ss)))}}function __PRIVATE_newLocalStore(e,i,s,o){return new __PRIVATE_LocalStoreImpl(e,i,s,o)}async function __PRIVATE_localStoreHandleUserChange(e,i){const s=__PRIVATE_debugCast(e);return await s.persistence.runTransaction(“Handle user change”,”readonly”,(e=>{let o;return s.mutationQueue.getAllMutationBatches(e).next((_=>(o=_,s.Fs(i),s.mutationQueue.getAllMutationBatches(e)))).next((i=>{const _=[],h=[];let d=__PRIVATE_documentKeySet();for(const e of o){_.push(e.batchId);for(const i of e.mutations)d=d.add(i.key)}for(const e of i){h.push(e.batchId);for(const i of e.mutations)d=d.add(i.key)}return s.localDocuments.getDocuments(e,d).next((e=>({Ms:e,removedBatchIds:_,addedBatchIds:h})))}))}))}function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e){const i=__PRIVATE_debugCast(e);return i.persistence.runTransaction(“Get last remote snapshot version”,”readonly”,(e=>i.ai.getLastRemoteSnapshotVersion(e)))}function __PRIVATE_populateDocumentChangeBuffer(e,i,s){let o=__PRIVATE_documentKeySet(),_=__PRIVATE_documentKeySet();return s.forEach((e=>o=o.add(e))),i.getEntries(e,o).next((e=>{let o=__PRIVATE_mutableDocumentMap();return s.forEach(((s,h)=>{const d=e.get(s);h.isFoundDocument()!==d.isFoundDocument()&&(_=_.add(s)),h.isNoDocument()&&h.version.isEqual(SnapshotVersion.min())?(i.removeEntry(s,h.readTime),o=o.insert(s,h)):!d.isValidDocument()||h.version.compareTo(d.version)>0||0===h.version.compareTo(d.version)&&d.hasPendingWrites?(i.addEntry(h),o=o.insert(s,h)):__PRIVATE_logDebug(_n,”Ignoring outdated watch update for “,s,”. Current version:”,d.version,” Watch version:”,h.version)})),{xs:o,Os:_}}))}function __PRIVATE_localStoreGetNextMutationBatch(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction(“Get next mutation batch”,”readonly”,(e=>(void 0===i&&(i=Re),s.mutationQueue.getNextMutationBatchAfterBatchId(e,i))))}function __PRIVATE_localStoreAllocateTarget(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction(“Allocate target”,”readwrite”,(e=>{let o;return s.ai.getTargetData(e,i).next((_=>_?(o=_,PersistencePromise.resolve(o)):s.ai.allocateTargetId(e).next((_=>(o=new TargetData(i,_,”TargetPurposeListen”,e.currentSequenceNumber),s.ai.addTargetData(e,o).next((()=>o)))))))})).then((e=>{const o=s.Ss.get(e.targetId);return(null===o||e.snapshotVersion.compareTo(o.snapshotVersion)>0)&&(s.Ss=s.Ss.insert(e.targetId,e),s.Ds.set(i,e.targetId)),e}))}async function __PRIVATE_localStoreReleaseTarget(e,i,s){const o=__PRIVATE_debugCast(e),_=o.Ss.get(i),h=s?”readwrite”:”readwrite-primary”;try{s||await o.persistence.runTransaction(“Release target”,h,(e=>o.persistence.referenceDelegate.removeTarget(e,_)))}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug(_n,`Failed to update sequence numbers for target ${i}: ${e}`)}o.Ss=o.Ss.remove(i),o.Ds.delete(_.target)}function __PRIVATE_localStoreExecuteQuery(e,i,s){const o=__PRIVATE_debugCast(e);let _=SnapshotVersion.min(),h=__PRIVATE_documentKeySet();return o.persistence.runTransaction(“Execute query”,”readwrite”,(e=>function __PRIVATE_localStoreGetTargetData(e,i,s){const o=__PRIVATE_debugCast(e),_=o.Ds.get(s);return void 0!==_?PersistencePromise.resolve(o.Ss.get(_)):o.ai.getTargetData(i,s)}(o,e,__PRIVATE_queryToTarget(i)).next((i=>{if(i)return _=i.lastLimboFreeSnapshotVersion,o.ai.getMatchingKeysForTargetId(e,i.targetId).next((e=>{h=e}))})).next((()=>o.bs.getDocumentsMatchingQuery(e,i,s?_:SnapshotVersion.min(),s?h:__PRIVATE_documentKeySet()))).next((e=>(__PRIVATE_setMaxReadTime(o,__PRIVATE_queryCollectionGroup(i),e),{documents:e,Ns:h})))))}function __PRIVATE_localStoreGetCachedTarget(e,i){const s=__PRIVATE_debugCast(e),o=__PRIVATE_debugCast(s.ai),_=s.Ss.get(i);return _?Promise.resolve(_.target):s.persistence.runTransaction(“Get target data”,”readonly”,(e=>o.Rt(e,i).next((e=>e?e.target:null))))}function __PRIVATE_localStoreGetNewDocumentChanges(e,i){const s=__PRIVATE_debugCast(e),o=s.vs.get(i)||SnapshotVersion.min();return s.persistence.runTransaction(“Get new document changes”,”readonly”,(e=>s.Cs.getAllFromCollectionGroup(e,i,__PRIVATE_newIndexOffsetSuccessorFromReadTime(o,Te),Number.MAX_SAFE_INTEGER))).then((e=>(__PRIVATE_setMaxReadTime(s,i,e),e)))}function __PRIVATE_setMaxReadTime(e,i,s){let o=e.vs.get(i)||SnapshotVersion.min();s.forEach(((e,i)=>{i.readTime.compareTo(o)>0&&(o=i.readTime)})),e.vs.set(i,o)}async function __PRIVATE_localStoreSaveNamedQuery(e,i,s=__PRIVATE_documentKeySet()){const o=await __PRIVATE_localStoreAllocateTarget(e,__PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(i.bundledQuery))),_=__PRIVATE_debugCast(e);return _.persistence.runTransaction(“Save named query”,”readwrite”,(e=>{const h=__PRIVATE_fromVersion(i.readTime);if(o.snapshotVersion.compareTo(h)>=0)return _.ci.saveNamedQuery(e,i);const d=o.withResumeToken(ByteString.EMPTY_BYTE_STRING,h);return _.Ss=_.Ss.insert(d.targetId,d),_.ai.updateTargetData(e,d).next((()=>_.ai.removeMatchingKeysForTargetId(e,o.targetId))).next((()=>_.ai.addMatchingKeys(e,s,o.targetId))).next((()=>_.ci.saveNamedQuery(e,i)))}))}const hn=”firestore_clients”;function createWebStorageClientStateKey(e,i){return`${hn}_${e}_${i}`}const dn=”firestore_mutations”;function createWebStorageMutationBatchKey(e,i,s){let o=`${dn}_${e}_${s}`;return i.isAuthenticated()&&(o+=`_${i.uid}`),o}const mn=”firestore_targets”;function createWebStorageQueryTargetMetadataKey(e,i){return`${mn}_${e}_${i}`}const fn=”SharedClientState”;class __PRIVATE_MutationMetadata{constructor(e,i,s,o){this.user=e,this.batchId=i,this.state=s,this.error=o}static qs(e,i,s){const o=JSON.parse(s);let _,h=”object”==typeof o&&-1!==[“pending”,”acknowledged”,”rejected”].indexOf(o.state)&&(void 0===o.error||”object”==typeof o.error);return h&&o.error&&(h=”string”==typeof o.error.message&&”string”==typeof o.error.code,h&&(_=new FirestoreError(o.error.code,o.error.message))),h?new __PRIVATE_MutationMetadata(e,i,o.state,_):(__PRIVATE_logError(fn,`Failed to parse mutation state for ID ‘${i}’: ${s}`),null)}Qs(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class __PRIVATE_QueryTargetMetadata{constructor(e,i,s){this.targetId=e,this.state=i,this.error=s}static qs(e,i){const s=JSON.parse(i);let o,_=”object”==typeof s&&-1!==[“not-current”,”current”,”rejected”].indexOf(s.state)&&(void 0===s.error||”object”==typeof s.error);return _&&s.error&&(_=”string”==typeof s.error.message&&”string”==typeof s.error.code,_&&(o=new FirestoreError(s.error.code,s.error.message))),_?new __PRIVATE_QueryTargetMetadata(e,s.state,o):(__PRIVATE_logError(fn,`Failed to parse target state for ID ‘${e}’: ${i}`),null)}Qs(){const e={state:this.state,updateTimeMs:Date.now()};return this.error&&(e.error={code:this.error.code,message:this.error.message}),JSON.stringify(e)}}class __PRIVATE_RemoteClientState{constructor(e,i){this.clientId=e,this.activeTargetIds=i}static qs(e,i){const s=JSON.parse(i);let o=”object”==typeof s&&s.activeTargetIds instanceof Array,_=__PRIVATE_targetIdSet();for(let e=0;o&ðis.shutdown())),this.started=!0}writeSequenceNumber(e){this.setItem(this.Js,JSON.stringify(e))}getAllActiveQueryTargets(){return this.oo(this.zs)}isActiveQueryTarget(e){let i=!1;return this.zs.forEach(((s,o)=>{o.activeTargetIds.has(e)&&(i=!0)})),i}addPendingMutation(e){this._o(e,”pending”)}updateMutationState(e,i,s){this._o(e,i,s),this.ao(e)}addLocalQueryTarget(e,i=!0){let s=”not-current”;if(this.isActiveQueryTarget(e)){const i=this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey,e));if(i){const o=__PRIVATE_QueryTargetMetadata.qs(e,i);o&&(s=o.state)}}return i&&this.uo.$s(e),this.ro(),s}removeLocalQueryTarget(e){this.uo.Us(e),this.ro()}isLocalQueryTarget(e){return this.uo.activeTargetIds.has(e)}clearQueryState(e){this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey,e))}updateQueryState(e,i,s){this.co(e,i,s)}handleUserChange(e,i,s){i.forEach((e=>{this.ao(e)})),this.currentUser=e,s.forEach((e=>{this.addPendingMutation(e)}))}setOnlineState(e){this.lo(e)}notifyBundleLoaded(e){this.ho(e)}shutdown(){this.started&&(this.window.removeEventListener(“storage”,this.Ws),this.removeItem(this.Hs),this.started=!1)}getItem(e){const i=this.storage.getItem(e);return __PRIVATE_logDebug(fn,”READ”,e,i),i}setItem(e,i){__PRIVATE_logDebug(fn,”SET”,e,i),this.storage.setItem(e,i)}removeItem(e){__PRIVATE_logDebug(fn,”REMOVE”,e),this.storage.removeItem(e)}Gs(e){const i=e;if(i.storageArea===this.storage){if(__PRIVATE_logDebug(fn,”EVENT”,i.key,i.newValue),i.key===this.Hs)return void __PRIVATE_logError(“Received WebStorage notification for local change. Another client might have garbage-collected our state”);this.bi.enqueueRetryable((async()=>{if(this.started){if(null!==i.key)if(this.Ys.test(i.key)){if(null==i.newValue){const e=this.Po(i.key);return this.To(e,null)}{const e=this.Io(i.key,i.newValue);if(e)return this.To(e.clientId,e)}}else if(this.Zs.test(i.key)){if(null!==i.newValue){const e=this.Eo(i.key,i.newValue);if(e)return this.Ao(e)}}else if(this.Xs.test(i.key)){if(null!==i.newValue){const e=this.Ro(i.key,i.newValue);if(e)return this.Vo(e)}}else if(i.key===this.eo){if(null!==i.newValue){const e=this.io(i.newValue);if(e)return this.so(e)}}else if(i.key===this.Js){const e=function __PRIVATE_fromWebStorageSequenceNumber(e){let i=__PRIVATE_ListenSequence.le;if(null!=e)try{const s=JSON.parse(e);__PRIVATE_hardAssert(“number”==typeof s,30636,{mo:e}),i=s}catch(e){__PRIVATE_logError(fn,”Failed to read sequence number from WebStorage”,e)}return i}(i.newValue);e!==__PRIVATE_ListenSequence.le&&this.sequenceNumberHandler(e)}else if(i.key===this.no){const e=this.fo(i.newValue);await Promise.all(e.map((e=>this.syncEngine.po(e))))}}else this.js.push(i)}))}}get uo(){return this.zs.get(this.Ks)}ro(){this.setItem(this.Hs,this.uo.Qs())}_o(e,i,s){const o=new __PRIVATE_MutationMetadata(this.currentUser,e,i,s),_=createWebStorageMutationBatchKey(this.persistenceKey,this.currentUser,e);this.setItem(_,o.Qs())}ao(e){const i=createWebStorageMutationBatchKey(this.persistenceKey,this.currentUser,e);this.removeItem(i)}lo(e){const i={clientId:this.Ks,onlineState:e};this.storage.setItem(this.eo,JSON.stringify(i))}co(e,i,s){const o=createWebStorageQueryTargetMetadataKey(this.persistenceKey,e),_=new __PRIVATE_QueryTargetMetadata(e,i,s);this.setItem(o,_.Qs())}ho(e){const i=JSON.stringify(Array.from(e));this.setItem(this.no,i)}Po(e){const i=this.Ys.exec(e);return i?i[1]:null}Io(e,i){const s=this.Po(e);return __PRIVATE_RemoteClientState.qs(s,i)}Eo(e,i){const s=this.Zs.exec(e),o=Number(s[1]),_=void 0!==s[2]?s[2]:null;return __PRIVATE_MutationMetadata.qs(new User(_),o,i)}Ro(e,i){const s=this.Xs.exec(e),o=Number(s[1]);return __PRIVATE_QueryTargetMetadata.qs(o,i)}io(e){return __PRIVATE_SharedOnlineState.qs(e)}fo(e){return JSON.parse(e)}async Ao(e){if(e.user.uid===this.currentUser.uid)return this.syncEngine.yo(e.batchId,e.state,e.error);__PRIVATE_logDebug(fn,`Ignoring mutation for non-active user ${e.user.uid}`)}Vo(e){return this.syncEngine.wo(e.targetId,e.state,e.error)}To(e,i){const s=i?this.zs.insert(e,i):this.zs.remove(e),o=this.oo(this.zs),_=this.oo(s),h=[],d=[];return _.forEach((e=>{o.has(e)||h.push(e)})),o.forEach((e=>{_.has(e)||d.push(e)})),this.syncEngine.bo(h,d).then((()=>{this.zs=s}))}so(e){this.zs.get(e.clientId)&&this.onlineStateHandler(e.onlineState)}oo(e){let i=__PRIVATE_targetIdSet();return e.forEach(((e,s)=>{i=i.unionWith(s.activeTargetIds)})),i}}class __PRIVATE_MemorySharedClientState{constructor(){this.So=new __PRIVATE_LocalClientState,this.Do={},this.onlineStateHandler=null,this.sequenceNumberHandler=null}addPendingMutation(e){}updateMutationState(e,i,s){}addLocalQueryTarget(e,i=!0){return i&&this.So.$s(e),this.Do[e]||”not-current”}updateQueryState(e,i,s){this.Do[e]=i}removeLocalQueryTarget(e){this.So.Us(e)}isLocalQueryTarget(e){return this.So.activeTargetIds.has(e)}clearQueryState(e){delete this.Do[e]}getAllActiveQueryTargets(){return this.So.activeTargetIds}isActiveQueryTarget(e){return this.So.activeTargetIds.has(e)}start(){return this.So=new __PRIVATE_LocalClientState,Promise.resolve()}handleUserChange(e,i,s){}setOnlineState(e){}shutdown(){}writeSequenceNumber(e){}notifyBundleLoaded(e){}}class __PRIVATE_NoopConnectivityMonitor{vo(e){}shutdown(){}}const gn=”ConnectivityMonitor”;class __PRIVATE_BrowserConnectivityMonitor{constructor(){this.Co=()=>this.Fo(),this.Mo=()=>this.xo(),this.Oo=[],this.No()}vo(e){this.Oo.push(e)}shutdown(){window.removeEventListener(“online”,this.Co),window.removeEventListener(“offline”,this.Mo)}No(){window.addEventListener(“online”,this.Co),window.addEventListener(“offline”,this.Mo)}Fo(){__PRIVATE_logDebug(gn,”Network connectivity changed: AVAILABLE”);for(const e of this.Oo)e(0)}xo(){__PRIVATE_logDebug(gn,”Network connectivity changed: UNAVAILABLE”);for(const e of this.Oo)e(1)}static C(){return”undefined”!=typeof window&&void 0!==window.addEventListener&&void 0!==window.removeEventListener}}let pn=null;function __PRIVATE_generateUniqueDebugId(){return null===pn?pn=function __PRIVATE_generateInitialUniqueDebugId(){return 268435456+Math.round(2147483648*Math.random())}():pn++,”0x”+pn.toString(16)}const Tn=”RestConnection”,In={BatchGetDocuments:”batchGet”,Commit:”commit”,RunQuery:”runQuery”,RunAggregationQuery:”runAggregationQuery”};class __PRIVATE_RestConnection{get Bo(){return!1}constructor(e){this.databaseInfo=e,this.databaseId=e.databaseId;const i=e.ssl?”https”:”http”,s=encodeURIComponent(this.databaseId.projectId),o=encodeURIComponent(this.databaseId.database);this.Lo=i+”://”+e.host,this.ko=`projects/${s}/databases/${o}`,this.qo=this.databaseId.database===Ft?`project_id=${s}`:`project_id=${s}&database_id=${o}`}Qo(e,i,s,o,_){const h=__PRIVATE_generateUniqueDebugId(),d=this.$o(e,i.toUriEncodedString());__PRIVATE_logDebug(Tn,`Sending RPC ‘${e}’ ${h}:`,d,s);const f={“google-cloud-resource-prefix”:this.ko,”x-goog-request-params”:this.qo};return this.Uo(f,o,_),this.Ko(e,d,f,s).then((i=>(__PRIVATE_logDebug(Tn,`Received RPC ‘${e}’ ${h}: `,i),i)),(i=>{throw __PRIVATE_logWarn(Tn,`RPC ‘${e}’ ${h} failed with error: `,i,”url: “,d,”request:”,s),i}))}Wo(e,i,s,o,_,h){return this.Qo(e,i,s,o,_)}Uo(e,i,s){e[“X-Goog-Api-Client”]=function __PRIVATE_getGoogApiClientValue(){return”gl-js/ fire/”+_e}(),e[“Content-Type”]=”text/plain”,this.databaseInfo.appId&&(e[“X-Firebase-GMPID”]=this.databaseInfo.appId),i&&i.headers.forEach(((i,s)=>e[s]=i)),s&&s.headers.forEach(((i,s)=>e[s]=i))}$o(e,i){const s=In[e];return`${this.Lo}/v1/${i}:${s}`}terminate(){}}class __PRIVATE_StreamBridge{constructor(e){this.Go=e.Go,this.zo=e.zo}jo(e){this.Ho=e}Jo(e){this.Yo=e}Zo(e){this.Xo=e}onMessage(e){this.e_=e}close(){this.zo()}send(e){this.Go(e)}t_(){this.Ho()}n_(){this.Yo()}r_(e){this.Xo(e)}i_(e){this.e_(e)}}const En=”WebChannelConnection”;class __PRIVATE_WebChannelConnection extends __PRIVATE_RestConnection{constructor(e){super(e),this.forceLongPolling=e.forceLongPolling,this.autoDetectLongPolling=e.autoDetectLongPolling,this.useFetchStreams=e.useFetchStreams,this.longPollingOptions=e.longPollingOptions}Ko(e,i,s,o){const _=__PRIVATE_generateUniqueDebugId();return new Promise(((h,d)=>{const f=new ee;f.setWithCredentials(!0),f.listenOnce(ne.COMPLETE,(()=>{try{switch(f.getLastErrorCode()){case re.NO_ERROR:const i=f.getResponseJson();__PRIVATE_logDebug(En,`XHR for RPC ‘${e}’ ${_} received:`,JSON.stringify(i)),h(i);break;case re.TIMEOUT:__PRIVATE_logDebug(En,`RPC ‘${e}’ ${_} timed out`),d(new FirestoreError(de.DEADLINE_EXCEEDED,”Request time out”));break;case re.HTTP_ERROR:const s=f.getStatus();if(__PRIVATE_logDebug(En,`RPC ‘${e}’ ${_} failed with status:`,s,”response text:”,f.getResponseText()),s>0){let e=f.getResponseJson();Array.isArray(e)&&(e=e[0]);const i=null==e?void 0:e.error;if(i&&i.status&&i.message){const e=function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e){const i=e.toLowerCase().replace(/_/g,”-“);return Object.values(de).indexOf(i)>=0?i:de.UNKNOWN}(i.status);d(new FirestoreError(e,i.message))}else d(new FirestoreError(de.UNKNOWN,”Server responded with status “+f.getStatus()))}else d(new FirestoreError(de.UNAVAILABLE,”Connection failed.”));break;default:fail(9055,{s_:e,streamId:_,o_:f.getLastErrorCode(),__:f.getLastError()})}}finally{__PRIVATE_logDebug(En,`RPC ‘${e}’ ${_} completed.`)}}));const g=JSON.stringify(o);__PRIVATE_logDebug(En,`RPC ‘${e}’ ${_} sending request:`,o),f.send(i,”POST”,g,s,15)}))}a_(e,i,s){const o=__PRIVATE_generateUniqueDebugId(),_=[this.Lo,”/”,”google.firestore.v1.Firestore”,”/”,e,”/channel”],h=ae(),d=oe(),f={httpSessionIdParam:”gsessionid”,initMessageHeaders:{},messageUrlParams:{database:`projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`},sendRawJson:!0,supportsCrossDomainXhr:!0,internalChannelParams:{forwardChannelRequestTimeoutMs:6e5},forceLongPolling:this.forceLongPolling,detectBufferingProxy:this.autoDetectLongPolling},g=this.longPollingOptions.timeoutSeconds;void 0!==g&&(f.longPollingTimeout=Math.round(1e3*g)),this.useFetchStreams&&(f.useFetchStreams=!0),this.Uo(f.initMessageHeaders,i,s),f.encodeInitMessageHeaders=!0;const b=_.join(“”);__PRIVATE_logDebug(En,`Creating RPC ‘${e}’ stream ${o}: ${b}`,f);const w=h.createWebChannel(b,f);let O=!1,q=!1;const j=new __PRIVATE_StreamBridge({Go:i=>{q?__PRIVATE_logDebug(En,`Not sending because RPC ‘${e}’ stream ${o} is closed:`,i):(O||(__PRIVATE_logDebug(En,`Opening RPC ‘${e}’ stream ${o} transport.`),w.open(),O=!0),__PRIVATE_logDebug(En,`RPC ‘${e}’ stream ${o} sending:`,i),w.send(i))},zo:()=>w.close()}),__PRIVATE_unguardedEventListen=(e,i,s)=>{e.listen(i,(e=>{try{s(e)}catch(e){setTimeout((()=>{throw e}),0)}}))};return __PRIVATE_unguardedEventListen(w,te.EventType.OPEN,(()=>{q||(__PRIVATE_logDebug(En,`RPC ‘${e}’ stream ${o} transport opened.`),j.t_())})),__PRIVATE_unguardedEventListen(w,te.EventType.CLOSE,(()=>{q||(q=!0,__PRIVATE_logDebug(En,`RPC ‘${e}’ stream ${o} transport closed`),j.r_())})),__PRIVATE_unguardedEventListen(w,te.EventType.ERROR,(i=>{q||(q=!0,__PRIVATE_logWarn(En,`RPC ‘${e}’ stream ${o} transport errored. Name:`,i.name,”Message:”,i.message),j.r_(new FirestoreError(de.UNAVAILABLE,”The operation could not be completed”)))})),__PRIVATE_unguardedEventListen(w,te.EventType.MESSAGE,(i=>{var s;if(!q){const _=i.data[0];__PRIVATE_hardAssert(!!_,16349);const h=_,d=(null==h?void 0:h.error)||(null===(s=h[0])||void 0===s?void 0:s.error);if(d){__PRIVATE_logDebug(En,`RPC ‘${e}’ stream ${o} received error:`,d);const i=d.status;let s=function __PRIVATE_mapCodeFromRpcStatus(e){const i=Gt[e];if(void 0!==i)return __PRIVATE_mapCodeFromRpcCode(i)}(i),_=d.message;void 0===s&&(s=de.INTERNAL,_=”Unknown error status: “+i+” with message “+d.message),q=!0,j.r_(new FirestoreError(s,_)),w.close()}else __PRIVATE_logDebug(En,`RPC ‘${e}’ stream ${o} received:`,_),j.i_(_)}})),__PRIVATE_unguardedEventListen(d,se.STAT_EVENT,(i=>{i.stat===ie.PROXY?__PRIVATE_logDebug(En,`RPC ‘${e}’ stream ${o} detected buffering proxy`):i.stat===ie.NOPROXY&&__PRIVATE_logDebug(En,`RPC ‘${e}’ stream ${o} detected no buffering proxy`)})),setTimeout((()=>{j.n_()}),0),j}}function __PRIVATE_getWindow(){return”undefined”!=typeof window?window:null}function getDocument(){return”undefined”!=typeof document?document:null}function __PRIVATE_newSerializer(e){return new JsonProtoSerializer(e,!0)}class __PRIVATE_ExponentialBackoff{constructor(e,i,s=1e3,o=1.5,_=6e4){this.bi=e,this.timerId=i,this.u_=s,this.c_=o,this.l_=_,this.h_=0,this.P_=null,this.T_=Date.now(),this.reset()}reset(){this.h_=0}I_(){this.h_=this.l_}E_(e){this.cancel();const i=Math.floor(this.h_+this.d_()),s=Math.max(0,Date.now()-this.T_),o=Math.max(0,i-s);o>0&&__PRIVATE_logDebug(“ExponentialBackoff”,`Backing off for ${o} ms (base delay: ${this.h_} ms, delay with jitter: ${i} ms, last attempt: ${s} ms ago)`),this.P_=this.bi.enqueueAfterDelay(this.timerId,o,(()=>(this.T_=Date.now(),e()))),this.h_*=this.c_,this.h_this.l_&&(this.h_=this.l_)}A_(){null!==this.P_&&(this.P_.skipDelay(),this.P_=null)}cancel(){null!==this.P_&&(this.P_.cancel(),this.P_=null)}d_(){return(Math.random()-.5)*this.h_}}const Pn=”PersistentStream”;class __PRIVATE_PersistentStream{constructor(e,i,s,o,_,h,d,f){this.bi=e,this.R_=s,this.V_=o,this.connection=_,this.authCredentialsProvider=h,this.appCheckCredentialsProvider=d,this.listener=f,this.state=0,this.m_=0,this.f_=null,this.g_=null,this.stream=null,this.p_=0,this.y_=new __PRIVATE_ExponentialBackoff(e,i)}w_(){return 1===this.state||5===this.state||this.b_()}b_(){return 2===this.state||3===this.state}start(){this.p_=0,4!==this.state?this.auth():this.S_()}async stop(){this.w_()&&await this.close(0)}D_(){this.state=0,this.y_.reset()}v_(){this.b_()&&null===this.f_&&(this.f_=this.bi.enqueueAfterDelay(this.R_,6e4,(()=>this.C_())))}F_(e){this.M_(),this.stream.send(e)}async C_(){if(this.b_())return this.close(0)}M_(){this.f_&&(this.f_.cancel(),this.f_=null)}x_(){this.g_&&(this.g_.cancel(),this.g_=null)}async close(e,i){this.M_(),this.x_(),this.y_.cancel(),this.m_++,4!==e?this.y_.reset():i&&i.code===de.RESOURCE_EXHAUSTED?(__PRIVATE_logError(i.toString()),__PRIVATE_logError(“Using maximum backoff delay to prevent overloading the backend.”),this.y_.I_()):i&&i.code===de.UNAUTHENTICATED&&3!==this.state&&(this.authCredentialsProvider.invalidateToken(),this.appCheckCredentialsProvider.invalidateToken()),null!==this.stream&&(this.O_(),this.stream.close(),this.stream=null),this.state=e,await this.listener.Zo(i)}O_(){}auth(){this.state=1;const e=this.N_(this.m_),i=this.m_;Promise.all([this.authCredentialsProvider.getToken(),this.appCheckCredentialsProvider.getToken()]).then((([e,s])=>{this.m_===i&&this.B_(e,s)}),(i=>{e((()=>{const e=new FirestoreError(de.UNKNOWN,”Fetching auth token failed: “+i.message);return this.L_(e)}))}))}B_(e,i){const s=this.N_(this.m_);this.stream=this.k_(e,i),this.stream.jo((()=>{s((()=>this.listener.jo()))})),this.stream.Jo((()=>{s((()=>(this.state=2,this.g_=this.bi.enqueueAfterDelay(this.V_,1e4,(()=>(this.b_()&&(this.state=3),Promise.resolve()))),this.listener.Jo())))})),this.stream.Zo((e=>{s((()=>this.L_(e)))})),this.stream.onMessage((e=>{s((()=>1==++this.p_?this.q_(e):this.onNext(e)))}))}S_(){this.state=5,this.y_.E_((async()=>{this.state=0,this.start()}))}L_(e){return __PRIVATE_logDebug(Pn,`close with error: ${e}`),this.stream=null,this.close(4,e)}N_(e){return i=>{this.bi.enqueueAndForget((()=>this.m_===e?i():(__PRIVATE_logDebug(Pn,”stream callback skipped by getCloseGuardedDispatcher.”),Promise.resolve())))}}}class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream{constructor(e,i,s,o,_,h){super(e,”listen_stream_connection_backoff”,”listen_stream_idle”,”health_check_timeout”,i,s,o,h),this.serializer=_}k_(e,i){return this.connection.a_(“Listen”,e,i)}q_(e){return this.onNext(e)}onNext(e){this.y_.reset();const i=function __PRIVATE_fromWatchChange(e,i){let s;if(“targetChange”in i){i.targetChange;const o=function __PRIVATE_fromWatchTargetChangeState(e){return”NO_CHANGE”===e?0:”ADD”===e?1:”REMOVE”===e?2:”CURRENT”===e?3:”RESET”===e?4:fail(39313,{state:e})}(i.targetChange.targetChangeType||”NO_CHANGE”),_=i.targetChange.targetIds||[],h=function __PRIVATE_fromBytes(e,i){return e.useProto3Json?(__PRIVATE_hardAssert(void 0===i||”string”==typeof i,58123),ByteString.fromBase64String(i||””)):(__PRIVATE_hardAssert(void 0===i||i instanceof Buffer||i instanceof Uint8Array,16193),ByteString.fromUint8Array(i||new Uint8Array))}(e,i.targetChange.resumeToken),d=i.targetChange.cause,f=d&&function __PRIVATE_fromRpcStatus(e){const i=void 0===e.code?de.UNKNOWN:__PRIVATE_mapCodeFromRpcCode(e.code);return new FirestoreError(i,e.message||””)}(d);s=new __PRIVATE_WatchTargetChange(o,_,h,f||null)}else if(“documentChange”in i){i.documentChange;const o=i.documentChange;o.document,o.document.name,o.document.updateTime;const _=fromName(e,o.document.name),h=__PRIVATE_fromVersion(o.document.updateTime),d=o.document.createTime?__PRIVATE_fromVersion(o.document.createTime):SnapshotVersion.min(),f=new ObjectValue({mapValue:{fields:o.document.fields}}),g=MutableDocument.newFoundDocument(_,h,d,f),b=o.targetIds||[],w=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange(b,w,g.key,g)}else if(“documentDelete”in i){i.documentDelete;const o=i.documentDelete;o.document;const _=fromName(e,o.document),h=o.readTime?__PRIVATE_fromVersion(o.readTime):SnapshotVersion.min(),d=MutableDocument.newNoDocument(_,h),f=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange([],f,d.key,d)}else if(“documentRemove”in i){i.documentRemove;const o=i.documentRemove;o.document;const _=fromName(e,o.document),h=o.removedTargetIds||[];s=new __PRIVATE_DocumentWatchChange([],h,_,null)}else{if(!(“filter”in i))return fail(11601,{Vt:i});{i.filter;const e=i.filter;e.targetId;const{count:o=0,unchangedNames:_}=e,h=new ExistenceFilter(o,_),d=e.targetId;s=new __PRIVATE_ExistenceFilterChange(d,h)}}return s}(this.serializer,e),s=function __PRIVATE_versionFromListenResponse(e){if(!(“targetChange”in e))return SnapshotVersion.min();const i=e.targetChange;return i.targetIds&&i.targetIds.length?SnapshotVersion.min():i.readTime?__PRIVATE_fromVersion(i.readTime):SnapshotVersion.min()}(e);return this.listener.Q_(i,s)}U_(e){const i={};i.database=__PRIVATE_getEncodedDatabaseId(this.serializer),i.addTarget=function __PRIVATE_toTarget(e,i){let s;const o=i.target;if(s=__PRIVATE_targetIsDocumentTarget(o)?{documents:__PRIVATE_toDocumentsTarget(e,o)}:{query:__PRIVATE_toQueryTarget(e,o).gt},s.targetId=i.targetId,i.resumeToken.approximateByteSize()>0){s.resumeToken=__PRIVATE_toBytes(e,i.resumeToken);const o=__PRIVATE_toInt32Proto(e,i.expectedCount);null!==o&&(s.expectedCount=o)}else if(i.snapshotVersion.compareTo(SnapshotVersion.min())>0){s.readTime=toTimestamp(e,i.snapshotVersion.toTimestamp());const o=__PRIVATE_toInt32Proto(e,i.expectedCount);null!==o&&(s.expectedCount=o)}return s}(this.serializer,e);const s=function __PRIVATE_toListenRequestLabels(e,i){const s=function __PRIVATE_toLabel(e){switch(e){case”TargetPurposeListen”:return null;case”TargetPurposeExistenceFilterMismatch”:return”existence-filter-mismatch”;case”TargetPurposeExistenceFilterMismatchBloom”:return”existence-filter-mismatch-bloom”;case”TargetPurposeLimboResolution”:return”limbo-document”;default:return fail(28987,{purpose:e})}}(i.purpose);return null==s?null:{“goog-listen-tags”:s}}(this.serializer,e);s&&(i.labels=s),this.F_(i)}K_(e){const i={};i.database=__PRIVATE_getEncodedDatabaseId(this.serializer),i.removeTarget=e,this.F_(i)}}class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream{constructor(e,i,s,o,_,h){super(e,”write_stream_connection_backoff”,”write_stream_idle”,”health_check_timeout”,i,s,o,h),this.serializer=_}get W_(){return this.p_>0}start(){this.lastStreamToken=void 0,super.start()}O_(){this.W_&&this.G_([])}k_(e,i){return this.connection.a_(“Write”,e,i)}q_(e){return __PRIVATE_hardAssert(!!e.streamToken,31322),this.lastStreamToken=e.streamToken,__PRIVATE_hardAssert(!e.writeResults||0===e.writeResults.length,55816),this.listener.z_()}onNext(e){__PRIVATE_hardAssert(!!e.streamToken,12678),this.lastStreamToken=e.streamToken,this.y_.reset();const i=function __PRIVATE_fromWriteResults(e,i){return e&&e.length>0?(__PRIVATE_hardAssert(void 0!==i,14353),e.map((e=>function __PRIVATE_fromWriteResult(e,i){let s=e.updateTime?__PRIVATE_fromVersion(e.updateTime):__PRIVATE_fromVersion(i);return s.isEqual(SnapshotVersion.min())&&(s=__PRIVATE_fromVersion(i)),new MutationResult(s,e.transformResults||[])}(e,i)))):[]}(e.writeResults,e.commitTime),s=__PRIVATE_fromVersion(e.commitTime);return this.listener.j_(s,i)}H_(){const e={};e.database=__PRIVATE_getEncodedDatabaseId(this.serializer),this.F_(e)}G_(e){const i={streamToken:this.lastStreamToken,writes:e.map((e=>toMutation(this.serializer,e)))};this.F_(i)}}class Datastore{}class __PRIVATE_DatastoreImpl extends Datastore{constructor(e,i,s,o){super(),this.authCredentials=e,this.appCheckCredentials=i,this.connection=s,this.serializer=o,this.J_=!1}Y_(){if(this.J_)throw new FirestoreError(de.FAILED_PRECONDITION,”The client has already been terminated.”)}Qo(e,i,s,o){return this.Y_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([_,h])=>this.connection.Qo(e,__PRIVATE_toResourcePath(i,s),o,_,h))).catch((e=>{throw”FirebaseError”===e.name?(e.code===de.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(de.UNKNOWN,e.toString())}))}Wo(e,i,s,o,_){return this.Y_(),Promise.all([this.authCredentials.getToken(),this.appCheckCredentials.getToken()]).then((([h,d])=>this.connection.Wo(e,__PRIVATE_toResourcePath(i,s),o,h,d,_))).catch((e=>{throw”FirebaseError”===e.name?(e.code===de.UNAUTHENTICATED&&(this.authCredentials.invalidateToken(),this.appCheckCredentials.invalidateToken()),e):new FirestoreError(de.UNKNOWN,e.toString())}))}terminate(){this.J_=!0,this.connection.terminate()}}class __PRIVATE_OnlineStateTracker{constructor(e,i){this.asyncQueue=e,this.onlineStateHandler=i,this.state=”Unknown”,this.Z_=0,this.X_=null,this.ea=!0}ta(){0===this.Z_&&(this.na(“Unknown”),this.X_=this.asyncQueue.enqueueAfterDelay(“online_state_timeout”,1e4,(()=>(this.X_=null,this.ra(“Backend didn’t respond within 10 seconds.”),this.na(“Offline”),Promise.resolve()))))}ia(e){“Online”===this.state?this.na(“Unknown”):(this.Z_++,this.Z_>=1&&(this.sa(),this.ra(`Connection failed 1 times. Most recent error: ${e.toString()}`),this.na(“Offline”)))}set(e){this.sa(),this.Z_=0,”Online”===e&&(this.ea=!1),this.na(e)}na(e){e!==this.state&&(this.state=e,this.onlineStateHandler(e))}ra(e){const i=`Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;this.ea?(__PRIVATE_logError(i),this.ea=!1):__PRIVATE_logDebug(“OnlineStateTracker”,i)}sa(){null!==this.X_&&(this.X_.cancel(),this.X_=null)}}const An=”RemoteStore”;class __PRIVATE_RemoteStoreImpl{constructor(e,i,s,o,_){this.localStore=e,this.datastore=i,this.asyncQueue=s,this.remoteSyncer={},this.oa=[],this._a=new Map,this.aa=new Set,this.ua=[],this.ca=_,this.ca.vo((e=>{s.enqueueAndForget((async()=>{__PRIVATE_canUseNetwork(this)&&(__PRIVATE_logDebug(An,”Restarting streams for network reachability change.”),await async function __PRIVATE_restartNetwork(e){const i=__PRIVATE_debugCast(e);i.aa.add(4),await __PRIVATE_disableNetworkInternal(i),i.la.set(“Unknown”),i.aa.delete(4),await __PRIVATE_enableNetworkInternal(i)}(this))}))})),this.la=new __PRIVATE_OnlineStateTracker(s,o)}}async function __PRIVATE_enableNetworkInternal(e){if(__PRIVATE_canUseNetwork(e))for(const i of e.ua)await i(!0)}async function __PRIVATE_disableNetworkInternal(e){for(const i of e.ua)await i(!1)}function __PRIVATE_remoteStoreListen(e,i){const s=__PRIVATE_debugCast(e);s._a.has(i.targetId)||(s._a.set(i.targetId,i),__PRIVATE_shouldStartWatchStream(s)?__PRIVATE_startWatchStream(s):__PRIVATE_ensureWatchStream(s).b_()&&__PRIVATE_sendWatchRequest(s,i))}function __PRIVATE_remoteStoreUnlisten(e,i){const s=__PRIVATE_debugCast(e),o=__PRIVATE_ensureWatchStream(s);s._a.delete(i),o.b_()&&__PRIVATE_sendUnwatchRequest(s,i),0===s._a.size&&(o.b_()?o.v_():__PRIVATE_canUseNetwork(s)&&s.la.set(“Unknown”))}function __PRIVATE_sendWatchRequest(e,i){if(e.ha.Ke(i.targetId),i.resumeToken.approximateByteSize()>0||i.snapshotVersion.compareTo(SnapshotVersion.min())>0){const s=e.remoteSyncer.getRemoteKeysForTarget(i.targetId).size;i=i.withExpectedCount(s)}__PRIVATE_ensureWatchStream(e).U_(i)}function __PRIVATE_sendUnwatchRequest(e,i){e.ha.Ke(i),__PRIVATE_ensureWatchStream(e).K_(i)}function __PRIVATE_startWatchStream(e){e.ha=new __PRIVATE_WatchChangeAggregator({getRemoteKeysForTarget:i=>e.remoteSyncer.getRemoteKeysForTarget(i),Rt:i=>e._a.get(i)||null,Pt:()=>e.datastore.serializer.databaseId}),__PRIVATE_ensureWatchStream(e).start(),e.la.ta()}function __PRIVATE_shouldStartWatchStream(e){return __PRIVATE_canUseNetwork(e)&&!__PRIVATE_ensureWatchStream(e).w_()&&e._a.size>0}function __PRIVATE_canUseNetwork(e){return 0===__PRIVATE_debugCast(e).aa.size}function __PRIVATE_cleanUpWatchStreamState(e){e.ha=void 0}async function __PRIVATE_onWatchStreamConnected(e){e.la.set(“Online”)}async function __PRIVATE_onWatchStreamOpen(e){e._a.forEach(((i,s)=>{__PRIVATE_sendWatchRequest(e,i)}))}async function __PRIVATE_onWatchStreamClose(e,i){__PRIVATE_cleanUpWatchStreamState(e),__PRIVATE_shouldStartWatchStream(e)?(e.la.ia(i),__PRIVATE_startWatchStream(e)):e.la.set(“Unknown”)}async function __PRIVATE_onWatchStreamChange(e,i,s){if(e.la.set(“Online”),i instanceof __PRIVATE_WatchTargetChange&&2===i.state&&i.cause)try{await async function __PRIVATE_handleTargetError(e,i){const s=i.cause;for(const o of i.targetIds)e._a.has(o)&&(await e.remoteSyncer.rejectListen(o,s),e._a.delete(o),e.ha.removeTarget(o))}(e,i)}catch(s){__PRIVATE_logDebug(An,”Failed to remove targets %s: %s “,i.targetIds.join(“,”),s),await __PRIVATE_disableNetworkUntilRecovery(e,s)}else if(i instanceof __PRIVATE_DocumentWatchChange?e.ha.Xe(i):i instanceof __PRIVATE_ExistenceFilterChange?e.ha.ot(i):e.ha.nt(i),!s.isEqual(SnapshotVersion.min()))try{const i=await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore);s.compareTo(i)>=0&&await function __PRIVATE_raiseWatchSnapshot(e,i){const s=e.ha.It(i);return s.targetChanges.forEach(((s,o)=>{if(s.resumeToken.approximateByteSize()>0){const _=e._a.get(o);_&&e._a.set(o,_.withResumeToken(s.resumeToken,i))}})),s.targetMismatches.forEach(((i,s)=>{const o=e._a.get(i);if(!o)return;e._a.set(i,o.withResumeToken(ByteString.EMPTY_BYTE_STRING,o.snapshotVersion)),__PRIVATE_sendUnwatchRequest(e,i);const _=new TargetData(o.target,i,s,o.sequenceNumber);__PRIVATE_sendWatchRequest(e,_)})),e.remoteSyncer.applyRemoteEvent(s)}(e,s)}catch(i){__PRIVATE_logDebug(An,”Failed to raise snapshot:”,i),await __PRIVATE_disableNetworkUntilRecovery(e,i)}}async function __PRIVATE_disableNetworkUntilRecovery(e,i,s){if(!__PRIVATE_isIndexedDbTransactionError(i))throw i;e.aa.add(1),await __PRIVATE_disableNetworkInternal(e),e.la.set(“Offline”),s||(s=()=>__PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)),e.asyncQueue.enqueueRetryable((async()=>{__PRIVATE_logDebug(An,”Retrying IndexedDB access”),await s(),e.aa.delete(1),await __PRIVATE_enableNetworkInternal(e)}))}function __PRIVATE_executeWithRecovery(e,i){return i().catch((s=>__PRIVATE_disableNetworkUntilRecovery(e,s,i)))}async function __PRIVATE_fillWritePipeline(e){const i=__PRIVATE_debugCast(e),s=__PRIVATE_ensureWriteStream(i);let o=i.oa.length>0?i.oa[i.oa.length-1].batchId:Re;for(;__PRIVATE_canAddToWritePipeline(i);)try{const e=await __PRIVATE_localStoreGetNextMutationBatch(i.localStore,o);if(null===e){0===i.oa.length&&s.v_();break}o=e.batchId,__PRIVATE_addToWritePipeline(i,e)}catch(e){await __PRIVATE_disableNetworkUntilRecovery(i,e)}__PRIVATE_shouldStartWriteStream(i)&&__PRIVATE_startWriteStream(i)}function __PRIVATE_canAddToWritePipeline(e){return __PRIVATE_canUseNetwork(e)&&e.oa.length<10}function __PRIVATE_addToWritePipeline(e,i){e.oa.push(i);const s=__PRIVATE_ensureWriteStream(e);s.b_()&&s.W_&&s.G_(i.mutations)}function __PRIVATE_shouldStartWriteStream(e){return __PRIVATE_canUseNetwork(e)&&!__PRIVATE_ensureWriteStream(e).w_()&&e.oa.length>0}function __PRIVATE_startWriteStream(e){__PRIVATE_ensureWriteStream(e).start()}async function __PRIVATE_onWriteStreamOpen(e){__PRIVATE_ensureWriteStream(e).H_()}async function __PRIVATE_onWriteHandshakeComplete(e){const i=__PRIVATE_ensureWriteStream(e);for(const s of e.oa)i.G_(s.mutations)}async function __PRIVATE_onMutationResult(e,i,s){const o=e.oa.shift(),_=MutationBatchResult.from(o,i,s);await __PRIVATE_executeWithRecovery(e,(()=>e.remoteSyncer.applySuccessfulWrite(_))),await __PRIVATE_fillWritePipeline(e)}async function __PRIVATE_onWriteStreamClose(e,i){i&&__PRIVATE_ensureWriteStream(e).W_&&await async function __PRIVATE_handleWriteError(e,i){if(function __PRIVATE_isPermanentWriteError(e){return __PRIVATE_isPermanentError(e)&&e!==de.ABORTED}(i.code)){const s=e.oa.shift();__PRIVATE_ensureWriteStream(e).D_(),await __PRIVATE_executeWithRecovery(e,(()=>e.remoteSyncer.rejectFailedWrite(s.batchId,i))),await __PRIVATE_fillWritePipeline(e)}}(e,i),__PRIVATE_shouldStartWriteStream(e)&&__PRIVATE_startWriteStream(e)}async function __PRIVATE_remoteStoreHandleCredentialChange(e,i){const s=__PRIVATE_debugCast(e);s.asyncQueue.verifyOperationInProgress(),__PRIVATE_logDebug(An,”RemoteStore received new credentials”);const o=__PRIVATE_canUseNetwork(s);s.aa.add(3),await __PRIVATE_disableNetworkInternal(s),o&&s.la.set(“Unknown”),await s.remoteSyncer.handleCredentialChange(i),s.aa.delete(3),await __PRIVATE_enableNetworkInternal(s)}async function __PRIVATE_remoteStoreApplyPrimaryState(e,i){const s=__PRIVATE_debugCast(e);i?(s.aa.delete(2),await __PRIVATE_enableNetworkInternal(s)):i||(s.aa.add(2),await __PRIVATE_disableNetworkInternal(s),s.la.set(“Unknown”))}function __PRIVATE_ensureWatchStream(e){return e.Pa||(e.Pa=function __PRIVATE_newPersistentWatchStream(e,i,s){const o=__PRIVATE_debugCast(e);return o.Y_(),new __PRIVATE_PersistentListenStream(i,o.connection,o.authCredentials,o.appCheckCredentials,o.serializer,s)}(e.datastore,e.asyncQueue,{jo:__PRIVATE_onWatchStreamConnected.bind(null,e),Jo:__PRIVATE_onWatchStreamOpen.bind(null,e),Zo:__PRIVATE_onWatchStreamClose.bind(null,e),Q_:__PRIVATE_onWatchStreamChange.bind(null,e)}),e.ua.push((async i=>{i?(e.Pa.D_(),__PRIVATE_shouldStartWatchStream(e)?__PRIVATE_startWatchStream(e):e.la.set(“Unknown”)):(await e.Pa.stop(),__PRIVATE_cleanUpWatchStreamState(e))}))),e.Pa}function __PRIVATE_ensureWriteStream(e){return e.Ta||(e.Ta=function __PRIVATE_newPersistentWriteStream(e,i,s){const o=__PRIVATE_debugCast(e);return o.Y_(),new __PRIVATE_PersistentWriteStream(i,o.connection,o.authCredentials,o.appCheckCredentials,o.serializer,s)}(e.datastore,e.asyncQueue,{jo:()=>Promise.resolve(),Jo:__PRIVATE_onWriteStreamOpen.bind(null,e),Zo:__PRIVATE_onWriteStreamClose.bind(null,e),z_:__PRIVATE_onWriteHandshakeComplete.bind(null,e),j_:__PRIVATE_onMutationResult.bind(null,e)}),e.ua.push((async i=>{i?(e.Ta.D_(),await __PRIVATE_fillWritePipeline(e)):(await e.Ta.stop(),e.oa.length>0&&(__PRIVATE_logDebug(An,`Stopping write stream with ${e.oa.length} pending writes`),e.oa=[]))}))),e.Ta}class DelayedOperation{constructor(e,i,s,o,_){this.asyncQueue=e,this.timerId=i,this.targetTimeMs=s,this.op=o,this.removalCallback=_,this.deferred=new __PRIVATE_Deferred,this.then=this.deferred.promise.then.bind(this.deferred.promise),this.deferred.promise.catch((e=>{}))}get promise(){return this.deferred.promise}static createAndSchedule(e,i,s,o,_){const h=Date.now()+s,d=new DelayedOperation(e,i,h,o,_);return d.start(s),d}start(e){this.timerHandle=setTimeout((()=>this.handleDelayElapsed()),e)}skipDelay(){return this.handleDelayElapsed()}cancel(e){null!==this.timerHandle&&(this.clearTimeout(),this.deferred.reject(new FirestoreError(de.CANCELLED,”Operation cancelled”+(e?”: “+e:””))))}handleDelayElapsed(){this.asyncQueue.enqueueAndForget((()=>null!==this.timerHandle?(this.clearTimeout(),this.op().then((e=>this.deferred.resolve(e)))):Promise.resolve()))}clearTimeout(){null!==this.timerHandle&&(this.removalCallback(this),clearTimeout(this.timerHandle),this.timerHandle=null)}}function __PRIVATE_wrapInUserErrorIfRecoverable(e,i){if(__PRIVATE_logError(“AsyncQueue”,`${i}: ${e}`),__PRIVATE_isIndexedDbTransactionError(e))return new FirestoreError(de.UNAVAILABLE,`${i}: ${e}`);throw e}class DocumentSet{static emptySet(e){return new DocumentSet(e.comparator)}constructor(e){this.comparator=e?(i,s)=>e(i,s)||DocumentKey.comparator(i.key,s.key):(e,i)=>DocumentKey.comparator(e.key,i.key),this.keyedMap=documentMap(),this.sortedSet=new SortedMap(this.comparator)}has(e){return null!=this.keyedMap.get(e)}get(e){return this.keyedMap.get(e)}first(){return this.sortedSet.minKey()}last(){return this.sortedSet.maxKey()}isEmpty(){return this.sortedSet.isEmpty()}indexOf(e){const i=this.keyedMap.get(e);return i?this.sortedSet.indexOf(i):-1}get size(){return this.sortedSet.size}forEach(e){this.sortedSet.inorderTraversal(((i,s)=>(e(i),!1)))}add(e){const i=this.delete(e.key);return i.copy(i.keyedMap.insert(e.key,e),i.sortedSet.insert(e,null))}delete(e){const i=this.get(e);return i?this.copy(this.keyedMap.remove(e),this.sortedSet.remove(i)):this}isEqual(e){if(!(e instanceof DocumentSet))return!1;if(this.size!==e.size)return!1;const i=this.sortedSet.getIterator(),s=e.sortedSet.getIterator();for(;i.hasNext();){const e=i.getNext().key,o=s.getNext().key;if(!e.isEqual(o))return!1}return!0}toString(){const e=[];return this.forEach((i=>{e.push(i.toString())})),0===e.length?”DocumentSet ()”:”DocumentSet (\n “+e.join(” \n”)+”\n)”}copy(e,i){const s=new DocumentSet;return s.comparator=this.comparator,s.keyedMap=e,s.sortedSet=i,s}}class __PRIVATE_DocumentChangeSet{constructor(){this.Ia=new SortedMap(DocumentKey.comparator)}track(e){const i=e.doc.key,s=this.Ia.get(i);s?0!==e.type&&3===s.type?this.Ia=this.Ia.insert(i,e):3===e.type&&1!==s.type?this.Ia=this.Ia.insert(i,{type:s.type,doc:e.doc}):2===e.type&&2===s.type?this.Ia=this.Ia.insert(i,{type:2,doc:e.doc}):2===e.type&&0===s.type?this.Ia=this.Ia.insert(i,{type:0,doc:e.doc}):1===e.type&&0===s.type?this.Ia=this.Ia.remove(i):1===e.type&&2===s.type?this.Ia=this.Ia.insert(i,{type:1,doc:s.doc}):0===e.type&&1===s.type?this.Ia=this.Ia.insert(i,{type:2,doc:e.doc}):fail(63341,{Vt:e,Ea:s}):this.Ia=this.Ia.insert(i,e)}da(){const e=[];return this.Ia.inorderTraversal(((i,s)=>{e.push(s)})),e}}class ViewSnapshot{constructor(e,i,s,o,_,h,d,f,g){this.query=e,this.docs=i,this.oldDocs=s,this.docChanges=o,this.mutatedKeys=_,this.fromCache=h,this.syncStateChanged=d,this.excludesMetadataChanges=f,this.hasCachedResults=g}static fromInitialDocuments(e,i,s,o,_){const h=[];return i.forEach((e=>{h.push({type:0,doc:e})})),new ViewSnapshot(e,i,DocumentSet.emptySet(i),h,s,o,!0,!1,_)}get hasPendingWrites(){return!this.mutatedKeys.isEmpty()}isEqual(e){if(!(this.fromCache===e.fromCache&&this.hasCachedResults===e.hasCachedResults&&this.syncStateChanged===e.syncStateChanged&&this.mutatedKeys.isEqual(e.mutatedKeys)&&__PRIVATE_queryEquals(this.query,e.query)&&this.docs.isEqual(e.docs)&&this.oldDocs.isEqual(e.oldDocs)))return!1;const i=this.docChanges,s=e.docChanges;if(i.length!==s.length)return!1;for(let e=0;ee.ma()))}}class __PRIVATE_EventManagerImpl{constructor(){this.queries=__PRIVATE_newQueriesObjectMap(),this.onlineState=”Unknown”,this.fa=new Set}terminate(){!function __PRIVATE_errorAllTargets(e,i){const s=__PRIVATE_debugCast(e),o=s.queries;s.queries=__PRIVATE_newQueriesObjectMap(),o.forEach(((e,s)=>{for(const e of s.Ra)e.onError(i)}))}(this,new FirestoreError(de.ABORTED,”Firestore shutting down”))}}function __PRIVATE_newQueriesObjectMap(){return new ObjectMap((e=>__PRIVATE_canonifyQuery(e)),__PRIVATE_queryEquals)}async function __PRIVATE_eventManagerListen(e,i){const s=__PRIVATE_debugCast(e);let o=3;const _=i.query;let h=s.queries.get(_);h?!h.Va()&&i.ma()&&(o=2):(h=new __PRIVATE_QueryListenersInfo,o=i.ma()?0:1);try{switch(o){case 0:h.Aa=await s.onListen(_,!0);break;case 1:h.Aa=await s.onListen(_,!1);break;case 2:await s.onFirstRemoteStoreListen(_)}}catch(e){const s=__PRIVATE_wrapInUserErrorIfRecoverable(e,`Initialization of query ‘${__PRIVATE_stringifyQuery(i.query)}’ failed`);return void i.onError(s)}s.queries.set(_,h),h.Ra.push(i),i.ga(s.onlineState),h.Aa&&i.pa(h.Aa)&&__PRIVATE_raiseSnapshotsInSyncEvent(s)}async function __PRIVATE_eventManagerUnlisten(e,i){const s=__PRIVATE_debugCast(e),o=i.query;let _=3;const h=s.queries.get(o);if(h){const e=h.Ra.indexOf(i);e>=0&&(h.Ra.splice(e,1),0===h.Ra.length?_=i.ma()?0:1:!h.Va()&&i.ma()&&(_=2))}switch(_){case 0:return s.queries.delete(o),s.onUnlisten(o,!0);case 1:return s.queries.delete(o),s.onUnlisten(o,!1);case 2:return s.onLastRemoteStoreUnlisten(o);default:return}}function __PRIVATE_eventManagerOnWatchChange(e,i){const s=__PRIVATE_debugCast(e);let o=!1;for(const e of i){const i=e.query,_=s.queries.get(i);if(_){for(const i of _.Ra)i.pa(e)&&(o=!0);_.Aa=e}}o&&__PRIVATE_raiseSnapshotsInSyncEvent(s)}function __PRIVATE_eventManagerOnWatchError(e,i,s){const o=__PRIVATE_debugCast(e),_=o.queries.get(i);if(_)for(const e of _.Ra)e.onError(s);o.queries.delete(i)}function __PRIVATE_raiseSnapshotsInSyncEvent(e){e.fa.forEach((e=>{e.next()}))}var Rn,yn;(yn=Rn||(Rn={})).ya=”default”,yn.Cache=”cache”;class __PRIVATE_QueryListener{constructor(e,i,s){this.query=e,this.wa=i,this.ba=!1,this.Sa=null,this.onlineState=”Unknown”,this.options=s||{}}pa(e){if(!this.options.includeMetadataChanges){const i=[];for(const s of e.docChanges)3!==s.type&&i.push(s);e=new ViewSnapshot(e.query,e.docs,e.oldDocs,i,e.mutatedKeys,e.fromCache,e.syncStateChanged,!0,e.hasCachedResults)}let i=!1;return this.ba?this.Da(e)&&(this.wa.next(e),i=!0):this.va(e,this.onlineState)&&(this.Ca(e),i=!0),this.Sa=e,i}onError(e){this.wa.error(e)}ga(e){this.onlineState=e;let i=!1;return this.Sa&&!this.ba&&this.va(this.Sa,e)&&(this.Ca(this.Sa),i=!0),i}va(e,i){if(!e.fromCache)return!0;if(!this.ma())return!0;const s=”Offline”!==i;return(!this.options.Fa||!s)&&(!e.docs.isEmpty()||e.hasCachedResults||”Offline”===i)}Da(e){if(e.docChanges.length>0)return!0;const i=this.Sa&&this.Sa.hasPendingWrites!==e.hasPendingWrites;return!(!e.syncStateChanged&&!i)&&!0===this.options.includeMetadataChanges}Ca(e){e=ViewSnapshot.fromInitialDocuments(e.query,e.docs,e.mutatedKeys,e.fromCache,e.hasCachedResults),this.ba=!0,this.wa.next(e)}ma(){return this.options.source!==Rn.Cache}}class __PRIVATE_SizedBundleElement{constructor(e,i){this.Ma=e,this.byteLength=i}xa(){return”metadata”in this.Ma}}class __PRIVATE_BundleConverterImpl{constructor(e){this.serializer=e}Bs(e){return fromName(this.serializer,e)}Ls(e){return e.metadata.exists?__PRIVATE_fromDocument(this.serializer,e.document,!1):MutableDocument.newNoDocument(this.Bs(e.metadata.name),this.ks(e.metadata.readTime))}ks(e){return __PRIVATE_fromVersion(e)}}class __PRIVATE_BundleLoader{constructor(e,i,s){this.Oa=e,this.localStore=i,this.serializer=s,this.queries=[],this.documents=[],this.collectionGroups=new Set,this.progress=__PRIVATE_bundleInitialProgress(e)}Na(e){this.progress.bytesLoaded+=e.byteLength;let i=this.progress.documentsLoaded;if(e.Ma.namedQuery)this.queries.push(e.Ma.namedQuery);else if(e.Ma.documentMetadata){this.documents.push({metadata:e.Ma.documentMetadata}),e.Ma.documentMetadata.exists||++i;const s=ResourcePath.fromString(e.Ma.documentMetadata.name);this.collectionGroups.add(s.get(s.length-2))}else e.Ma.document&&(this.documents[this.documents.length-1].document=e.Ma.document,++i);return i!==this.progress.documentsLoaded?(this.progress.documentsLoaded=i,Object.assign({},this.progress)):null}Ba(e){const i=new Map,s=new __PRIVATE_BundleConverterImpl(this.serializer);for(const o of e)if(o.metadata.queries){const e=s.Bs(o.metadata.name);for(const s of o.metadata.queries){const o=(i.get(s)||__PRIVATE_documentKeySet()).add(e);i.set(s,o)}}return i}async complete(){const e=await async function __PRIVATE_localStoreApplyBundledDocuments(e,i,s,o){const _=__PRIVATE_debugCast(e);let h=__PRIVATE_documentKeySet(),d=__PRIVATE_mutableDocumentMap();for(const e of s){const s=i.Bs(e.metadata.name);e.document&&(h=h.add(s));const o=i.Ls(e);o.setReadTime(i.ks(e.metadata.readTime)),d=d.insert(s,o)}const f=_.Cs.newChangeBuffer({trackRemovals:!0}),g=await __PRIVATE_localStoreAllocateTarget(_,function __PRIVATE_umbrellaTarget(e){return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`)))}(o));return _.persistence.runTransaction(“Apply bundle documents”,”readwrite”,(e=>__PRIVATE_populateDocumentChangeBuffer(e,f,d).next((i=>(f.apply(e),i))).next((i=>_.ai.removeMatchingKeysForTargetId(e,g.targetId).next((()=>_.ai.addMatchingKeys(e,h,g.targetId))).next((()=>_.localDocuments.getLocalViewOfDocuments(e,i.xs,i.Os))).next((()=>i.xs))))))}(this.localStore,new __PRIVATE_BundleConverterImpl(this.serializer),this.documents,this.Oa.id),i=this.Ba(this.documents);for(const e of this.queries)await __PRIVATE_localStoreSaveNamedQuery(this.localStore,e,i.get(e.name));return this.progress.taskState=”Success”,{progress:this.progress,La:this.collectionGroups,ka:e}}}function __PRIVATE_bundleInitialProgress(e){return{taskState:”Running”,documentsLoaded:0,bytesLoaded:0,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}class __PRIVATE_AddedLimboDocument{constructor(e){this.key=e}}class __PRIVATE_RemovedLimboDocument{constructor(e){this.key=e}}class __PRIVATE_View{constructor(e,i){this.query=e,this.qa=i,this.Qa=null,this.hasCachedResults=!1,this.current=!1,this.$a=__PRIVATE_documentKeySet(),this.mutatedKeys=__PRIVATE_documentKeySet(),this.Ua=__PRIVATE_newQueryComparator(e),this.Ka=new DocumentSet(this.Ua)}get Wa(){return this.qa}Ga(e,i){const s=i?i.za:new __PRIVATE_DocumentChangeSet,o=i?i.Ka:this.Ka;let _=i?i.mutatedKeys:this.mutatedKeys,h=o,d=!1;const f=”F”===this.query.limitType&&o.size===this.query.limit?o.last():null,g=”L”===this.query.limitType&&o.size===this.query.limit?o.first():null;if(e.inorderTraversal(((e,i)=>{const b=o.get(e),w=__PRIVATE_queryMatches(this.query,i)?i:null,O=!!b&&this.mutatedKeys.has(b.key),q=!!w&&(w.hasLocalMutations||this.mutatedKeys.has(w.key)&&w.hasCommittedMutations);let j=!1;b&&w?b.data.isEqual(w.data)?O!==q&&(s.track({type:3,doc:w}),j=!0):this.ja(b,w)||(s.track({type:2,doc:w}),j=!0,(f&&this.Ua(w,f)>0||g&&this.Ua(w,g)<0)&&(d=!0)):!b&&w?(s.track({type:0,doc:w}),j=!0):b&&!w&&(s.track({type:1,doc:b}),j=!0,(f||g)&&(d=!0)),j&&(w?(h=h.add(w),_=q?_.add(e):_.delete(e)):(h=h.delete(e),_=_.delete(e)))})),null!==this.query.limit)for(;h.size>this.query.limit;){const e=”F”===this.query.limitType?h.last():h.first();h=h.delete(e.key),_=_.delete(e.key),s.track({type:1,doc:e})}return{Ka:h,za:s,ys:d,mutatedKeys:_}}ja(e,i){return e.hasLocalMutations&&i.hasCommittedMutations&&!i.hasLocalMutations}applyChanges(e,i,s,o){const _=this.Ka;this.Ka=e.Ka,this.mutatedKeys=e.mutatedKeys;const h=e.za.da();h.sort(((e,i)=>function __PRIVATE_compareChangeType(e,i){const order=e=>{switch(e){case 0:return 1;case 2:case 3:return 2;case 1:return 0;default:return fail(20277,{Vt:e})}};return order(e)-order(i)}(e.type,i.type)||this.Ua(e.doc,i.doc))),this.Ha(s),o=null!=o&&o;const d=i&&!o?this.Ja():[],f=0===this.$a.size&&this.current&&!o?1:0,g=f!==this.Qa;return this.Qa=f,0!==h.length||g?{snapshot:new ViewSnapshot(this.query,e.Ka,_,h,e.mutatedKeys,0===f,g,!1,!!s&&s.resumeToken.approximateByteSize()>0),Ya:d}:{Ya:d}}ga(e){return this.current&&”Offline”===e?(this.current=!1,this.applyChanges({Ka:this.Ka,za:new __PRIVATE_DocumentChangeSet,mutatedKeys:this.mutatedKeys,ys:!1},!1)):{Ya:[]}}Za(e){return!this.qa.has(e)&&!!this.Ka.has(e)&&!this.Ka.get(e).hasLocalMutations}Ha(e){e&&(e.addedDocuments.forEach((e=>this.qa=this.qa.add(e))),e.modifiedDocuments.forEach((e=>{})),e.removedDocuments.forEach((e=>this.qa=this.qa.delete(e))),this.current=e.current)}Ja(){if(!this.current)return[];const e=this.$a;this.$a=__PRIVATE_documentKeySet(),this.Ka.forEach((e=>{this.Za(e.key)&&(this.$a=this.$a.add(e.key))}));const i=[];return e.forEach((e=>{this.$a.has(e)||i.push(new __PRIVATE_RemovedLimboDocument(e))})),this.$a.forEach((s=>{e.has(s)||i.push(new __PRIVATE_AddedLimboDocument(s))})),i}Xa(e){this.qa=e.Ns,this.$a=__PRIVATE_documentKeySet();const i=this.Ga(e.documents);return this.applyChanges(i,!0)}eu(){return ViewSnapshot.fromInitialDocuments(this.query,this.Ka,this.mutatedKeys,0===this.Qa,this.hasCachedResults)}}const Vn=”SyncEngine”;class __PRIVATE_QueryView{constructor(e,i,s){this.query=e,this.targetId=i,this.view=s}}class LimboResolution{constructor(e){this.key=e,this.tu=!1}}class __PRIVATE_SyncEngineImpl{constructor(e,i,s,o,_,h){this.localStore=e,this.remoteStore=i,this.eventManager=s,this.sharedClientState=o,this.currentUser=_,this.maxConcurrentLimboResolutions=h,this.nu={},this.ru=new ObjectMap((e=>__PRIVATE_canonifyQuery(e)),__PRIVATE_queryEquals),this.iu=new Map,this.su=new Set,this.ou=new SortedMap(DocumentKey.comparator),this._u=new Map,this.au=new __PRIVATE_ReferenceSet,this.uu={},this.cu=new Map,this.lu=__PRIVATE_TargetIdGenerator.ir(),this.onlineState=”Unknown”,this.hu=void 0}get isPrimaryClient(){return!0===this.hu}}async function __PRIVATE_syncEngineListen(e,i,s=!0){const o=__PRIVATE_ensureWatchCallbacks(e);let _;const h=o.ru.get(i);return h?(o.sharedClientState.addLocalQueryTarget(h.targetId),_=h.view.eu()):_=await __PRIVATE_allocateTargetAndMaybeListen(o,i,s,!0),_}async function __PRIVATE_triggerRemoteStoreListen(e,i){const s=__PRIVATE_ensureWatchCallbacks(e);await __PRIVATE_allocateTargetAndMaybeListen(s,i,!0,!1)}async function __PRIVATE_allocateTargetAndMaybeListen(e,i,s,o){const _=await __PRIVATE_localStoreAllocateTarget(e.localStore,__PRIVATE_queryToTarget(i)),h=_.targetId,d=e.sharedClientState.addLocalQueryTarget(h,s);let f;return o&&(f=await __PRIVATE_initializeViewAndComputeSnapshot(e,i,h,”current”===d,_.resumeToken)),e.isPrimaryClient&&s&&__PRIVATE_remoteStoreListen(e.remoteStore,_),f}async function __PRIVATE_initializeViewAndComputeSnapshot(e,i,s,o,_){e.Pu=(i,s,o)=>async function __PRIVATE_applyDocChanges(e,i,s,o){let _=i.view.Ga(s);_.ys&&(_=await __PRIVATE_localStoreExecuteQuery(e.localStore,i.query,!1).then((({documents:e})=>i.view.Ga(e,_))));const h=o&&o.targetChanges.get(i.targetId),d=o&&null!=o.targetMismatches.get(i.targetId),f=i.view.applyChanges(_,e.isPrimaryClient,h,d);return __PRIVATE_updateTrackedLimbos(e,i.targetId,f.Ya),f.snapshot}(e,i,s,o);const h=await __PRIVATE_localStoreExecuteQuery(e.localStore,i,!0),d=new __PRIVATE_View(i,h.Ns),f=d.Ga(h.documents),g=TargetChange.createSynthesizedTargetChangeForCurrentChange(s,o&&”Offline”!==e.onlineState,_),b=d.applyChanges(f,e.isPrimaryClient,g);__PRIVATE_updateTrackedLimbos(e,s,b.Ya);const w=new __PRIVATE_QueryView(i,s,d);return e.ru.set(i,w),e.iu.has(s)?e.iu.get(s).push(i):e.iu.set(s,[i]),b.snapshot}async function __PRIVATE_syncEngineUnlisten(e,i,s){const o=__PRIVATE_debugCast(e),_=o.ru.get(i),h=o.iu.get(_.targetId);if(h.length>1)return o.iu.set(_.targetId,h.filter((e=>!__PRIVATE_queryEquals(e,i)))),void o.ru.delete(i);o.isPrimaryClient?(o.sharedClientState.removeLocalQueryTarget(_.targetId),o.sharedClientState.isActiveQueryTarget(_.targetId)||await __PRIVATE_localStoreReleaseTarget(o.localStore,_.targetId,!1).then((()=>{o.sharedClientState.clearQueryState(_.targetId),s&&__PRIVATE_remoteStoreUnlisten(o.remoteStore,_.targetId),__PRIVATE_removeAndCleanupTarget(o,_.targetId)})).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)):(__PRIVATE_removeAndCleanupTarget(o,_.targetId),await __PRIVATE_localStoreReleaseTarget(o.localStore,_.targetId,!0))}async function __PRIVATE_triggerRemoteStoreUnlisten(e,i){const s=__PRIVATE_debugCast(e),o=s.ru.get(i),_=s.iu.get(o.targetId);s.isPrimaryClient&&1===_.length&&(s.sharedClientState.removeLocalQueryTarget(o.targetId),__PRIVATE_remoteStoreUnlisten(s.remoteStore,o.targetId))}async function __PRIVATE_syncEngineApplyRemoteEvent(e,i){const s=__PRIVATE_debugCast(e);try{const e=await function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e,i){const s=__PRIVATE_debugCast(e),o=i.snapshotVersion;let _=s.Ss;return s.persistence.runTransaction(“Apply remote event”,”readwrite-primary”,(e=>{const h=s.Cs.newChangeBuffer({trackRemovals:!0});_=s.Ss;const d=[];i.targetChanges.forEach(((h,f)=>{const g=_.get(f);if(!g)return;d.push(s.ai.removeMatchingKeys(e,h.removedDocuments,f).next((()=>s.ai.addMatchingKeys(e,h.addedDocuments,f))));let b=g.withSequenceNumber(e.currentSequenceNumber);null!==i.targetMismatches.get(f)?b=b.withResumeToken(ByteString.EMPTY_BYTE_STRING,SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()):h.resumeToken.approximateByteSize()>0&&(b=b.withResumeToken(h.resumeToken,o)),_=_.insert(f,b),function __PRIVATE_shouldPersistTargetData(e,i,s){return 0===e.resumeToken.approximateByteSize()||(i.snapshotVersion.toMicroseconds()-e.snapshotVersion.toMicroseconds()>=3e8||s.addedDocuments.size+s.modifiedDocuments.size+s.removedDocuments.size>0)}(g,b,h)&&d.push(s.ai.updateTargetData(e,b))}));let f=__PRIVATE_mutableDocumentMap(),g=__PRIVATE_documentKeySet();if(i.documentUpdates.forEach((o=>{i.resolvedLimboDocuments.has(o)&&d.push(s.persistence.referenceDelegate.updateLimboDocument(e,o))})),d.push(__PRIVATE_populateDocumentChangeBuffer(e,h,i.documentUpdates).next((e=>{f=e.xs,g=e.Os}))),!o.isEqual(SnapshotVersion.min())){const i=s.ai.getLastRemoteSnapshotVersion(e).next((i=>s.ai.setTargetsMetadata(e,e.currentSequenceNumber,o)));d.push(i)}return PersistencePromise.waitFor(d).next((()=>h.apply(e))).next((()=>s.localDocuments.getLocalViewOfDocuments(e,f,g))).next((()=>f))})).then((e=>(s.Ss=_,e)))}(s.localStore,i);i.targetChanges.forEach(((e,i)=>{const o=s._u.get(i);o&&(__PRIVATE_hardAssert(e.addedDocuments.size+e.modifiedDocuments.size+e.removedDocuments.size<=1,22616),e.addedDocuments.size>0?o.tu=!0:e.modifiedDocuments.size>0?__PRIVATE_hardAssert(o.tu,14607):e.removedDocuments.size>0&&(__PRIVATE_hardAssert(o.tu,42227),o.tu=!1))})),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(s,e,i)}catch(e){await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}}function __PRIVATE_syncEngineApplyOnlineStateChange(e,i,s){const o=__PRIVATE_debugCast(e);if(o.isPrimaryClient&&0===s||!o.isPrimaryClient&&1===s){const e=[];o.ru.forEach(((s,o)=>{const _=o.view.ga(i);_.snapshot&&e.push(_.snapshot)})),function __PRIVATE_eventManagerOnOnlineStateChange(e,i){const s=__PRIVATE_debugCast(e);s.onlineState=i;let o=!1;s.queries.forEach(((e,s)=>{for(const e of s.Ra)e.ga(i)&&(o=!0)})),o&&__PRIVATE_raiseSnapshotsInSyncEvent(s)}(o.eventManager,i),e.length&&o.nu.Q_(e),o.onlineState=i,o.isPrimaryClient&&o.sharedClientState.setOnlineState(i)}}async function __PRIVATE_syncEngineRejectListen(e,i,s){const o=__PRIVATE_debugCast(e);o.sharedClientState.updateQueryState(i,”rejected”,s);const _=o._u.get(i),h=_&&_.key;if(h){let e=new SortedMap(DocumentKey.comparator);e=e.insert(h,MutableDocument.newNoDocument(h,SnapshotVersion.min()));const s=__PRIVATE_documentKeySet().add(h),_=new RemoteEvent(SnapshotVersion.min(),new Map,new SortedMap(__PRIVATE_primitiveComparator),e,s);await __PRIVATE_syncEngineApplyRemoteEvent(o,_),o.ou=o.ou.remove(h),o._u.delete(i),__PRIVATE_pumpEnqueuedLimboResolutions(o)}else await __PRIVATE_localStoreReleaseTarget(o.localStore,i,!1).then((()=>__PRIVATE_removeAndCleanupTarget(o,i,s))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)}async function __PRIVATE_syncEngineApplySuccessfulWrite(e,i){const s=__PRIVATE_debugCast(e),o=i.batch.batchId;try{const e=await function __PRIVATE_localStoreAcknowledgeBatch(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction(“Acknowledge batch”,”readwrite-primary”,(e=>{const o=i.batch.keys(),_=s.Cs.newChangeBuffer({trackRemovals:!0});return function __PRIVATE_applyWriteToRemoteDocuments(e,i,s,o){const _=s.batch,h=_.keys();let d=PersistencePromise.resolve();return h.forEach((e=>{d=d.next((()=>o.getEntry(i,e))).next((i=>{const h=s.docVersions.get(e);__PRIVATE_hardAssert(null!==h,48541),i.version.compareTo(h)<0&&(_.applyToRemoteDocument(i,s),i.isValidDocument()&&(i.setReadTime(s.commitVersion),o.addEntry(i)))}))})),d.next((()=>e.mutationQueue.removeMutationBatch(i,_)))}(s,e,i,_).next((()=>_.apply(e))).next((()=>s.mutationQueue.performConsistencyCheck(e))).next((()=>s.documentOverlayCache.removeOverlaysForBatchId(e,o,i.batch.batchId))).next((()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,function __PRIVATE_getKeysWithTransformResults(e){let i=__PRIVATE_documentKeySet();for(let s=0;s0&&(i=i.add(e.batch.mutations[s].key));return i}(i)))).next((()=>s.localDocuments.getDocuments(e,o)))}))}(s.localStore,i);__PRIVATE_processUserCallback(s,o,null),__PRIVATE_triggerPendingWritesCallbacks(s,o),s.sharedClientState.updateMutationState(o,”acknowledged”),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(s,e)}catch(e){await __PRIVATE_ignoreIfPrimaryLeaseLoss(e)}}async function __PRIVATE_syncEngineRejectFailedWrite(e,i,s){const o=__PRIVATE_debugCast(e);try{const e=await function __PRIVATE_localStoreRejectBatch(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction(“Reject batch”,”readwrite-primary”,(e=>{let o;return s.mutationQueue.lookupMutationBatch(e,i).next((i=>(__PRIVATE_hardAssert(null!==i,37113),o=i.keys(),s.mutationQueue.removeMutationBatch(e,i)))).next((()=>s.mutationQueue.performConsistencyCheck(e))).next((()=>s.documentOverlayCache.removeOverlaysForBatchId(e,o,i))).next((()=>s.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e,o))).next((()=>s.localDocuments.getDocuments(e,o)))}))}(o.localStore,i);__PRIVATE_processUserCallback(o,i,s),__PRIVATE_triggerPendingWritesCallbacks(o,i),o.sharedClientState.updateMutationState(i,”rejected”,s),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(o,e)}catch(s){await __PRIVATE_ignoreIfPrimaryLeaseLoss(s)}}function __PRIVATE_triggerPendingWritesCallbacks(e,i){(e.cu.get(i)||[]).forEach((e=>{e.resolve()})),e.cu.delete(i)}function __PRIVATE_processUserCallback(e,i,s){const o=__PRIVATE_debugCast(e);let _=o.uu[o.currentUser.toKey()];if(_){const e=_.get(i);e&&(s?e.reject(s):e.resolve(),_=_.remove(i)),o.uu[o.currentUser.toKey()]=_}}function __PRIVATE_removeAndCleanupTarget(e,i,s=null){e.sharedClientState.removeLocalQueryTarget(i);for(const o of e.iu.get(i))e.ru.delete(o),s&&e.nu.Tu(o,s);e.iu.delete(i),e.isPrimaryClient&&e.au.Ur(i).forEach((i=>{e.au.containsKey(i)||__PRIVATE_removeLimboTarget(e,i)}))}function __PRIVATE_removeLimboTarget(e,i){e.su.delete(i.path.canonicalString());const s=e.ou.get(i);null!==s&&(__PRIVATE_remoteStoreUnlisten(e.remoteStore,s),e.ou=e.ou.remove(i),e._u.delete(s),__PRIVATE_pumpEnqueuedLimboResolutions(e))}function __PRIVATE_updateTrackedLimbos(e,i,s){for(const o of s)o instanceof __PRIVATE_AddedLimboDocument?(e.au.addReference(o.key,i),__PRIVATE_trackLimboChange(e,o)):o instanceof __PRIVATE_RemovedLimboDocument?(__PRIVATE_logDebug(Vn,”Document no longer in limbo: “+o.key),e.au.removeReference(o.key,i),e.au.containsKey(o.key)||__PRIVATE_removeLimboTarget(e,o.key)):fail(19791,{Iu:o})}function __PRIVATE_trackLimboChange(e,i){const s=i.key,o=s.path.canonicalString();e.ou.get(s)||e.su.has(o)||(__PRIVATE_logDebug(Vn,”New document in limbo: “+s),e.su.add(o),__PRIVATE_pumpEnqueuedLimboResolutions(e))}function __PRIVATE_pumpEnqueuedLimboResolutions(e){for(;e.su.size>0&&e.ou.size{d.push(o.Pu(f,i,s).then((e=>{var i;if((e||s)&&o.isPrimaryClient){const _=e?!e.fromCache:null===(i=null==s?void 0:s.targetChanges.get(f.targetId))||void 0===i?void 0:i.current;o.sharedClientState.updateQueryState(f.targetId,_?”current”:”not-current”)}if(e){_.push(e);const i=__PRIVATE_LocalViewChanges.Ps(f.targetId,e);h.push(i)}})))})),await Promise.all(d),o.nu.Q_(_),await async function __PRIVATE_localStoreNotifyLocalViewChanges(e,i){const s=__PRIVATE_debugCast(e);try{await s.persistence.runTransaction(“notifyLocalViewChanges”,”readwrite”,(e=>PersistencePromise.forEach(i,(i=>PersistencePromise.forEach(i.ls,(o=>s.persistence.referenceDelegate.addReference(e,i.targetId,o))).next((()=>PersistencePromise.forEach(i.hs,(o=>s.persistence.referenceDelegate.removeReference(e,i.targetId,o)))))))))}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug(_n,”Failed to update sequence numbers: “+e)}for(const e of i){const i=e.targetId;if(!e.fromCache){const e=s.Ss.get(i),o=e.snapshotVersion,_=e.withLastLimboFreeSnapshotVersion(o);s.Ss=s.Ss.insert(i,_)}}}(o.localStore,h))}async function __PRIVATE_syncEngineHandleCredentialChange(e,i){const s=__PRIVATE_debugCast(e);if(!s.currentUser.isEqual(i)){__PRIVATE_logDebug(Vn,”User change. New user:”,i.toKey());const e=await __PRIVATE_localStoreHandleUserChange(s.localStore,i);s.currentUser=i,function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e,i){e.cu.forEach((e=>{e.forEach((e=>{e.reject(new FirestoreError(de.CANCELLED,i))}))})),e.cu.clear()}(s,”‘waitForPendingWrites’ promise is rejected due to a user change.”),s.sharedClientState.handleUserChange(i,e.removedBatchIds,e.addedBatchIds),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(s,e.Ms)}}function __PRIVATE_syncEngineGetRemoteKeysForTarget(e,i){const s=__PRIVATE_debugCast(e),o=s._u.get(i);if(o&&o.tu)return __PRIVATE_documentKeySet().add(o.key);{let e=__PRIVATE_documentKeySet();const o=s.iu.get(i);if(!o)return e;for(const i of o){const o=s.ru.get(i);e=e.unionWith(o.view.Wa)}return e}}async function __PRIVATE_synchronizeViewAndComputeSnapshot(e,i){const s=__PRIVATE_debugCast(e),o=await __PRIVATE_localStoreExecuteQuery(s.localStore,i.query,!0),_=i.view.Xa(o);return s.isPrimaryClient&&__PRIVATE_updateTrackedLimbos(s,i.targetId,_.Ya),_}async function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e,i){const s=__PRIVATE_debugCast(e);return __PRIVATE_localStoreGetNewDocumentChanges(s.localStore,i).then((e=>__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(s,e)))}async function __PRIVATE_syncEngineApplyBatchState(e,i,s,o){const _=__PRIVATE_debugCast(e),h=await function __PRIVATE_localStoreLookupMutationDocuments(e,i){const s=__PRIVATE_debugCast(e),o=__PRIVATE_debugCast(s.mutationQueue);return s.persistence.runTransaction(“Lookup mutation documents”,”readonly”,(e=>o.Hn(e,i).next((i=>i?s.localDocuments.getDocuments(e,i):PersistencePromise.resolve(null)))))}(_.localStore,i);null!==h?(“pending”===s?await __PRIVATE_fillWritePipeline(_.remoteStore):”acknowledged”===s||”rejected”===s?(__PRIVATE_processUserCallback(_,i,o||null),__PRIVATE_triggerPendingWritesCallbacks(_,i),function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e,i){__PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).Xn(i)}(_.localStore,i)):fail(6720,”Unknown batchState”,{Eu:s}),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(_,h)):__PRIVATE_logDebug(Vn,”Cannot apply mutation batch with id: “+i)}async function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e,i,s){const o=__PRIVATE_debugCast(e),_=[],h=[];for(const e of i){let i;const s=o.iu.get(e);if(s&&0!==s.length){i=await __PRIVATE_localStoreAllocateTarget(o.localStore,__PRIVATE_queryToTarget(s[0]));for(const e of s){const i=o.ru.get(e),s=await __PRIVATE_synchronizeViewAndComputeSnapshot(o,i);s.snapshot&&h.push(s.snapshot)}}else{const s=await __PRIVATE_localStoreGetCachedTarget(o.localStore,e);i=await __PRIVATE_localStoreAllocateTarget(o.localStore,s),await __PRIVATE_initializeViewAndComputeSnapshot(o,__PRIVATE_synthesizeTargetToQuery(s),e,!1,i.resumeToken)}_.push(i)}return o.nu.Q_(h),_}function __PRIVATE_synthesizeTargetToQuery(e){return __PRIVATE_newQuery(e.path,e.collectionGroup,e.orderBy,e.filters,e.limit,”F”,e.startAt,e.endAt)}function __PRIVATE_syncEngineGetActiveClients(e){return function __PRIVATE_localStoreGetActiveClients(e){return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).us()}(__PRIVATE_debugCast(e).localStore)}async function __PRIVATE_syncEngineApplyTargetState(e,i,s,o){const _=__PRIVATE_debugCast(e);if(_.hu)return void __PRIVATE_logDebug(Vn,”Ignoring unexpected query state notification.”);const h=_.iu.get(i);if(h&&h.length>0)switch(s){case”current”:case”not-current”:{const e=await __PRIVATE_localStoreGetNewDocumentChanges(_.localStore,__PRIVATE_queryCollectionGroup(h[0])),o=RemoteEvent.createSynthesizedRemoteEventForCurrentChange(i,”current”===s,ByteString.EMPTY_BYTE_STRING);await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(_,e,o);break}case”rejected”:await __PRIVATE_localStoreReleaseTarget(_.localStore,i,!0),__PRIVATE_removeAndCleanupTarget(_,i,o);break;default:fail(64155,s)}}async function __PRIVATE_syncEngineApplyActiveTargetsChange(e,i,s){const o=__PRIVATE_ensureWatchCallbacks(e);if(o.hu){for(const e of i){if(o.iu.has(e)&&o.sharedClientState.isActiveQueryTarget(e)){__PRIVATE_logDebug(Vn,”Adding an already active target “+e);continue}const i=await __PRIVATE_localStoreGetCachedTarget(o.localStore,e),s=await __PRIVATE_localStoreAllocateTarget(o.localStore,i);await __PRIVATE_initializeViewAndComputeSnapshot(o,__PRIVATE_synthesizeTargetToQuery(i),s.targetId,!1,s.resumeToken),__PRIVATE_remoteStoreListen(o.remoteStore,s)}for(const e of s)o.iu.has(e)&&await __PRIVATE_localStoreReleaseTarget(o.localStore,e,!1).then((()=>{__PRIVATE_remoteStoreUnlisten(o.remoteStore,e),__PRIVATE_removeAndCleanupTarget(o,e)})).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss)}}function __PRIVATE_ensureWatchCallbacks(e){const i=__PRIVATE_debugCast(e);return i.remoteStore.remoteSyncer.applyRemoteEvent=__PRIVATE_syncEngineApplyRemoteEvent.bind(null,i),i.remoteStore.remoteSyncer.getRemoteKeysForTarget=__PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null,i),i.remoteStore.remoteSyncer.rejectListen=__PRIVATE_syncEngineRejectListen.bind(null,i),i.nu.Q_=__PRIVATE_eventManagerOnWatchChange.bind(null,i.eventManager),i.nu.Tu=__PRIVATE_eventManagerOnWatchError.bind(null,i.eventManager),i}function __PRIVATE_syncEngineEnsureWriteCallbacks(e){const i=__PRIVATE_debugCast(e);return i.remoteStore.remoteSyncer.applySuccessfulWrite=__PRIVATE_syncEngineApplySuccessfulWrite.bind(null,i),i.remoteStore.remoteSyncer.rejectFailedWrite=__PRIVATE_syncEngineRejectFailedWrite.bind(null,i),i}class __PRIVATE_MemoryOfflineComponentProvider{constructor(){this.kind=”memory”,this.synchronizeTabs=!1}async initialize(e){this.serializer=__PRIVATE_newSerializer(e.databaseInfo.databaseId),this.sharedClientState=this.Au(e),this.persistence=this.Ru(e),await this.persistence.start(),this.localStore=this.Vu(e),this.gcScheduler=this.mu(e,this.localStore),this.indexBackfillerScheduler=this.fu(e,this.localStore)}mu(e,i){return null}fu(e,i){return null}Vu(e){return __PRIVATE_newLocalStore(this.persistence,new __PRIVATE_QueryEngine,e.initialUser,this.serializer)}Ru(e){return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.Ei,this.serializer)}Au(e){return new __PRIVATE_MemorySharedClientState}async terminate(){var e,i;null===(e=this.gcScheduler)||void 0===e||e.stop(),null===(i=this.indexBackfillerScheduler)||void 0===i||i.stop(),this.sharedClientState.shutdown(),await this.persistence.shutdown()}}__PRIVATE_MemoryOfflineComponentProvider.provider={build:()=>new __PRIVATE_MemoryOfflineComponentProvider};class __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider{constructor(e){super(),this.cacheSizeBytes=e}mu(e,i){__PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate,46915);const s=this.persistence.referenceDelegate.garbageCollector;return new __PRIVATE_LruScheduler(s,e.asyncQueue,i)}Ru(e){const i=void 0!==this.cacheSizeBytes?LruParams.withCacheSize(this.cacheSizeBytes):LruParams.DEFAULT;return new __PRIVATE_MemoryPersistence((e=>__PRIVATE_MemoryLruDelegate.Ei(e,i)),this.serializer)}}class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider{constructor(e,i,s){super(),this.gu=e,this.cacheSizeBytes=i,this.forceOwnership=s,this.kind=”persistent”,this.synchronizeTabs=!1}async initialize(e){await super.initialize(e),await this.gu.initialize(this,e),await __PRIVATE_syncEngineEnsureWriteCallbacks(this.gu.syncEngine),await __PRIVATE_fillWritePipeline(this.gu.remoteStore),await this.persistence.Ki((()=>(this.gcScheduler&&!this.gcScheduler.started&&this.gcScheduler.start(),this.indexBackfillerScheduler&&!this.indexBackfillerScheduler.started&&this.indexBackfillerScheduler.start(),Promise.resolve())))}Vu(e){return __PRIVATE_newLocalStore(this.persistence,new __PRIVATE_QueryEngine,e.initialUser,this.serializer)}mu(e,i){const s=this.persistence.referenceDelegate.garbageCollector;return new __PRIVATE_LruScheduler(s,e.asyncQueue,i)}fu(e,i){const s=new __PRIVATE_IndexBackfiller(i,this.persistence);return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue,s)}Ru(e){const i=__PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey),s=void 0!==this.cacheSizeBytes?LruParams.withCacheSize(this.cacheSizeBytes):LruParams.DEFAULT;return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs,i,e.clientId,s,e.asyncQueue,__PRIVATE_getWindow(),getDocument(),this.serializer,this.sharedClientState,!!this.forceOwnership)}Au(e){return new __PRIVATE_MemorySharedClientState}}class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider{constructor(e,i){super(e,i,!1),this.gu=e,this.cacheSizeBytes=i,this.synchronizeTabs=!0}async initialize(e){await super.initialize(e);const i=this.gu.syncEngine;this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState&&(this.sharedClientState.syncEngine={yo:__PRIVATE_syncEngineApplyBatchState.bind(null,i),wo:__PRIVATE_syncEngineApplyTargetState.bind(null,i),bo:__PRIVATE_syncEngineApplyActiveTargetsChange.bind(null,i),us:__PRIVATE_syncEngineGetActiveClients.bind(null,i),po:__PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null,i)},await this.sharedClientState.start()),await this.persistence.Ki((async e=>{await async function __PRIVATE_syncEngineApplyPrimaryState(e,i){const s=__PRIVATE_debugCast(e);if(__PRIVATE_ensureWatchCallbacks(s),__PRIVATE_syncEngineEnsureWriteCallbacks(s),!0===i&&!0!==s.hu){const e=s.sharedClientState.getAllActiveQueryTargets(),i=await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(s,e.toArray());s.hu=!0,await __PRIVATE_remoteStoreApplyPrimaryState(s.remoteStore,!0);for(const e of i)__PRIVATE_remoteStoreListen(s.remoteStore,e)}else if(!1===i&&!1!==s.hu){const e=[];let i=Promise.resolve();s.iu.forEach(((o,_)=>{s.sharedClientState.isLocalQueryTarget(_)?e.push(_):i=i.then((()=>(__PRIVATE_removeAndCleanupTarget(s,_),__PRIVATE_localStoreReleaseTarget(s.localStore,_,!0)))),__PRIVATE_remoteStoreUnlisten(s.remoteStore,_)})),await i,await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(s,e),function __PRIVATE_resetLimboDocuments(e){const i=__PRIVATE_debugCast(e);i._u.forEach(((e,s)=>{__PRIVATE_remoteStoreUnlisten(i.remoteStore,s)})),i.au.Kr(),i._u=new Map,i.ou=new SortedMap(DocumentKey.comparator)}(s),s.hu=!1,await __PRIVATE_remoteStoreApplyPrimaryState(s.remoteStore,!1)}}(this.gu.syncEngine,e),this.gcScheduler&&(e&&!this.gcScheduler.started?this.gcScheduler.start():e||this.gcScheduler.stop()),this.indexBackfillerScheduler&&(e&&!this.indexBackfillerScheduler.started?this.indexBackfillerScheduler.start():e||this.indexBackfillerScheduler.stop())}))}Au(e){const i=__PRIVATE_getWindow();if(!__PRIVATE_WebStorageSharedClientState.C(i))throw new FirestoreError(de.UNIMPLEMENTED,”IndexedDB persistence is only available on platforms that support LocalStorage.”);const s=__PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId,e.databaseInfo.persistenceKey);return new __PRIVATE_WebStorageSharedClientState(i,e.asyncQueue,s,e.clientId,e.initialUser)}}class OnlineComponentProvider{async initialize(e,i){this.localStore||(this.localStore=e.localStore,this.sharedClientState=e.sharedClientState,this.datastore=this.createDatastore(i),this.remoteStore=this.createRemoteStore(i),this.eventManager=this.createEventManager(i),this.syncEngine=this.createSyncEngine(i,!e.synchronizeTabs),this.sharedClientState.onlineStateHandler=e=>__PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine,e,1),this.remoteStore.remoteSyncer.handleCredentialChange=__PRIVATE_syncEngineHandleCredentialChange.bind(null,this.syncEngine),await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore,this.syncEngine.isPrimaryClient))}createEventManager(e){return function __PRIVATE_newEventManager(){return new __PRIVATE_EventManagerImpl}()}createDatastore(e){const i=__PRIVATE_newSerializer(e.databaseInfo.databaseId),s=function __PRIVATE_newConnection(e){return new __PRIVATE_WebChannelConnection(e)}(e.databaseInfo);return function __PRIVATE_newDatastore(e,i,s,o){return new __PRIVATE_DatastoreImpl(e,i,s,o)}(e.authCredentials,e.appCheckCredentials,s,i)}createRemoteStore(e){return function __PRIVATE_newRemoteStore(e,i,s,o,_){return new __PRIVATE_RemoteStoreImpl(e,i,s,o,_)}(this.localStore,this.datastore,e.asyncQueue,(e=>__PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine,e,0)),function __PRIVATE_newConnectivityMonitor(){return __PRIVATE_BrowserConnectivityMonitor.C()?new __PRIVATE_BrowserConnectivityMonitor:new __PRIVATE_NoopConnectivityMonitor}())}createSyncEngine(e,i){return function __PRIVATE_newSyncEngine(e,i,s,o,_,h,d){const f=new __PRIVATE_SyncEngineImpl(e,i,s,o,_,h);return d&&(f.hu=!0),f}(this.localStore,this.remoteStore,this.eventManager,this.sharedClientState,e.initialUser,e.maxConcurrentLimboResolutions,i)}async terminate(){var e,i;await async function __PRIVATE_remoteStoreShutdown(e){const i=__PRIVATE_debugCast(e);__PRIVATE_logDebug(An,”RemoteStore shutting down.”),i.aa.add(5),await __PRIVATE_disableNetworkInternal(i),i.ca.shutdown(),i.la.set(“Unknown”)}(this.remoteStore),null===(e=this.datastore)||void 0===e||e.terminate(),null===(i=this.eventManager)||void 0===i||i.terminate()}}function __PRIVATE_toByteStreamReaderHelper(e,i=10240){let s=0;return{async read(){if(snew OnlineComponentProvider};class __PRIVATE_AsyncObserver{constructor(e){this.observer=e,this.muted=!1}next(e){this.muted||this.observer.next&&this.pu(this.observer.next,e)}error(e){this.muted||(this.observer.error?this.pu(this.observer.error,e):__PRIVATE_logError(“Uncaught Error in snapshot listener:”,e.toString()))}yu(){this.muted=!0}pu(e,i){setTimeout((()=>{this.muted||e(i)}),0)}}class __PRIVATE_BundleReaderImpl{constructor(e,i){this.wu=e,this.serializer=i,this.metadata=new __PRIVATE_Deferred,this.buffer=new Uint8Array,this.bu=function __PRIVATE_newTextDecoder(){return new TextDecoder(“utf-8”)}(),this.Su().then((e=>{e&&e.xa()?this.metadata.resolve(e.Ma.metadata):this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(null==e?void 0:e.Ma)}`))}),(e=>this.metadata.reject(e)))}close(){return this.wu.cancel()}async getMetadata(){return this.metadata.promise}async du(){return await this.getMetadata(),this.Su()}async Su(){const e=await this.Du();if(null===e)return null;const i=this.bu.decode(e),s=Number(i);isNaN(s)&&this.vu(`length string (${i}) is not valid number`);const o=await this.Cu(s);return new __PRIVATE_SizedBundleElement(JSON.parse(o),e.length+s)}Fu(){return this.buffer.findIndex((e=>e===”{“.charCodeAt(0)))}async Du(){for(;this.Fu()<0&&!await this.Mu(););if(0===this.buffer.length)return null;const e=this.Fu();e<0&&this.vu("Reached the end of bundle when a length string is expected.");const i=this.buffer.slice(0,e);return this.buffer=this.buffer.slice(e),i}async Cu(e){for(;this.buffer.length0)throw this.lastTransactionError=new FirestoreError(de.INVALID_ARGUMENT,”Firestore transactions require all reads to be executed before all writes.”),this.lastTransactionError;const i=await async function __PRIVATE_invokeBatchGetDocumentsRpc(e,i){const s=__PRIVATE_debugCast(e),o={documents:i.map((e=>__PRIVATE_toName(s.serializer,e)))},_=await s.Wo(“BatchGetDocuments”,s.serializer.databaseId,ResourcePath.emptyPath(),o,i.length),h=new Map;_.forEach((e=>{const i=function __PRIVATE_fromBatchGetDocumentsResponse(e,i){return”found”in i?function __PRIVATE_fromFound(e,i){__PRIVATE_hardAssert(!!i.found,43571),i.found.name,i.found.updateTime;const s=fromName(e,i.found.name),o=__PRIVATE_fromVersion(i.found.updateTime),_=i.found.createTime?__PRIVATE_fromVersion(i.found.createTime):SnapshotVersion.min(),h=new ObjectValue({mapValue:{fields:i.found.fields}});return MutableDocument.newFoundDocument(s,o,_,h)}(e,i):”missing”in i?function __PRIVATE_fromMissing(e,i){__PRIVATE_hardAssert(!!i.missing,3894),__PRIVATE_hardAssert(!!i.readTime,22933);const s=fromName(e,i.missing),o=__PRIVATE_fromVersion(i.readTime);return MutableDocument.newNoDocument(s,o)}(e,i):fail(7234,{result:i})}(s.serializer,e);h.set(i.key.toString(),i)}));const d=[];return i.forEach((e=>{const i=h.get(e.toString());__PRIVATE_hardAssert(!!i,55234,{key:e}),d.push(i)})),d}(this.datastore,e);return i.forEach((e=>this.recordVersion(e))),i}set(e,i){this.write(i.toMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}update(e,i){try{this.write(i.toMutation(e,this.preconditionForUpdate(e)))}catch(e){this.lastTransactionError=e}this.writtenDocs.add(e.toString())}delete(e){this.write(new __PRIVATE_DeleteMutation(e,this.precondition(e))),this.writtenDocs.add(e.toString())}async commit(){if(this.ensureCommitNotCalled(),this.lastTransactionError)throw this.lastTransactionError;const e=this.readVersions;this.mutations.forEach((i=>{e.delete(i.key.toString())})),e.forEach(((e,i)=>{const s=DocumentKey.fromPath(i);this.mutations.push(new __PRIVATE_VerifyMutation(s,this.precondition(s)))})),await async function __PRIVATE_invokeCommitRpc(e,i){const s=__PRIVATE_debugCast(e),o={writes:i.map((e=>toMutation(s.serializer,e)))};await s.Qo(“Commit”,s.serializer.databaseId,ResourcePath.emptyPath(),o)}(this.datastore,this.mutations),this.committed=!0}recordVersion(e){let i;if(e.isFoundDocument())i=e.version;else{if(!e.isNoDocument())throw fail(50498,{xu:e.constructor.name});i=SnapshotVersion.min()}const s=this.readVersions.get(e.key.toString());if(s){if(!i.isEqual(s))throw new FirestoreError(de.ABORTED,”Document version changed between two reads.”)}else this.readVersions.set(e.key.toString(),i)}precondition(e){const i=this.readVersions.get(e.toString());return!this.writtenDocs.has(e.toString())&&i?i.isEqual(SnapshotVersion.min())?Precondition.exists(!1):Precondition.updateTime(i):Precondition.none()}preconditionForUpdate(e){const i=this.readVersions.get(e.toString());if(!this.writtenDocs.has(e.toString())&&i){if(i.isEqual(SnapshotVersion.min()))throw new FirestoreError(de.INVALID_ARGUMENT,”Can’t update a document that doesn’t exist.”);return Precondition.updateTime(i)}return Precondition.exists(!0)}write(e){this.ensureCommitNotCalled(),this.mutations.push(e)}ensureCommitNotCalled(){}}class __PRIVATE_TransactionRunner{constructor(e,i,s,o,_){this.asyncQueue=e,this.datastore=i,this.options=s,this.updateFunction=o,this.deferred=_,this.Ou=s.maxAttempts,this.y_=new __PRIVATE_ExponentialBackoff(this.asyncQueue,”transaction_retry”)}Nu(){this.Ou-=1,this.Bu()}Bu(){this.y_.E_((async()=>{const e=new Transaction$2(this.datastore),i=this.Lu(e);i&&i.then((i=>{this.asyncQueue.enqueueAndForget((()=>e.commit().then((()=>{this.deferred.resolve(i)})).catch((e=>{this.ku(e)}))))})).catch((e=>{this.ku(e)}))}))}Lu(e){try{const i=this.updateFunction(e);return!__PRIVATE_isNullOrUndefined(i)&&i.catch&&i.then?i:(this.deferred.reject(Error(“Transaction callback must return a Promise”)),null)}catch(e){return this.deferred.reject(e),null}}ku(e){this.Ou>0&&this.qu(e)?(this.Ou-=1,this.asyncQueue.enqueueAndForget((()=>(this.Bu(),Promise.resolve())))):this.deferred.reject(e)}qu(e){if(“FirebaseError”===e.name){const i=e.code;return”aborted”===i||”failed-precondition”===i||”already-exists”===i||!__PRIVATE_isPermanentError(i)}return!1}}const vn=”FirestoreClient”;class FirestoreClient{constructor(e,i,s,o,_){this.authCredentials=e,this.appCheckCredentials=i,this.asyncQueue=s,this.databaseInfo=o,this.user=User.UNAUTHENTICATED,this.clientId=__PRIVATE_AutoId.newId(),this.authCredentialListener=()=>Promise.resolve(),this.appCheckCredentialListener=()=>Promise.resolve(),this._uninitializedComponentsProvider=_,this.authCredentials.start(s,(async e=>{__PRIVATE_logDebug(vn,”Received user=”,e.uid),await this.authCredentialListener(e),this.user=e})),this.appCheckCredentials.start(s,(e=>(__PRIVATE_logDebug(vn,”Received new app check token=”,e),this.appCheckCredentialListener(e,this.user))))}get configuration(){return{asyncQueue:this.asyncQueue,databaseInfo:this.databaseInfo,clientId:this.clientId,authCredentials:this.authCredentials,appCheckCredentials:this.appCheckCredentials,initialUser:this.user,maxConcurrentLimboResolutions:100}}setCredentialChangeListener(e){this.authCredentialListener=e}setAppCheckTokenChangeListener(e){this.appCheckCredentialListener=e}terminate(){this.asyncQueue.enterRestrictedMode();const e=new __PRIVATE_Deferred;return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async()=>{try{this._onlineComponents&&await this._onlineComponents.terminate(),this._offlineComponents&&await this._offlineComponents.terminate(),this.authCredentials.shutdown(),this.appCheckCredentials.shutdown(),e.resolve()}catch(i){const s=__PRIVATE_wrapInUserErrorIfRecoverable(i,”Failed to shutdown persistence”);e.reject(s)}})),e.promise}}async function __PRIVATE_setOfflineComponentProvider(e,i){e.asyncQueue.verifyOperationInProgress(),__PRIVATE_logDebug(vn,”Initializing OfflineComponentProvider”);const s=e.configuration;await i.initialize(s);let o=s.initialUser;e.setCredentialChangeListener((async e=>{o.isEqual(e)||(await __PRIVATE_localStoreHandleUserChange(i.localStore,e),o=e)})),i.persistence.setDatabaseDeletedListener((()=>e.terminate())),e._offlineComponents=i}async function __PRIVATE_setOnlineComponentProvider(e,i){e.asyncQueue.verifyOperationInProgress();const s=await __PRIVATE_ensureOfflineComponents(e);__PRIVATE_logDebug(vn,”Initializing OnlineComponentProvider”),await i.initialize(s,e.configuration),e.setCredentialChangeListener((e=>__PRIVATE_remoteStoreHandleCredentialChange(i.remoteStore,e))),e.setAppCheckTokenChangeListener(((e,s)=>__PRIVATE_remoteStoreHandleCredentialChange(i.remoteStore,s))),e._onlineComponents=i}async function __PRIVATE_ensureOfflineComponents(e){if(!e._offlineComponents)if(e._uninitializedComponentsProvider){__PRIVATE_logDebug(vn,”Using user provided OfflineComponentProvider”);try{await __PRIVATE_setOfflineComponentProvider(e,e._uninitializedComponentsProvider._offline)}catch(i){const s=i;if(!function __PRIVATE_canFallbackFromIndexedDbError(e){return”FirebaseError”===e.name?e.code===de.FAILED_PRECONDITION||e.code===de.UNIMPLEMENTED:!(“undefined”!=typeof DOMException&&e instanceof DOMException)||22===e.code||20===e.code||11===e.code}(s))throw s;__PRIVATE_logWarn(“Error using user provided cache. Falling back to memory cache: “+s),await __PRIVATE_setOfflineComponentProvider(e,new __PRIVATE_MemoryOfflineComponentProvider)}}else __PRIVATE_logDebug(vn,”Using default OfflineComponentProvider”),await __PRIVATE_setOfflineComponentProvider(e,new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0));return e._offlineComponents}async function __PRIVATE_ensureOnlineComponents(e){return e._onlineComponents||(e._uninitializedComponentsProvider?(__PRIVATE_logDebug(vn,”Using user provided OnlineComponentProvider”),await __PRIVATE_setOnlineComponentProvider(e,e._uninitializedComponentsProvider._online)):(__PRIVATE_logDebug(vn,”Using default OnlineComponentProvider”),await __PRIVATE_setOnlineComponentProvider(e,new OnlineComponentProvider))),e._onlineComponents}function __PRIVATE_getPersistence(e){return __PRIVATE_ensureOfflineComponents(e).then((e=>e.persistence))}function __PRIVATE_getLocalStore(e){return __PRIVATE_ensureOfflineComponents(e).then((e=>e.localStore))}function __PRIVATE_getRemoteStore(e){return __PRIVATE_ensureOnlineComponents(e).then((e=>e.remoteStore))}function __PRIVATE_getSyncEngine(e){return __PRIVATE_ensureOnlineComponents(e).then((e=>e.syncEngine))}function __PRIVATE_getDatastore(e){return __PRIVATE_ensureOnlineComponents(e).then((e=>e.datastore))}async function __PRIVATE_getEventManager(e){const i=await __PRIVATE_ensureOnlineComponents(e),s=i.eventManager;return s.onListen=__PRIVATE_syncEngineListen.bind(null,i.syncEngine),s.onUnlisten=__PRIVATE_syncEngineUnlisten.bind(null,i.syncEngine),s.onFirstRemoteStoreListen=__PRIVATE_triggerRemoteStoreListen.bind(null,i.syncEngine),s.onLastRemoteStoreUnlisten=__PRIVATE_triggerRemoteStoreUnlisten.bind(null,i.syncEngine),s}function __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e,i,s={}){const o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>function __PRIVATE_readDocumentViaSnapshotListener(e,i,s,o,_){const h=new __PRIVATE_AsyncObserver({next:f=>{h.yu(),i.enqueueAndForget((()=>__PRIVATE_eventManagerUnlisten(e,d)));const g=f.docs.has(s);!g&&f.fromCache?_.reject(new FirestoreError(de.UNAVAILABLE,”Failed to get document because the client is offline.”)):g&&f.fromCache&&o&&”server”===o.source?_.reject(new FirestoreError(de.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.)’)):_.resolve(f)},error:e=>_.reject(e)}),d=new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(s.path),h,{includeMetadataChanges:!0,Fa:!0});return __PRIVATE_eventManagerListen(e,d)}(await __PRIVATE_getEventManager(e),e.asyncQueue,i,s,o))),o.promise}function __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e,i,s={}){const o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>function __PRIVATE_executeQueryViaSnapshotListener(e,i,s,o,_){const h=new __PRIVATE_AsyncObserver({next:s=>{h.yu(),i.enqueueAndForget((()=>__PRIVATE_eventManagerUnlisten(e,d))),s.fromCache&&”server”===o.source?_.reject(new FirestoreError(de.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.)’)):_.resolve(s)},error:e=>_.reject(e)}),d=new __PRIVATE_QueryListener(s,h,{includeMetadataChanges:!0,Fa:!0});return __PRIVATE_eventManagerListen(e,d)}(await __PRIVATE_getEventManager(e),e.asyncQueue,i,s,o))),o.promise}function __PRIVATE_firestoreClientLoadBundle(e,i,s,o){const _=function __PRIVATE_createBundleReader(e,i){let s;return s=”string”==typeof e?__PRIVATE_newTextEncoder().encode(e):e,function __PRIVATE_newBundleReader(e,i){return new __PRIVATE_BundleReaderImpl(e,i)}(function __PRIVATE_toByteStreamReader(e,i){if(e instanceof Uint8Array)return __PRIVATE_toByteStreamReaderHelper(e,i);if(e instanceof ArrayBuffer)return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e),i);if(e instanceof ReadableStream)return e.getReader();throw new Error(“Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream”)}(s),i)}(s,__PRIVATE_newSerializer(i));e.asyncQueue.enqueueAndForget((async()=>{!function __PRIVATE_syncEngineLoadBundle(e,i,s){const o=__PRIVATE_debugCast(e);(async function __PRIVATE_loadBundleImpl(e,i,s){try{const o=await i.getMetadata();if(await function __PRIVATE_localStoreHasNewerBundle(e,i){const s=__PRIVATE_debugCast(e),o=__PRIVATE_fromVersion(i.createTime);return s.persistence.runTransaction(“hasNewerBundle”,”readonly”,(e=>s.ci.getBundleMetadata(e,i.id))).then((e=>!!e&&e.createTime.compareTo(o)>=0))}(e.localStore,o))return await i.close(),s._completeWith(function __PRIVATE_bundleSuccessProgress(e){return{taskState:”Success”,documentsLoaded:e.totalDocuments,bytesLoaded:e.totalBytes,totalDocuments:e.totalDocuments,totalBytes:e.totalBytes}}(o)),Promise.resolve(new Set);s._updateProgress(__PRIVATE_bundleInitialProgress(o));const _=new __PRIVATE_BundleLoader(o,e.localStore,i.serializer);let h=await i.du();for(;h;){const e=await _.Na(h);e&&s._updateProgress(e),h=await i.du()}const d=await _.complete();return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e,d.ka,void 0),await function __PRIVATE_localStoreSaveBundle(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction(“Save bundle”,”readwrite”,(e=>s.ci.saveBundleMetadata(e,i)))}(e.localStore,o),s._completeWith(d.progress),Promise.resolve(d.La)}catch(e){return __PRIVATE_logWarn(Vn,`Loading bundle failed with ${e}`),s._failWith(e),Promise.resolve(new Set)}})(o,i,s).then((e=>{o.sharedClientState.notifyBundleLoaded(e)}))}(await __PRIVATE_getSyncEngine(e),_,o)}))}function __PRIVATE_cloneLongPollingOptions(e){const i={};return void 0!==e.timeoutSeconds&&(i.timeoutSeconds=e.timeoutSeconds),i}const bn=new Map;function __PRIVATE_validateNonEmptyArgument(e,i,s){if(!s)throw new FirestoreError(de.INVALID_ARGUMENT,`Function ${e}() cannot be called with an empty ${i}.`)}function __PRIVATE_validateIsNotUsedTogether(e,i,s,o){if(!0===i&&!0===o)throw new FirestoreError(de.INVALID_ARGUMENT,`${e} and ${s} cannot be used together.`)}function __PRIVATE_validateDocumentPath(e){if(!DocumentKey.isDocumentKey(e))throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_validateCollectionPath(e){if(DocumentKey.isDocumentKey(e))throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`)}function __PRIVATE_valueDescription(e){if(void 0===e)return”undefined”;if(null===e)return”null”;if(“string”==typeof e)return e.length>20&&(e=`${e.substring(0,20)}…`),JSON.stringify(e);if(“number”==typeof e||”boolean”==typeof e)return””+e;if(“object”==typeof e){if(e instanceof Array)return”an array”;{const i=function __PRIVATE_tryGetCustomObjectType(e){return e.constructor?e.constructor.name:null}(e);return i?`a custom ${i} object`:”an object”}}return”function”==typeof e?”a function”:fail(12329,{type:typeof e})}function __PRIVATE_cast(e,i){if(“_delegate”in e&&(e=e._delegate),!(e instanceof i)){if(i.name===e.constructor.name)throw new FirestoreError(de.INVALID_ARGUMENT,”Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?”);{const s=__PRIVATE_valueDescription(e);throw new FirestoreError(de.INVALID_ARGUMENT,`Expected type ‘${i.name}’, but it was: ${s}`)}}return e}function __PRIVATE_validatePositiveNumber(e,i){if(i<=0)throw new FirestoreError(de.INVALID_ARGUMENT,`Function ${e}() requires a positive number, but it was: ${i}.`)}const Sn="firestore.googleapis.com",wn=!0;class FirestoreSettingsImpl{constructor(e){var i,s;if(void 0===e.host){if(void 0!==e.ssl)throw new FirestoreError(de.INVALID_ARGUMENT,"Can't provide ssl option if host option is not set");this.host=Sn,this.ssl=wn}else this.host=e.host,this.ssl=null!==(i=e.ssl)&&void 0!==i?i:wn;if(this.credentials=e.credentials,this.ignoreUndefinedProperties=!!e.ignoreUndefinedProperties,this.localCache=e.localCache,void 0===e.cacheSizeBytes)this.cacheSizeBytes=nn;else{if(-1!==e.cacheSizeBytes&&e.cacheSizeBytes30)throw new FirestoreError(de.INVALID_ARGUMENT,`invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`)}}(this.experimentalLongPollingOptions),this.useFetchStreams=!!e.useFetchStreams}isEqual(e){return this.host===e.host&&this.ssl===e.ssl&&this.credentials===e.credentials&&this.cacheSizeBytes===e.cacheSizeBytes&&this.experimentalForceLongPolling===e.experimentalForceLongPolling&&this.experimentalAutoDetectLongPolling===e.experimentalAutoDetectLongPolling&&function __PRIVATE_longPollingOptionsEqual(e,i){return e.timeoutSeconds===i.timeoutSeconds}(this.experimentalLongPollingOptions,e.experimentalLongPollingOptions)&&this.ignoreUndefinedProperties===e.ignoreUndefinedProperties&&this.useFetchStreams===e.useFetchStreams}}class Firestore$1{constructor(e,i,s,o){this._authCredentials=e,this._appCheckCredentials=i,this._databaseId=s,this._app=o,this.type=”firestore-lite”,this._persistenceKey=”(lite)”,this._settings=new FirestoreSettingsImpl({}),this._settingsFrozen=!1,this._emulatorOptions={},this._terminateTask=”notTerminated”}get app(){if(!this._app)throw new FirestoreError(de.FAILED_PRECONDITION,”Firestore was not initialized using the Firebase SDK. ‘app’ is not available”);return this._app}get _initialized(){return this._settingsFrozen}get _terminated(){return”notTerminated”!==this._terminateTask}_setSettings(e){if(this._settingsFrozen)throw new FirestoreError(de.FAILED_PRECONDITION,”Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.”);this._settings=new FirestoreSettingsImpl(e),this._emulatorOptions=e.emulatorOptions||{},void 0!==e.credentials&&(this._authCredentials=function __PRIVATE_makeAuthCredentialsProvider(e){if(!e)return new __PRIVATE_EmptyAuthCredentialsProvider;switch(e.type){case”firstParty”:return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex||”0″,e.iamToken||null,e.authTokenFactory||null);case”provider”:return e.client;default:throw new FirestoreError(de.INVALID_ARGUMENT,”makeAuthCredentialsProvider failed due to invalid credential type”)}}(e.credentials))}_getSettings(){return this._settings}_getEmulatorOptions(){return this._emulatorOptions}_freezeSettings(){return this._settingsFrozen=!0,this._settings}_delete(){return”notTerminated”===this._terminateTask&&(this._terminateTask=this._terminate()),this._terminateTask}async _restart(){“notTerminated”===this._terminateTask?await this._terminate():this._terminateTask=”notTerminated”}toJSON(){return{app:this._app,databaseId:this._databaseId,settings:this._settings}}_terminate(){return function __PRIVATE_removeComponents(e){const i=bn.get(e);i&&(__PRIVATE_logDebug(“ComponentProvider”,”Removing Datastore”),bn.delete(e),i.terminate())}(this),Promise.resolve()}}function connectFirestoreEmulator(e,i,s,o={}){var _;const h=(e=__PRIVATE_cast(e,Firestore$1))._getSettings(),d=Object.assign(Object.assign({},h),{emulatorOptions:e._getEmulatorOptions()}),f=`${i}:${s}`;h.host!==Sn&&h.host!==f&&__PRIVATE_logWarn(“Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used.”);const g=Object.assign(Object.assign({},h),{host:f,ssl:!1,emulatorOptions:o});if(!deepEqual(g,d)&&(e._setSettings(g),o.mockUserToken)){let i,s;if(“string”==typeof o.mockUserToken)i=o.mockUserToken,s=User.MOCK_USER;else{i=function createMockUserToken(e,i){if(e.uid)throw new Error(‘The “uid” field is no longer supported by mockUserToken. Please use “sub” instead for Firebase Auth User ID.’);const s=i||”demo-project”,o=e.iat||0,_=e.sub||e.user_id;if(!_)throw new Error(“mockUserToken must contain ‘sub’ or ‘user_id’ field!”);const h=Object.assign({iss:`https://securetoken.google.com/${s}`,aud:s,iat:o,exp:o+3600,auth_time:o,sub:_,user_id:_,firebase:{sign_in_provider:”custom”,identities:{}}},e);return[base64urlEncodeWithoutPadding(JSON.stringify({alg:”none”,type:”JWT”})),base64urlEncodeWithoutPadding(JSON.stringify(h)),””].join(“.”)}(o.mockUserToken,null===(_=e._app)||void 0===_?void 0:_.options.projectId);const h=o.mockUserToken.sub||o.mockUserToken.user_id;if(!h)throw new FirestoreError(de.INVALID_ARGUMENT,”mockUserToken must contain ‘sub’ or ‘user_id’ field!”);s=new User(h)}e._authCredentials=new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(i,s))}}class Query{constructor(e,i,s){this.converter=i,this._query=s,this.type=”query”,this.firestore=e}withConverter(e){return new Query(this.firestore,e,this._query)}}class DocumentReference{constructor(e,i,s){this.converter=i,this._key=s,this.type=”document”,this.firestore=e}get _path(){return this._key.path}get id(){return this._key.path.lastSegment()}get path(){return this._key.path.canonicalString()}get parent(){return new CollectionReference(this.firestore,this.converter,this._key.path.popLast())}withConverter(e){return new DocumentReference(this.firestore,e,this._key)}}class CollectionReference extends Query{constructor(e,i,s){super(e,i,__PRIVATE_newQueryForPath(s)),this._path=s,this.type=”collection”}get id(){return this._query.path.lastSegment()}get path(){return this._query.path.canonicalString()}get parent(){const e=this._path.popLast();return e.isEmpty()?null:new DocumentReference(this.firestore,null,new DocumentKey(e))}withConverter(e){return new CollectionReference(this.firestore,e,this._path)}}function collection(e,i,…s){if(e=getModularInstance(e),__PRIVATE_validateNonEmptyArgument(“collection”,”path”,i),e instanceof Firestore$1){const o=ResourcePath.fromString(i,…s);return __PRIVATE_validateCollectionPath(o),new CollectionReference(e,null,o)}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(de.INVALID_ARGUMENT,”Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore”);const o=e._path.child(ResourcePath.fromString(i,…s));return __PRIVATE_validateCollectionPath(o),new CollectionReference(e.firestore,null,o)}}function collectionGroup(e,i){if(e=__PRIVATE_cast(e,Firestore$1),__PRIVATE_validateNonEmptyArgument(“collectionGroup”,”collection id”,i),i.indexOf(“/”)>=0)throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid collection ID ‘${i}’ passed to function collectionGroup(). Collection IDs must not contain ‘/’.`);return new Query(e,null,function __PRIVATE_newQueryForCollectionGroup(e){return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(),e)}(i))}function doc(e,i,…s){if(e=getModularInstance(e),1===arguments.length&&(i=__PRIVATE_AutoId.newId()),__PRIVATE_validateNonEmptyArgument(“doc”,”path”,i),e instanceof Firestore$1){const o=ResourcePath.fromString(i,…s);return __PRIVATE_validateDocumentPath(o),new DocumentReference(e,null,new DocumentKey(o))}{if(!(e instanceof DocumentReference||e instanceof CollectionReference))throw new FirestoreError(de.INVALID_ARGUMENT,”Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore”);const o=e._path.child(ResourcePath.fromString(i,…s));return __PRIVATE_validateDocumentPath(o),new DocumentReference(e.firestore,e instanceof CollectionReference?e.converter:null,new DocumentKey(o))}}function refEqual(e,i){return e=getModularInstance(e),i=getModularInstance(i),(e instanceof DocumentReference||e instanceof CollectionReference)&&(i instanceof DocumentReference||i instanceof CollectionReference)&&e.firestore===i.firestore&&e.path===i.path&&e.converter===i.converter}function queryEqual(e,i){return e=getModularInstance(e),i=getModularInstance(i),e instanceof Query&&i instanceof Query&&e.firestore===i.firestore&&__PRIVATE_queryEquals(e._query,i._query)&&e.converter===i.converter}const Dn=”AsyncQueue”;class __PRIVATE_AsyncQueueImpl{constructor(e=Promise.resolve()){this.Qu=[],this.$u=!1,this.Uu=[],this.Ku=null,this.Wu=!1,this.Gu=!1,this.zu=[],this.y_=new __PRIVATE_ExponentialBackoff(this,”async_queue_retry”),this.ju=()=>{const e=getDocument();e&&__PRIVATE_logDebug(Dn,”Visibility state changed to “+e.visibilityState),this.y_.A_()},this.Hu=e;const i=getDocument();i&&”function”==typeof i.addEventListener&&i.addEventListener(“visibilitychange”,this.ju)}get isShuttingDown(){return this.$u}enqueueAndForget(e){this.enqueue(e)}enqueueAndForgetEvenWhileRestricted(e){this.Ju(),this.Yu(e)}enterRestrictedMode(e){if(!this.$u){this.$u=!0,this.Gu=e||!1;const i=getDocument();i&&”function”==typeof i.removeEventListener&&i.removeEventListener(“visibilitychange”,this.ju)}}enqueue(e){if(this.Ju(),this.$u)return new Promise((()=>{}));const i=new __PRIVATE_Deferred;return this.Yu((()=>this.$u&&this.Gu?Promise.resolve():(e().then(i.resolve,i.reject),i.promise))).then((()=>i.promise))}enqueueRetryable(e){this.enqueueAndForget((()=>(this.Qu.push(e),this.Zu())))}async Zu(){if(0!==this.Qu.length){try{await this.Qu[0](),this.Qu.shift(),this.y_.reset()}catch(e){if(!__PRIVATE_isIndexedDbTransactionError(e))throw e;__PRIVATE_logDebug(Dn,”Operation failed with retryable error: “+e)}this.Qu.length>0&&this.y_.E_((()=>this.Zu()))}}Yu(e){const i=this.Hu.then((()=>(this.Wu=!0,e().catch((e=>{throw this.Ku=e,this.Wu=!1,__PRIVATE_logError(“INTERNAL UNHANDLED ERROR: “,__PRIVATE_getMessageOrStack(e)),e})).then((e=>(this.Wu=!1,e))))));return this.Hu=i,i}enqueueAfterDelay(e,i,s){this.Ju(),this.zu.indexOf(e)>-1&&(i=0);const o=DelayedOperation.createAndSchedule(this,e,i,s,(e=>this.Xu(e)));return this.Uu.push(o),o}Ju(){this.Ku&&fail(47125,{ec:__PRIVATE_getMessageOrStack(this.Ku)})}verifyOperationInProgress(){}async tc(){let e;do{e=this.Hu,await e}while(e!==this.Hu)}nc(e){for(const i of this.Uu)if(i.timerId===e)return!0;return!1}rc(e){return this.tc().then((()=>{this.Uu.sort(((e,i)=>e.targetTimeMs-i.targetTimeMs));for(const i of this.Uu)if(i.skipDelay(),”all”!==e&&i.timerId===e)break;return this.tc()}))}sc(e){this.zu.push(e)}Xu(e){const i=this.Uu.indexOf(e);this.Uu.splice(i,1)}}function __PRIVATE_getMessageOrStack(e){let i=e.message||””;return e.stack&&(i=e.stack.includes(e.message)?e.stack:e.message+”\n”+e.stack),i}function __PRIVATE_isPartialObserver(e){return function __PRIVATE_implementsAnyMethods(e,i){if(“object”!=typeof e||null===e)return!1;const s=e;for(const e of i)if(e in s&&”function”==typeof s[e])return!0;return!1}(e,[“next”,”error”,”complete”])}class LoadBundleTask{constructor(){this._progressObserver={},this._taskCompletionResolver=new __PRIVATE_Deferred,this._lastProgress={taskState:”Running”,totalBytes:0,totalDocuments:0,bytesLoaded:0,documentsLoaded:0}}onProgress(e,i,s){this._progressObserver={next:e,error:i,complete:s}}catch(e){return this._taskCompletionResolver.promise.catch(e)}then(e,i){return this._taskCompletionResolver.promise.then(e,i)}_completeWith(e){this._updateProgress(e),this._progressObserver.complete&&this._progressObserver.complete(),this._taskCompletionResolver.resolve(e)}_failWith(e){this._lastProgress.taskState=”Error”,this._progressObserver.next&&this._progressObserver.next(this._lastProgress),this._progressObserver.error&&this._progressObserver.error(e),this._taskCompletionResolver.reject(e)}_updateProgress(e){this._lastProgress=e,this._progressObserver.next&&this._progressObserver.next(e)}}const Cn=-1;class Firestore extends Firestore$1{constructor(e,i,s,o){super(e,i,s,o),this.type=”firestore”,this._queue=new __PRIVATE_AsyncQueueImpl,this._persistenceKey=(null==o?void 0:o.name)||”[DEFAULT]”}async _terminate(){if(this._firestoreClient){const e=this._firestoreClient.terminate();this._queue=new __PRIVATE_AsyncQueueImpl(e),this._firestoreClient=void 0,await e}}}function initializeFirestore(e,i,s){s||(s=Ft);const o=_getProvider(e,”firestore”);if(o.isInitialized(s)){const e=o.getImmediate({identifier:s});if(deepEqual(o.getOptions(s),i))return e;throw new FirestoreError(de.FAILED_PRECONDITION,”initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.”)}if(void 0!==i.cacheSizeBytes&&void 0!==i.localCache)throw new FirestoreError(de.INVALID_ARGUMENT,”cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object”);if(void 0!==i.cacheSizeBytes&&-1!==i.cacheSizeBytes&&i.cacheSizeBytesnew __PRIVATE_IndexedDbOfflineComponentProvider(e,s.cacheSizeBytes,null==i?void 0:i.forceOwnership)}),Promise.resolve()}async function enableMultiTabIndexedDbPersistence(e){__PRIVATE_logWarn(“enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead.”);const i=e._freezeSettings();__PRIVATE_setPersistenceProviders(e,OnlineComponentProvider.provider,{build:e=>new __PRIVATE_MultiTabOfflineComponentProvider(e,i.cacheSizeBytes)})}function __PRIVATE_setPersistenceProviders(e,i,s){if((e=__PRIVATE_cast(e,Firestore))._firestoreClient||e._terminated)throw new FirestoreError(de.FAILED_PRECONDITION,”Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.”);if(e._componentsProvider||e._getSettings().localCache)throw new FirestoreError(de.FAILED_PRECONDITION,”SDK cache is already specified.”);e._componentsProvider={_online:i,_offline:s},__PRIVATE_configureFirestore(e)}function clearIndexedDbPersistence(e){if(e._initialized&&!e._terminated)throw new FirestoreError(de.FAILED_PRECONDITION,”Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.”);const i=new __PRIVATE_Deferred;return e._queue.enqueueAndForgetEvenWhileRestricted((async()=>{try{await async function __PRIVATE_indexedDbClearPersistence(e){if(!__PRIVATE_SimpleDb.C())return Promise.resolve();const i=e+ln;await __PRIVATE_SimpleDb.delete(i)}(__PRIVATE_indexedDbStoragePrefix(e._databaseId,e._persistenceKey)),i.resolve()}catch(e){i.reject(e)}})),i.promise}function waitForPendingWrites(e){return function __PRIVATE_firestoreClientWaitForPendingWrites(e){const i=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e,i){const s=__PRIVATE_debugCast(e);__PRIVATE_canUseNetwork(s.remoteStore)||__PRIVATE_logDebug(Vn,”The network is disabled. The task returned by ‘awaitPendingWrites()’ will not complete until the network is enabled.”);try{const e=await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e){const i=__PRIVATE_debugCast(e);return i.persistence.runTransaction(“Get highest unacknowledged batch id”,”readonly”,(e=>i.mutationQueue.getHighestUnacknowledgedBatchId(e)))}(s.localStore);if(e===Re)return void i.resolve();const o=s.cu.get(e)||[];o.push(i),s.cu.set(e,o)}catch(e){const s=__PRIVATE_wrapInUserErrorIfRecoverable(e,”Initialization of waitForPendingWrites() operation failed”);i.reject(s)}}(await __PRIVATE_getSyncEngine(e),i))),i.promise}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)))}function enableNetwork(e){return function __PRIVATE_firestoreClientEnableNetwork(e){return e.asyncQueue.enqueue((async()=>{const i=await __PRIVATE_getPersistence(e),s=await __PRIVATE_getRemoteStore(e);return i.setNetworkEnabled(!0),function __PRIVATE_remoteStoreEnableNetwork(e){const i=__PRIVATE_debugCast(e);return i.aa.delete(0),__PRIVATE_enableNetworkInternal(i)}(s)}))}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)))}function disableNetwork(e){return function __PRIVATE_firestoreClientDisableNetwork(e){return e.asyncQueue.enqueue((async()=>{const i=await __PRIVATE_getPersistence(e),s=await __PRIVATE_getRemoteStore(e);return i.setNetworkEnabled(!1),async function __PRIVATE_remoteStoreDisableNetwork(e){const i=__PRIVATE_debugCast(e);i.aa.add(0),await __PRIVATE_disableNetworkInternal(i),i.la.set(“Offline”)}(s)}))}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)))}function terminate(e){return _(e.app,”firestore”,e._databaseId.database),e._delete()}function loadBundle(e,i){const s=ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),o=new LoadBundleTask;return __PRIVATE_firestoreClientLoadBundle(s,e._databaseId,i,o),o}function namedQuery(e,i){return function __PRIVATE_firestoreClientGetNamedQuery(e,i){return e.asyncQueue.enqueue((async()=>function __PRIVATE_localStoreGetNamedQuery(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction(“Get named query”,”readonly”,(e=>s.ci.getNamedQuery(e,i)))}(await __PRIVATE_getLocalStore(e),i)))}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),i).then((i=>i?new Query(e,null,i.query):null))}class AggregateField{constructor(e=”count”,i){this._internalFieldPath=i,this.type=”AggregateField”,this.aggregateType=e}}class AggregateQuerySnapshot{constructor(e,i,s){this._userDataWriter=i,this._data=s,this.type=”AggregateQuerySnapshot”,this.query=e}data(){return this._userDataWriter.convertObjectMap(this._data)}}class Bytes{constructor(e){this._byteString=e}static fromBase64String(e){try{return new Bytes(ByteString.fromBase64String(e))}catch(e){throw new FirestoreError(de.INVALID_ARGUMENT,”Failed to construct data from Base64 string: “+e)}}static fromUint8Array(e){return new Bytes(ByteString.fromUint8Array(e))}toBase64(){return this._byteString.toBase64()}toUint8Array(){return this._byteString.toUint8Array()}toString(){return”Bytes(base64: “+this.toBase64()+”)”}isEqual(e){return this._byteString.isEqual(e._byteString)}}class FieldPath{constructor(…e){for(let i=0;i90)throw new FirestoreError(de.INVALID_ARGUMENT,”Latitude must be a number between -90 and 90, but was: “+e);if(!isFinite(i)||i<-180||i>180)throw new FirestoreError(de.INVALID_ARGUMENT,”Longitude must be a number between -180 and 180, but was: “+i);this._lat=e,this._long=i}get latitude(){return this._lat}get longitude(){return this._long}isEqual(e){return this._lat===e._lat&&this._long===e._long}toJSON(){return{latitude:this._lat,longitude:this._long}}_compareTo(e){return __PRIVATE_primitiveComparator(this._lat,e._lat)||__PRIVATE_primitiveComparator(this._long,e._long)}}class VectorValue{constructor(e){this._values=(e||[]).map((e=>e))}toArray(){return this._values.map((e=>e))}isEqual(e){return function __PRIVATE_isPrimitiveArrayEqual(e,i){if(e.length!==i.length)return!1;for(let s=0;se.isPrefixOf(i)))||void 0!==this.fieldTransforms.find((i=>e.isPrefixOf(i.field)))}_c(){if(this.path)for(let e=0;eg.covers(e.field)))}else g=null,b=d.fieldTransforms;return new ParsedSetData(new ObjectValue(f),g,b)}class __PRIVATE_DeleteFieldValueImpl extends FieldValue{_toFieldTransform(e){if(2!==e.oc)throw 1===e.oc?e.Tc(`${this._methodName}() can only appear at the top level of your update data`):e.Tc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);return e.fieldMask.push(e.path),null}isEqual(e){return e instanceof __PRIVATE_DeleteFieldValueImpl}}function __PRIVATE_createSentinelChildContext(e,i,s){return new __PRIVATE_ParseContextImpl({oc:3,Ec:i.settings.Ec,methodName:e._methodName,cc:s},i.databaseId,i.serializer,i.ignoreUndefinedProperties)}class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue{_toFieldTransform(e){return new FieldTransform(e.path,new __PRIVATE_ServerTimestampTransform)}isEqual(e){return e instanceof __PRIVATE_ServerTimestampFieldValueImpl}}class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Ac=i}_toFieldTransform(e){const i=__PRIVATE_createSentinelChildContext(this,e,!0),s=this.Ac.map((e=>__PRIVATE_parseData(e,i))),o=new __PRIVATE_ArrayUnionTransformOperation(s);return new FieldTransform(e.path,o)}isEqual(e){return e instanceof __PRIVATE_ArrayUnionFieldValueImpl&&deepEqual(this.Ac,e.Ac)}}class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Ac=i}_toFieldTransform(e){const i=__PRIVATE_createSentinelChildContext(this,e,!0),s=this.Ac.map((e=>__PRIVATE_parseData(e,i))),o=new __PRIVATE_ArrayRemoveTransformOperation(s);return new FieldTransform(e.path,o)}isEqual(e){return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl&&deepEqual(this.Ac,e.Ac)}}class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue{constructor(e,i){super(e),this.Rc=i}_toFieldTransform(e){const i=new __PRIVATE_NumericIncrementTransformOperation(e.serializer,toNumber(e.serializer,this.Rc));return new FieldTransform(e.path,i)}isEqual(e){return e instanceof __PRIVATE_NumericIncrementFieldValueImpl&&this.Rc===e.Rc}}function __PRIVATE_parseUpdateData(e,i,s,o){const _=e.dc(1,i,s);__PRIVATE_validatePlainObject(“Data must be an object, but it was:”,_,o);const h=[],d=ObjectValue.empty();forEach(o,((e,o)=>{const f=__PRIVATE_fieldPathFromDotSeparatedString(i,e,s);o=getModularInstance(o);const g=_.hc(f);if(o instanceof __PRIVATE_DeleteFieldValueImpl)h.push(f);else{const e=__PRIVATE_parseData(o,g);null!=e&&(h.push(f),d.set(f,e))}}));const f=new FieldMask(h);return new ParsedUpdateData(d,f,_.fieldTransforms)}function __PRIVATE_parseUpdateVarargs(e,i,s,o,_,h){const d=e.dc(1,i,s),f=[__PRIVATE_fieldPathFromArgument$1(i,o,s)],g=[_];if(h.length%2!=0)throw new FirestoreError(de.INVALID_ARGUMENT,`Function ${i}() needs to be called with an even number of arguments that alternate between field names and values.`);for(let e=0;e=0;–e)if(!__PRIVATE_fieldMaskContains(b,f[e])){const i=f[e];let s=g[e];s=getModularInstance(s);const o=d.hc(i);if(s instanceof __PRIVATE_DeleteFieldValueImpl)b.push(i);else{const e=__PRIVATE_parseData(s,o);null!=e&&(b.push(i),w.set(i,e))}}const O=new FieldMask(b);return new ParsedUpdateData(w,O,d.fieldTransforms)}function __PRIVATE_parseQueryValue(e,i,s,o=!1){return __PRIVATE_parseData(s,e.dc(o?4:3,i))}function __PRIVATE_parseData(e,i){if(__PRIVATE_looksLikeJsonObject(e=getModularInstance(e)))return __PRIVATE_validatePlainObject(“Unsupported field value:”,i,e),__PRIVATE_parseObject(e,i);if(e instanceof FieldValue)return function __PRIVATE_parseSentinelFieldValue(e,i){if(!__PRIVATE_isWrite(i.oc))throw i.Tc(`${e._methodName}() can only be used with update() and set()`);if(!i.path)throw i.Tc(`${e._methodName}() is not currently supported inside arrays`);const s=e._toFieldTransform(i);s&&i.fieldTransforms.push(s)}(e,i),null;if(void 0===e&&i.ignoreUndefinedProperties)return null;if(i.path&&i.fieldMask.push(i.path),e instanceof Array){if(i.settings.cc&&4!==i.oc)throw i.Tc(“Nested arrays are not supported”);return function __PRIVATE_parseArray(e,i){const s=[];let o=0;for(const _ of e){let e=__PRIVATE_parseData(_,i.Pc(o));null==e&&(e={nullValue:”NULL_VALUE”}),s.push(e),o++}return{arrayValue:{values:s}}}(e,i)}return function __PRIVATE_parseScalarValue(e,i){if(null===(e=getModularInstance(e)))return{nullValue:”NULL_VALUE”};if(“number”==typeof e)return toNumber(i.serializer,e);if(“boolean”==typeof e)return{booleanValue:e};if(“string”==typeof e)return{stringValue:e};if(e instanceof Date){const s=Timestamp.fromDate(e);return{timestampValue:toTimestamp(i.serializer,s)}}if(e instanceof Timestamp){const s=new Timestamp(e.seconds,1e3*Math.floor(e.nanoseconds/1e3));return{timestampValue:toTimestamp(i.serializer,s)}}if(e instanceof GeoPoint)return{geoPointValue:{latitude:e.latitude,longitude:e.longitude}};if(e instanceof Bytes)return{bytesValue:__PRIVATE_toBytes(i.serializer,e._byteString)};if(e instanceof DocumentReference){const s=i.databaseId,o=e.firestore._databaseId;if(!o.isEqual(s))throw i.Tc(`Document reference is for database ${o.projectId}/${o.database} but should be for database ${s.projectId}/${s.database}`);return{referenceValue:__PRIVATE_toResourceName(e.firestore._databaseId||i.databaseId,e._key.path)}}if(e instanceof VectorValue)return function __PRIVATE_parseVectorValue(e,i){return{mapValue:{fields:{[xt]:{stringValue:kt},[Ot]:{arrayValue:{values:e.toArray().map((e=>{if(“number”!=typeof e)throw i.Tc(“VectorValues must only contain numeric values.”);return __PRIVATE_toDouble(i.serializer,e)}))}}}}}}(e,i);throw i.Tc(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`)}(e,i)}function __PRIVATE_parseObject(e,i){const s={};return isEmpty(e)?i.path&&i.path.length>0&&i.fieldMask.push(i.path):forEach(e,((e,o)=>{const _=__PRIVATE_parseData(o,i.uc(e));null!=_&&(s[e]=_)})),{mapValue:{fields:s}}}function __PRIVATE_looksLikeJsonObject(e){return!(“object”!=typeof e||null===e||e instanceof Array||e instanceof Date||e instanceof Timestamp||e instanceof GeoPoint||e instanceof Bytes||e instanceof DocumentReference||e instanceof FieldValue||e instanceof VectorValue)}function __PRIVATE_validatePlainObject(e,i,s){if(!__PRIVATE_looksLikeJsonObject(s)||!function __PRIVATE_isPlainObject(e){return”object”==typeof e&&null!==e&&(Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e))}(s)){const o=__PRIVATE_valueDescription(s);throw”an object”===o?i.Tc(e+” a custom object”):i.Tc(e+” “+o)}}function __PRIVATE_fieldPathFromArgument$1(e,i,s){if((i=getModularInstance(i))instanceof FieldPath)return i._internalPath;if(“string”==typeof i)return __PRIVATE_fieldPathFromDotSeparatedString(e,i);throw __PRIVATE_createError(“Field path arguments must be of type string or “,e,!1,void 0,s)}const xn=new RegExp(“[~\\*/\\[\\]]”);function __PRIVATE_fieldPathFromDotSeparatedString(e,i,s){if(i.search(xn)>=0)throw __PRIVATE_createError(`Invalid field path (${i}). Paths must not contain ‘~’, ‘*’, ‘/’, ‘[‘, or ‘]’`,e,!1,void 0,s);try{return new FieldPath(…i.split(“.”))._internalPath}catch(o){throw __PRIVATE_createError(`Invalid field path (${i}). Paths must not be empty, begin with ‘.’, end with ‘.’, or contain ‘..’`,e,!1,void 0,s)}}function __PRIVATE_createError(e,i,s,o,_){const h=o&&!o.isEmpty(),d=void 0!==_;let f=`Function ${i}() called with invalid data`;s&&(f+=” (via `toFirestore()`)”),f+=”. “;let g=””;return(h||d)&&(g+=” (found”,h&&(g+=` in field ${o}`),d&&(g+=` in document ${_}`),g+=”)”),new FirestoreError(de.INVALID_ARGUMENT,f+e+g)}function __PRIVATE_fieldMaskContains(e,i){return e.some((e=>e.isEqual(i)))}class DocumentSnapshot$1{constructor(e,i,s,o,_){this._firestore=e,this._userDataWriter=i,this._key=s,this._document=o,this._converter=_}get id(){return this._key.path.lastSegment()}get ref(){return new DocumentReference(this._firestore,this._converter,this._key)}exists(){return null!==this._document}data(){if(this._document){if(this._converter){const e=new QueryDocumentSnapshot$1(this._firestore,this._userDataWriter,this._key,this._document,null);return this._converter.fromFirestore(e)}return this._userDataWriter.convertValue(this._document.data.value)}}get(e){if(this._document){const i=this._document.data.field(__PRIVATE_fieldPathFromArgument(“DocumentSnapshot.get”,e));if(null!==i)return this._userDataWriter.convertValue(i)}}}class QueryDocumentSnapshot$1 extends DocumentSnapshot$1{data(){return super.data()}}function __PRIVATE_fieldPathFromArgument(e,i){return”string”==typeof i?__PRIVATE_fieldPathFromDotSeparatedString(e,i):i instanceof FieldPath?i._internalPath:i._delegate._internalPath}function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e){if(“L”===e.limitType&&0===e.explicitOrderBy.length)throw new FirestoreError(de.UNIMPLEMENTED,”limitToLast() queries require specifying at least one orderBy() clause”)}class AppliableConstraint{}class QueryConstraint extends AppliableConstraint{}function query(e,i,…s){let o=[];i instanceof AppliableConstraint&&o.push(i),o=o.concat(s),function __PRIVATE_validateQueryConstraintArray(e){const i=e.filter((e=>e instanceof QueryCompositeFilterConstraint)).length,s=e.filter((e=>e instanceof QueryFieldFilterConstraint)).length;if(i>1||i>0&&s>0)throw new FirestoreError(de.INVALID_ARGUMENT,”InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(…)` statement. For example: change `query(query, where(…), or(…))` to `query(query, and(where(…), or(…)))`.”)}(o);for(const i of o)e=i._apply(e);return e}class QueryFieldFilterConstraint extends QueryConstraint{constructor(e,i,s){super(),this._field=e,this._op=i,this._value=s,this.type=”where”}static _create(e,i,s){return new QueryFieldFilterConstraint(e,i,s)}_apply(e){const i=this._parse(e);return __PRIVATE_validateNewFieldFilter(e._query,i),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,i))}_parse(e){const i=__PRIVATE_newUserDataReader(e.firestore),s=function __PRIVATE_newQueryFilter(e,i,s,o,_,h,d){let f;if(_.isKeyField()){if(“array-contains”===h||”array-contains-any”===h)throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid Query. You can’t perform ‘${h}’ queries on documentId().`);if(“in”===h||”not-in”===h){__PRIVATE_validateDisjunctiveFilterElements(d,h);const i=[];for(const s of d)i.push(__PRIVATE_parseDocumentIdValue(o,e,s));f={arrayValue:{values:i}}}else f=__PRIVATE_parseDocumentIdValue(o,e,d)}else”in”!==h&&”not-in”!==h&&”array-contains-any”!==h||__PRIVATE_validateDisjunctiveFilterElements(d,h),f=__PRIVATE_parseQueryValue(s,i,d,”in”===h||”not-in”===h);return FieldFilter.create(_,h,f)}(e._query,”where”,i,e.firestore._databaseId,this._field,this._op,this._value);return s}}function where(e,i,s){const o=i,_=__PRIVATE_fieldPathFromArgument(“where”,e);return QueryFieldFilterConstraint._create(_,o,s)}class QueryCompositeFilterConstraint extends AppliableConstraint{constructor(e,i){super(),this.type=e,this._queryConstraints=i}static _create(e,i){return new QueryCompositeFilterConstraint(e,i)}_parse(e){const i=this._queryConstraints.map((i=>i._parse(e))).filter((e=>e.getFilters().length>0));return 1===i.length?i[0]:CompositeFilter.create(i,this._getOperator())}_apply(e){const i=this._parse(e);return 0===i.getFilters().length?e:(function __PRIVATE_validateNewFilter(e,i){let s=e;const o=i.getFlattenedFilters();for(const e of o)__PRIVATE_validateNewFieldFilter(s,e),s=__PRIVATE_queryWithAddedFilter(s,e)}(e._query,i),new Query(e.firestore,e.converter,__PRIVATE_queryWithAddedFilter(e._query,i)))}_getQueryConstraints(){return this._queryConstraints}_getOperator(){return”and”===this.type?”and”:”or”}}function or(…e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint(“or”,e))),QueryCompositeFilterConstraint._create(“or”,e)}function and(…e){return e.forEach((e=>__PRIVATE_validateQueryFilterConstraint(“and”,e))),QueryCompositeFilterConstraint._create(“and”,e)}class QueryOrderByConstraint extends QueryConstraint{constructor(e,i){super(),this._field=e,this._direction=i,this.type=”orderBy”}static _create(e,i){return new QueryOrderByConstraint(e,i)}_apply(e){const i=function __PRIVATE_newQueryOrderBy(e,i,s){if(null!==e.startAt)throw new FirestoreError(de.INVALID_ARGUMENT,”Invalid query. You must not call startAt() or startAfter() before calling orderBy().”);if(null!==e.endAt)throw new FirestoreError(de.INVALID_ARGUMENT,”Invalid query. You must not call endAt() or endBefore() before calling orderBy().”);return new OrderBy(i,s)}(e._query,this._field,this._direction);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithAddedOrderBy(e,i){const s=e.explicitOrderBy.concat([i]);return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,s,e.filters.slice(),e.limit,e.limitType,e.startAt,e.endAt)}(e._query,i))}}function orderBy(e,i=”asc”){const s=i,o=__PRIVATE_fieldPathFromArgument(“orderBy”,e);return QueryOrderByConstraint._create(o,s)}class QueryLimitConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._limit=i,this._limitType=s}static _create(e,i,s){return new QueryLimitConstraint(e,i,s)}_apply(e){return new Query(e.firestore,e.converter,__PRIVATE_queryWithLimit(e._query,this._limit,this._limitType))}}function limit(e){return __PRIVATE_validatePositiveNumber(“limit”,e),QueryLimitConstraint._create(“limit”,e,”F”)}function limitToLast(e){return __PRIVATE_validatePositiveNumber(“limitToLast”,e),QueryLimitConstraint._create(“limitToLast”,e,”L”)}class QueryStartAtConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._docOrFields=i,this._inclusive=s}static _create(e,i,s){return new QueryStartAtConstraint(e,i,s)}_apply(e){const i=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithStartAt(e,i){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,i,e.endAt)}(e._query,i))}}function startAt(…e){return QueryStartAtConstraint._create(“startAt”,e,!0)}function startAfter(…e){return QueryStartAtConstraint._create(“startAfter”,e,!1)}class QueryEndAtConstraint extends QueryConstraint{constructor(e,i,s){super(),this.type=e,this._docOrFields=i,this._inclusive=s}static _create(e,i,s){return new QueryEndAtConstraint(e,i,s)}_apply(e){const i=__PRIVATE_newQueryBoundFromDocOrFields(e,this.type,this._docOrFields,this._inclusive);return new Query(e.firestore,e.converter,function __PRIVATE_queryWithEndAt(e,i){return new __PRIVATE_QueryImpl(e.path,e.collectionGroup,e.explicitOrderBy.slice(),e.filters.slice(),e.limit,e.limitType,e.startAt,i)}(e._query,i))}}function endBefore(…e){return QueryEndAtConstraint._create(“endBefore”,e,!1)}function endAt(…e){return QueryEndAtConstraint._create(“endAt”,e,!0)}function __PRIVATE_newQueryBoundFromDocOrFields(e,i,s,o){if(s[0]=getModularInstance(s[0]),s[0]instanceof DocumentSnapshot$1)return function __PRIVATE_newQueryBoundFromDocument(e,i,s,o,_){if(!o)throw new FirestoreError(de.NOT_FOUND,`Can’t use a DocumentSnapshot that doesn’t exist for ${s}().`);const h=[];for(const s of __PRIVATE_queryNormalizedOrderBy(e))if(s.field.isKeyField())h.push(__PRIVATE_refValue(i,o.key));else{const e=o.data.field(s.field);if(__PRIVATE_isServerTimestamp(e))throw new FirestoreError(de.INVALID_ARGUMENT,’Invalid query. You are trying to start or end a query using a document for which the field “‘+s.field+'” is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)’);if(null===e){const e=s.field.canonicalString();throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. You are trying to start or end a query using a document for which the field ‘${e}’ (used as the orderBy) does not exist.`)}h.push(e)}return new Bound(h,_)}(e._query,e.firestore._databaseId,i,s[0]._document,o);{const _=__PRIVATE_newUserDataReader(e.firestore);return function __PRIVATE_newQueryBoundFromFields(e,i,s,o,_,h){const d=e.explicitOrderBy;if(_.length>d.length)throw new FirestoreError(de.INVALID_ARGUMENT,`Too many arguments provided to ${o}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);const f=[];for(let h=0;h<_.length;h++){const g=_[h];if(d[h].field.isKeyField()){if("string"!=typeof g)throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. Expected a string for document ID in ${o}(), but got a ${typeof g}`);if(!__PRIVATE_isCollectionGroupQuery(e)&&-1!==g.indexOf("/"))throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. When querying a collection and ordering by documentId(), the value passed to ${o}() must be a plain document ID, but '${g}' contains a slash.`);const s=e.path.child(ResourcePath.fromString(g));if(!DocumentKey.isDocumentKey(s))throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${o}() must result in a valid document path, but '${s}' is not because it contains an odd number of segments.`);const _=new DocumentKey(s);f.push(__PRIVATE_refValue(i,_))}else{const e=__PRIVATE_parseQueryValue(s,o,g);f.push(e)}}return new Bound(f,h)}(e._query,e.firestore._databaseId,_,i,s,o)}}function __PRIVATE_parseDocumentIdValue(e,i,s){if("string"==typeof(s=getModularInstance(s))){if(""===s)throw new FirestoreError(de.INVALID_ARGUMENT,"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.");if(!__PRIVATE_isCollectionGroupQuery(i)&&-1!==s.indexOf("/"))throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${s}' contains a '/' character.`);const o=i.path.child(ResourcePath.fromString(s));if(!DocumentKey.isDocumentKey(o))throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${o}' is not because it has an odd number of segments (${o.length}).`);return __PRIVATE_refValue(e,new DocumentKey(o))}if(s instanceof DocumentReference)return __PRIVATE_refValue(e,s._key);throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(s)}.`)}function __PRIVATE_validateDisjunctiveFilterElements(e,i){if(!Array.isArray(e)||0===e.length)throw new FirestoreError(de.INVALID_ARGUMENT,`Invalid Query. A non-empty array is required for '${i.toString()}' filters.`)}function __PRIVATE_validateNewFieldFilter(e,i){const s=function __PRIVATE_findOpInsideFilters(e,i){for(const s of e)for(const e of s.getFlattenedFilters())if(i.indexOf(e.op)>=0)return e.op;return null}(e.filters,function __PRIVATE_conflictingOps(e){switch(e){case”!=”:return[“!=”,”not-in”];case”array-contains-any”:case”in”:return[“not-in”];case”not-in”:return[“array-contains-any”,”in”,”not-in”,”!=”];default:return[]}}(i.op));if(null!==s)throw s===i.op?new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. You cannot use more than one ‘${i.op.toString()}’ filter.`):new FirestoreError(de.INVALID_ARGUMENT,`Invalid query. You cannot use ‘${i.op.toString()}’ filters with ‘${s.toString()}’ filters.`)}function __PRIVATE_validateQueryFilterConstraint(e,i){if(!(i instanceof QueryFieldFilterConstraint||i instanceof QueryCompositeFilterConstraint))throw new FirestoreError(de.INVALID_ARGUMENT,`Function ${e}() requires AppliableConstraints created with a call to ‘where(…)’, ‘or(…)’, or ‘and(…)’.`)}class AbstractUserDataWriter{convertValue(e,i=”none”){switch(__PRIVATE_typeOrder(e)){case 0:return null;case 1:return e.booleanValue;case 2:return __PRIVATE_normalizeNumber(e.integerValue||e.doubleValue);case 3:return this.convertTimestamp(e.timestampValue);case 4:return this.convertServerTimestamp(e,i);case 5:return e.stringValue;case 6:return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue));case 7:return this.convertReference(e.referenceValue);case 8:return this.convertGeoPoint(e.geoPointValue);case 9:return this.convertArray(e.arrayValue,i);case 11:return this.convertObject(e.mapValue,i);case 10:return this.convertVectorValue(e.mapValue);default:throw fail(62114,{value:e})}}convertObject(e,i){return this.convertObjectMap(e.fields,i)}convertObjectMap(e,i=”none”){const s={};return forEach(e,((e,o)=>{s[e]=this.convertValue(o,i)})),s}convertVectorValue(e){var i,s,o;const _=null===(o=null===(s=null===(i=e.fields)||void 0===i?void 0:i[Ot].arrayValue)||void 0===s?void 0:s.values)||void 0===o?void 0:o.map((e=>__PRIVATE_normalizeNumber(e.doubleValue)));return new VectorValue(_)}convertGeoPoint(e){return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude),__PRIVATE_normalizeNumber(e.longitude))}convertArray(e,i){return(e.values||[]).map((e=>this.convertValue(e,i)))}convertServerTimestamp(e,i){switch(i){case”previous”:const s=__PRIVATE_getPreviousValue(e);return null==s?null:this.convertValue(s,i);case”estimate”:return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e));default:return null}}convertTimestamp(e){const i=__PRIVATE_normalizeTimestamp(e);return new Timestamp(i.seconds,i.nanos)}convertDocumentKey(e,i){const s=ResourcePath.fromString(e);__PRIVATE_hardAssert(__PRIVATE_isValidResourceName(s),9688,{name:e});const o=new DatabaseId(s.get(1),s.get(3)),_=new DocumentKey(s.popFirst(5));return o.isEqual(i)||__PRIVATE_logError(`Document ${_} contains a document reference within a different database (${o.projectId}/${o.database}) which is not supported. It will be treated as a reference in the current database (${i.projectId}/${i.database}) instead.`),_}}function __PRIVATE_applyFirestoreDataConverter(e,i,s){let o;return o=e?s&&(s.merge||s.mergeFields)?e.toFirestore(i,s):e.toFirestore(i):i,o}class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bytes(e)}convertReference(e){const i=this.convertDocumentKey(e,this.firestore._databaseId);return new DocumentReference(this.firestore,null,i)}}function sum(e){return new AggregateField(“sum”,__PRIVATE_fieldPathFromArgument$1(“sum”,e))}function average(e){return new AggregateField(“avg”,__PRIVATE_fieldPathFromArgument$1(“average”,e))}function count(){return new AggregateField(“count”)}function aggregateFieldEqual(e,i){var s,o;return e instanceof AggregateField&&i instanceof AggregateField&&e.aggregateType===i.aggregateType&&(null===(s=e._internalFieldPath)||void 0===s?void 0:s.canonicalString())===(null===(o=i._internalFieldPath)||void 0===o?void 0:o.canonicalString())}function aggregateQuerySnapshotEqual(e,i){return queryEqual(e.query,i.query)&&deepEqual(e.data(),i.data())}class SnapshotMetadata{constructor(e,i){this.hasPendingWrites=e,this.fromCache=i}isEqual(e){return this.hasPendingWrites===e.hasPendingWrites&&this.fromCache===e.fromCache}}class DocumentSnapshot extends DocumentSnapshot$1{constructor(e,i,s,o,_,h){super(e,i,s,o,h),this._firestore=e,this._firestoreImpl=e,this.metadata=_}exists(){return super.exists()}data(e={}){if(this._document){if(this._converter){const i=new QueryDocumentSnapshot(this._firestore,this._userDataWriter,this._key,this._document,this.metadata,null);return this._converter.fromFirestore(i,e)}return this._userDataWriter.convertValue(this._document.data.value,e.serverTimestamps)}}get(e,i={}){if(this._document){const s=this._document.data.field(__PRIVATE_fieldPathFromArgument(“DocumentSnapshot.get”,e));if(null!==s)return this._userDataWriter.convertValue(s,i.serverTimestamps)}}}class QueryDocumentSnapshot extends DocumentSnapshot{data(e={}){return super.data(e)}}class QuerySnapshot{constructor(e,i,s,o){this._firestore=e,this._userDataWriter=i,this._snapshot=o,this.metadata=new SnapshotMetadata(o.hasPendingWrites,o.fromCache),this.query=s}get docs(){const e=[];return this.forEach((i=>e.push(i))),e}get size(){return this._snapshot.docs.size}get empty(){return 0===this.size}forEach(e,i){this._snapshot.docs.forEach((s=>{e.call(i,new QueryDocumentSnapshot(this._firestore,this._userDataWriter,s.key,s,new SnapshotMetadata(this._snapshot.mutatedKeys.has(s.key),this._snapshot.fromCache),this.query.converter))}))}docChanges(e={}){const i=!!e.includeMetadataChanges;if(i&&this._snapshot.excludesMetadataChanges)throw new FirestoreError(de.INVALID_ARGUMENT,”To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().”);return this._cachedChanges&&this._cachedChangesIncludeMetadataChanges===i||(this._cachedChanges=function __PRIVATE_changesFromSnapshot(e,i){if(e._snapshot.oldDocs.isEmpty()){let i=0;return e._snapshot.docChanges.map((s=>{const o=new QueryDocumentSnapshot(e._firestore,e._userDataWriter,s.doc.key,s.doc,new SnapshotMetadata(e._snapshot.mutatedKeys.has(s.doc.key),e._snapshot.fromCache),e.query.converter);return s.doc,{type:”added”,doc:o,oldIndex:-1,newIndex:i++}}))}{let s=e._snapshot.oldDocs;return e._snapshot.docChanges.filter((e=>i||3!==e.type)).map((i=>{const o=new QueryDocumentSnapshot(e._firestore,e._userDataWriter,i.doc.key,i.doc,new SnapshotMetadata(e._snapshot.mutatedKeys.has(i.doc.key),e._snapshot.fromCache),e.query.converter);let _=-1,h=-1;return 0!==i.type&&(_=s.indexOf(i.doc.key),s=s.delete(i.doc.key)),1!==i.type&&(s=s.add(i.doc),h=s.indexOf(i.doc.key)),{type:__PRIVATE_resultChangeType(i.type),doc:o,oldIndex:_,newIndex:h}}))}}(this,i),this._cachedChangesIncludeMetadataChanges=i),this._cachedChanges}}function __PRIVATE_resultChangeType(e){switch(e){case 0:return”added”;case 2:case 3:return”modified”;case 1:return”removed”;default:return fail(61501,{type:e})}}function snapshotEqual(e,i){return e instanceof DocumentSnapshot&&i instanceof DocumentSnapshot?e._firestore===i._firestore&&e._key.isEqual(i._key)&&(null===e._document?null===i._document:e._document.isEqual(i._document))&&e._converter===i._converter:e instanceof QuerySnapshot&&i instanceof QuerySnapshot&&e._firestore===i._firestore&&queryEqual(e.query,i.query)&&e.metadata.isEqual(i.metadata)&&e._snapshot.isEqual(i._snapshot)}function getDoc(e){e=__PRIVATE_cast(e,DocumentReference);const i=__PRIVATE_cast(e.firestore,Firestore);return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(i),e._key).then((s=>__PRIVATE_convertToDocSnapshot(i,e,s)))}class __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter{constructor(e){super(),this.firestore=e}convertBytes(e){return new Bytes(e)}convertReference(e){const i=this.convertDocumentKey(e,this.firestore._databaseId);return new DocumentReference(this.firestore,null,i)}}function getDocFromCache(e){e=__PRIVATE_cast(e,DocumentReference);const i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e,i){const s=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>async function __PRIVATE_readDocumentFromCache(e,i,s){try{const o=await function __PRIVATE_localStoreReadDocument(e,i){const s=__PRIVATE_debugCast(e);return s.persistence.runTransaction(“read document”,”readonly”,(e=>s.localDocuments.getDocument(e,i)))}(e,i);o.isFoundDocument()?s.resolve(o):o.isNoDocument()?s.resolve(null):s.reject(new FirestoreError(de.UNAVAILABLE,”Failed to get document from cache. (However, this document may exist on the server. Run again without setting ‘source’ in the GetOptions to attempt to retrieve the document from the server.)”))}catch(e){const o=__PRIVATE_wrapInUserErrorIfRecoverable(e,`Failed to get document ‘${i} from cache`);s.reject(o)}}(await __PRIVATE_getLocalStore(e),i,s))),s.promise}(s,e._key).then((s=>new DocumentSnapshot(i,o,e._key,s,new SnapshotMetadata(null!==s&&s.hasLocalMutations,!0),e.converter)))}function getDocFromServer(e){e=__PRIVATE_cast(e,DocumentReference);const i=__PRIVATE_cast(e.firestore,Firestore);return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(i),e._key,{source:”server”}).then((s=>__PRIVATE_convertToDocSnapshot(i,e,s)))}function getDocs(e){e=__PRIVATE_cast(e,Query);const i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query),__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(s,e._query).then((s=>new QuerySnapshot(i,o,e,s)))}function getDocsFromCache(e){e=__PRIVATE_cast(e,Query);const i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return function __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e,i){const s=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>async function __PRIVATE_executeQueryFromCache(e,i,s){try{const o=await __PRIVATE_localStoreExecuteQuery(e,i,!0),_=new __PRIVATE_View(i,o.Ns),h=_.Ga(o.documents),d=_.applyChanges(h,!1);s.resolve(d.snapshot)}catch(e){const o=__PRIVATE_wrapInUserErrorIfRecoverable(e,`Failed to execute query ‘${i} against cache`);s.reject(o)}}(await __PRIVATE_getLocalStore(e),i,s))),s.promise}(s,e._query).then((s=>new QuerySnapshot(i,o,e,s)))}function getDocsFromServer(e){e=__PRIVATE_cast(e,Query);const i=__PRIVATE_cast(e.firestore,Firestore),s=ensureFirestoreConfigured(i),o=new __PRIVATE_ExpUserDataWriter(i);return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(s,e._query,{source:”server”}).then((s=>new QuerySnapshot(i,o,e,s)))}function setDoc(e,i,s){e=__PRIVATE_cast(e,DocumentReference);const o=__PRIVATE_cast(e.firestore,Firestore),_=__PRIVATE_applyFirestoreDataConverter(e.converter,i,s);return executeWrite(o,[__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(o),”setDoc”,e._key,_,null!==e.converter,s).toMutation(e._key,Precondition.none())])}function updateDoc(e,i,s,…o){e=__PRIVATE_cast(e,DocumentReference);const _=__PRIVATE_cast(e.firestore,Firestore),h=__PRIVATE_newUserDataReader(_);let d;return d=”string”==typeof(i=getModularInstance(i))||i instanceof FieldPath?__PRIVATE_parseUpdateVarargs(h,”updateDoc”,e._key,i,s,o):__PRIVATE_parseUpdateData(h,”updateDoc”,e._key,i),executeWrite(_,[d.toMutation(e._key,Precondition.exists(!0))])}function deleteDoc(e){return executeWrite(__PRIVATE_cast(e.firestore,Firestore),[new __PRIVATE_DeleteMutation(e._key,Precondition.none())])}function addDoc(e,i){const s=__PRIVATE_cast(e.firestore,Firestore),o=doc(e),_=__PRIVATE_applyFirestoreDataConverter(e.converter,i);return executeWrite(s,[__PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore),”addDoc”,o._key,_,null!==e.converter,{}).toMutation(o._key,Precondition.exists(!1))]).then((()=>o))}function onSnapshot(e,…i){var s,o,_;e=getModularInstance(e);let h={includeMetadataChanges:!1,source:”default”},d=0;”object”!=typeof i[d]||__PRIVATE_isPartialObserver(i[d])||(h=i[d],d++);const f={includeMetadataChanges:h.includeMetadataChanges,source:h.source};if(__PRIVATE_isPartialObserver(i[d])){const e=i[d];i[d]=null===(s=e.next)||void 0===s?void 0:s.bind(e),i[d+1]=null===(o=e.error)||void 0===o?void 0:o.bind(e),i[d+2]=null===(_=e.complete)||void 0===_?void 0:_.bind(e)}let g,b,w;if(e instanceof DocumentReference)b=__PRIVATE_cast(e.firestore,Firestore),w=__PRIVATE_newQueryForPath(e._key.path),g={next:s=>{i[d]&&i[d](__PRIVATE_convertToDocSnapshot(b,e,s))},error:i[d+1],complete:i[d+2]};else{const s=__PRIVATE_cast(e,Query);b=__PRIVATE_cast(s.firestore,Firestore),w=s._query;const o=new __PRIVATE_ExpUserDataWriter(b);g={next:e=>{i[d]&&i[d](new QuerySnapshot(b,o,s,e))},error:i[d+1],complete:i[d+2]},__PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query)}return function __PRIVATE_firestoreClientListen(e,i,s,o){const _=new __PRIVATE_AsyncObserver(o),h=new __PRIVATE_QueryListener(i,_,s);return e.asyncQueue.enqueueAndForget((async()=>__PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e),h))),()=>{_.yu(),e.asyncQueue.enqueueAndForget((async()=>__PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e),h)))}}(ensureFirestoreConfigured(b),w,f,g)}function onSnapshotsInSync(e,i){return function __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e,i){const s=new __PRIVATE_AsyncObserver(i);return e.asyncQueue.enqueueAndForget((async()=>function __PRIVATE_addSnapshotsInSyncListener(e,i){__PRIVATE_debugCast(e).fa.add(i),i.next()}(await __PRIVATE_getEventManager(e),s))),()=>{s.yu(),e.asyncQueue.enqueueAndForget((async()=>function __PRIVATE_removeSnapshotsInSyncListener(e,i){__PRIVATE_debugCast(e).fa.delete(i)}(await __PRIVATE_getEventManager(e),s)))}}(ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),__PRIVATE_isPartialObserver(i)?i:{next:i})}function executeWrite(e,i){return function __PRIVATE_firestoreClientWrite(e,i){const s=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>async function __PRIVATE_syncEngineWrite(e,i,s){const o=__PRIVATE_syncEngineEnsureWriteCallbacks(e);try{const e=await function __PRIVATE_localStoreWriteLocally(e,i){const s=__PRIVATE_debugCast(e),o=Timestamp.now(),_=i.reduce(((e,i)=>e.add(i.key)),__PRIVATE_documentKeySet());let h,d;return s.persistence.runTransaction(“Locally write mutations”,”readwrite”,(e=>{let f=__PRIVATE_mutableDocumentMap(),g=__PRIVATE_documentKeySet();return s.Cs.getEntries(e,_).next((e=>{f=e,f.forEach(((e,i)=>{i.isValidDocument()||(g=g.add(e))}))})).next((()=>s.localDocuments.getOverlayedDocuments(e,f))).next((_=>{h=_;const d=[];for(const e of i){const i=__PRIVATE_mutationExtractBaseValue(e,h.get(e.key).overlayedDocument);null!=i&&d.push(new __PRIVATE_PatchMutation(e.key,i,__PRIVATE_extractFieldMask(i.value.mapValue),Precondition.exists(!0)))}return s.mutationQueue.addMutationBatch(e,o,d,i)})).next((i=>{d=i;const o=i.applyToLocalDocumentSet(h,g);return s.documentOverlayCache.saveOverlays(e,i.batchId,o)}))})).then((()=>({batchId:d.batchId,changes:__PRIVATE_convertOverlayedDocumentMapToDocumentMap(h)})))}(o.localStore,i);o.sharedClientState.addPendingMutation(e.batchId),function __PRIVATE_addMutationCallback(e,i,s){let o=e.uu[e.currentUser.toKey()];o||(o=new SortedMap(__PRIVATE_primitiveComparator)),o=o.insert(i,s),e.uu[e.currentUser.toKey()]=o}(o,e.batchId,s),await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(o,e.changes),await __PRIVATE_fillWritePipeline(o.remoteStore)}catch(e){const i=__PRIVATE_wrapInUserErrorIfRecoverable(e,”Failed to persist write”);s.reject(i)}}(await __PRIVATE_getSyncEngine(e),i,s))),s.promise}(ensureFirestoreConfigured(e),i)}function __PRIVATE_convertToDocSnapshot(e,i,s){const o=s.docs.get(i._key),_=new __PRIVATE_ExpUserDataWriter(e);return new DocumentSnapshot(e,_,i._key,o,new SnapshotMetadata(s.hasPendingWrites,s.fromCache),i.converter)}function getCountFromServer(e){return getAggregateFromServer(e,{count:count()})}function getAggregateFromServer(e,i){const s=__PRIVATE_cast(e.firestore,Firestore),o=ensureFirestoreConfigured(s),_=__PRIVATE_mapToArray(i,((e,i)=>new __PRIVATE_AggregateImpl(i,e.aggregateType,e._internalFieldPath)));return function __PRIVATE_firestoreClientRunAggregateQuery(e,i,s){const o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>{try{const _=await __PRIVATE_getDatastore(e);o.resolve(async function __PRIVATE_invokeRunAggregationQueryRpc(e,i,s){var o;const _=__PRIVATE_debugCast(e),{request:h,yt:d,parent:f}=__PRIVATE_toRunAggregationQueryRequest(_.serializer,__PRIVATE_queryToAggregateTarget(i),s);_.connection.Bo||delete h.parent;const g=(await _.Wo(“RunAggregationQuery”,_.serializer.databaseId,f,h,1)).filter((e=>!!e.result));__PRIVATE_hardAssert(1===g.length,64727);const b=null===(o=g[0].result)||void 0===o?void 0:o.aggregateFields;return Object.keys(b).reduce(((e,i)=>(e[d[i]]=b[i],e)),{})}(_,i,s))}catch(e){o.reject(e)}})),o.promise}(o,e._query,_).then((i=>function __PRIVATE_convertToAggregateQuerySnapshot(e,i,s){const o=new __PRIVATE_ExpUserDataWriter(e);return new AggregateQuerySnapshot(i,o,s)}(s,e,i)))}class __PRIVATE_MemoryLocalCacheImpl{constructor(e){this.kind=”memory”,this._onlineComponentProvider=OnlineComponentProvider.provider,(null==e?void 0:e.garbageCollector)?this._offlineComponentProvider=e.garbageCollector._offlineComponentProvider:this._offlineComponentProvider={build:()=>new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0)}}toJSON(){return{kind:this.kind}}}class __PRIVATE_PersistentLocalCacheImpl{constructor(e){let i;this.kind=”persistent”,(null==e?void 0:e.tabManager)?(e.tabManager._initialize(e),i=e.tabManager):(i=persistentSingleTabManager(void 0),i._initialize(e)),this._onlineComponentProvider=i._onlineComponentProvider,this._offlineComponentProvider=i._offlineComponentProvider}toJSON(){return{kind:this.kind}}}class __PRIVATE_MemoryEagerGarbageCollectorImpl{constructor(){this.kind=”memoryEager”,this._offlineComponentProvider=__PRIVATE_MemoryOfflineComponentProvider.provider}toJSON(){return{kind:this.kind}}}class __PRIVATE_MemoryLruGarbageCollectorImpl{constructor(e){this.kind=”memoryLru”,this._offlineComponentProvider={build:()=>new __PRIVATE_LruGcMemoryOfflineComponentProvider(e)}}toJSON(){return{kind:this.kind}}}function memoryEagerGarbageCollector(){return new __PRIVATE_MemoryEagerGarbageCollectorImpl}function memoryLruGarbageCollector(e){return new __PRIVATE_MemoryLruGarbageCollectorImpl(null==e?void 0:e.cacheSizeBytes)}function memoryLocalCache(e){return new __PRIVATE_MemoryLocalCacheImpl(e)}function persistentLocalCache(e){return new __PRIVATE_PersistentLocalCacheImpl(e)}class __PRIVATE_SingleTabManagerImpl{constructor(e){this.forceOwnership=e,this.kind=”persistentSingleTab”}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=OnlineComponentProvider.provider,this._offlineComponentProvider={build:i=>new __PRIVATE_IndexedDbOfflineComponentProvider(i,null==e?void 0:e.cacheSizeBytes,this.forceOwnership)}}}class __PRIVATE_MultiTabManagerImpl{constructor(){this.kind=”PersistentMultipleTab”}toJSON(){return{kind:this.kind}}_initialize(e){this._onlineComponentProvider=OnlineComponentProvider.provider,this._offlineComponentProvider={build:i=>new __PRIVATE_MultiTabOfflineComponentProvider(i,null==e?void 0:e.cacheSizeBytes)}}}function persistentSingleTabManager(e){return new __PRIVATE_SingleTabManagerImpl(null==e?void 0:e.forceOwnership)}function persistentMultipleTabManager(){return new __PRIVATE_MultiTabManagerImpl}const Mn={maxAttempts:5};class WriteBatch{constructor(e,i){this._firestore=e,this._commitHandler=i,this._mutations=[],this._committed=!1,this._dataReader=__PRIVATE_newUserDataReader(e)}set(e,i,s){this._verifyNotCommitted();const o=__PRIVATE_validateReference(e,this._firestore),_=__PRIVATE_applyFirestoreDataConverter(o.converter,i,s),h=__PRIVATE_parseSetData(this._dataReader,”WriteBatch.set”,o._key,_,null!==o.converter,s);return this._mutations.push(h.toMutation(o._key,Precondition.none())),this}update(e,i,s,…o){this._verifyNotCommitted();const _=__PRIVATE_validateReference(e,this._firestore);let h;return h=”string”==typeof(i=getModularInstance(i))||i instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,”WriteBatch.update”,_._key,i,s,o):__PRIVATE_parseUpdateData(this._dataReader,”WriteBatch.update”,_._key,i),this._mutations.push(h.toMutation(_._key,Precondition.exists(!0))),this}delete(e){this._verifyNotCommitted();const i=__PRIVATE_validateReference(e,this._firestore);return this._mutations=this._mutations.concat(new __PRIVATE_DeleteMutation(i._key,Precondition.none())),this}commit(){return this._verifyNotCommitted(),this._committed=!0,this._mutations.length>0?this._commitHandler(this._mutations):Promise.resolve()}_verifyNotCommitted(){if(this._committed)throw new FirestoreError(de.FAILED_PRECONDITION,”A write batch can no longer be used after commit() has been called.”)}}function __PRIVATE_validateReference(e,i){if((e=getModularInstance(e)).firestore!==i)throw new FirestoreError(de.INVALID_ARGUMENT,”Provided document reference is from a different Firestore instance.”);return e}class Transaction$1{constructor(e,i){this._firestore=e,this._transaction=i,this._dataReader=__PRIVATE_newUserDataReader(e)}get(e){const i=__PRIVATE_validateReference(e,this._firestore),s=new __PRIVATE_LiteUserDataWriter(this._firestore);return this._transaction.lookup([i._key]).then((e=>{if(!e||1!==e.length)return fail(24041);const o=e[0];if(o.isFoundDocument())return new DocumentSnapshot$1(this._firestore,s,o.key,o,i.converter);if(o.isNoDocument())return new DocumentSnapshot$1(this._firestore,s,i._key,null,i.converter);throw fail(18433,{doc:o})}))}set(e,i,s){const o=__PRIVATE_validateReference(e,this._firestore),_=__PRIVATE_applyFirestoreDataConverter(o.converter,i,s),h=__PRIVATE_parseSetData(this._dataReader,”Transaction.set”,o._key,_,null!==o.converter,s);return this._transaction.set(o._key,h),this}update(e,i,s,…o){const _=__PRIVATE_validateReference(e,this._firestore);let h;return h=”string”==typeof(i=getModularInstance(i))||i instanceof FieldPath?__PRIVATE_parseUpdateVarargs(this._dataReader,”Transaction.update”,_._key,i,s,o):__PRIVATE_parseUpdateData(this._dataReader,”Transaction.update”,_._key,i),this._transaction.update(_._key,h),this}delete(e){const i=__PRIVATE_validateReference(e,this._firestore);return this._transaction.delete(i._key),this}}class Transaction extends Transaction$1{constructor(e,i){super(e,i),this._firestore=e}get(e){const i=__PRIVATE_validateReference(e,this._firestore),s=new __PRIVATE_ExpUserDataWriter(this._firestore);return super.get(e).then((e=>new DocumentSnapshot(this._firestore,s,i._key,e._document,new SnapshotMetadata(!1,!1),i.converter)))}}function runTransaction(e,i,s){e=__PRIVATE_cast(e,Firestore);const o=Object.assign(Object.assign({},Mn),s);return function __PRIVATE_validateTransactionOptions(e){if(e.maxAttempts<1)throw new FirestoreError(de.INVALID_ARGUMENT,"Max attempts must be at least 1")}(o),function __PRIVATE_firestoreClientTransaction(e,i,s){const o=new __PRIVATE_Deferred;return e.asyncQueue.enqueueAndForget((async()=>{const _=await __PRIVATE_getDatastore(e);new __PRIVATE_TransactionRunner(e.asyncQueue,_,s,i,o).Nu()})),o.promise}(ensureFirestoreConfigured(e),(s=>i(new Transaction(e,s))),o)}function deleteField(){return new __PRIVATE_DeleteFieldValueImpl(“deleteField”)}function serverTimestamp(){return new __PRIVATE_ServerTimestampFieldValueImpl(“serverTimestamp”)}function arrayUnion(…e){return new __PRIVATE_ArrayUnionFieldValueImpl(“arrayUnion”,e)}function arrayRemove(…e){return new __PRIVATE_ArrayRemoveFieldValueImpl(“arrayRemove”,e)}function increment(e){return new __PRIVATE_NumericIncrementFieldValueImpl(“increment”,e)}function vector(e){return new VectorValue(e)}function writeBatch(e){return ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore)),new WriteBatch(e,(i=>executeWrite(e,i)))}function setIndexConfiguration(e,i){const s=ensureFirestoreConfigured(e=__PRIVATE_cast(e,Firestore));if(!s._uninitializedComponentsProvider||”memory”===s._uninitializedComponentsProvider._offline.kind)return __PRIVATE_logWarn(“Cannot enable indexes when persistence is disabled”),Promise.resolve();const o=function __PRIVATE_parseIndexes(e){const i=”string”==typeof e?function __PRIVATE_tryParseJson(e){try{return JSON.parse(e)}catch(e){throw new FirestoreError(de.INVALID_ARGUMENT,”Failed to parse JSON: “+(null==e?void 0:e.message))}}(e):e,s=[];if(Array.isArray(i.indexes))for(const e of i.indexes){const i=__PRIVATE_tryGetString(e,”collectionGroup”),o=[];if(Array.isArray(e.fields))for(const i of e.fields){const e=__PRIVATE_fieldPathFromDotSeparatedString(“setIndexConfiguration”,__PRIVATE_tryGetString(i,”fieldPath”));”CONTAINS”===i.arrayConfig?o.push(new IndexSegment(e,2)):”ASCENDING”===i.order?o.push(new IndexSegment(e,0)):”DESCENDING”===i.order&&o.push(new IndexSegment(e,1))}s.push(new FieldIndex(FieldIndex.UNKNOWN_ID,i,o,IndexState.empty()))}return s}(i);return function __PRIVATE_firestoreClientSetIndexConfiguration(e,i){return e.asyncQueue.enqueue((async()=>async function __PRIVATE_localStoreConfigureFieldIndexes(e,i){const s=__PRIVATE_debugCast(e),o=s.indexManager,_=[];return s.persistence.runTransaction(“Configure indexes”,”readwrite”,(e=>o.getFieldIndexes(e).next((s=>function __PRIVATE_diffArrays(e,i,s,o,_){e=[…e],i=[…i],e.sort(s),i.sort(s);const h=e.length,d=i.length;let f=0,g=0;for(;f0?o(i[f++]):(f++,g++)}for(;f{_.push(o.addFieldIndex(e,i))}),(i=>{_.push(o.deleteFieldIndex(e,i))})))).next((()=>PersistencePromise.waitFor(_)))))}(await __PRIVATE_getLocalStore(e),i)))}(s,o)}function __PRIVATE_tryGetString(e,i){if(“string”!=typeof e[i])throw new FirestoreError(de.INVALID_ARGUMENT,”Missing string value for: “+i);return e[i]}class PersistentCacheIndexManager{constructor(e){this._firestore=e,this.type=”PersistentCacheIndexManager”}}function getPersistentCacheIndexManager(e){var i;e=__PRIVATE_cast(e,Firestore);const s=Nn.get(e);if(s)return s;if(“persistent”!==(null===(i=ensureFirestoreConfigured(e)._uninitializedComponentsProvider)||void 0===i?void 0:i._offline.kind))return null;const o=new PersistentCacheIndexManager(e);return Nn.set(e,o),o}function enablePersistentCacheIndexAutoCreation(e){__PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e,!0)}function disablePersistentCacheIndexAutoCreation(e){__PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e,!1)}function deleteAllPersistentCacheIndexes(e){(function __PRIVATE_firestoreClientDeleteAllFieldIndexes(e){return e.asyncQueue.enqueue((async()=>function __PRIVATE_localStoreDeleteAllFieldIndexes(e){const i=__PRIVATE_debugCast(e),s=i.indexManager;return i.persistence.runTransaction(“Delete All Indexes”,”readwrite”,(e=>s.deleteAllFieldIndexes(e)))}(await __PRIVATE_getLocalStore(e))))})(ensureFirestoreConfigured(e._firestore)).then((e=>__PRIVATE_logDebug(“deleting all persistent cache indexes succeeded”))).catch((e=>__PRIVATE_logWarn(“deleting all persistent cache indexes failed”,e)))}function __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e,i){(function __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e,i){return e.asyncQueue.enqueue((async()=>function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e,i){__PRIVATE_debugCast(e).bs.Is=i}(await __PRIVATE_getLocalStore(e),i)))})(ensureFirestoreConfigured(e._firestore),i).then((e=>__PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${i} succeeded`))).catch((e=>__PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${i} failed`,e)))}const Nn=new WeakMap;function _internalQueryToProtoQueryTarget(e){var i;const s=null===(i=ensureFirestoreConfigured(__PRIVATE_cast(e.firestore,Firestore))._onlineComponents)||void 0===i?void 0:i.datastore.serializer;return void 0===s?null:__PRIVATE_toQueryTarget(s,__PRIVATE_queryToTarget(e._query)).gt}function _internalAggregationQueryToProtoRunAggregationQueryRequest(e,i){var s;const o=__PRIVATE_mapToArray(i,((e,i)=>new __PRIVATE_AggregateImpl(i,e.aggregateType,e._internalFieldPath))),_=null===(s=ensureFirestoreConfigured(__PRIVATE_cast(e.firestore,Firestore))._onlineComponents)||void 0===s?void 0:s.datastore.serializer;return void 0===_?null:__PRIVATE_toRunAggregationQueryRequest(_,__PRIVATE_queryToAggregateTarget(e._query),o,!0).request}class TestingHooks{constructor(){throw new Error(“instances of this class should not be created”)}static onExistenceFilterMismatch(e){return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e)}}class __PRIVATE_TestingHooksSpiImpl{constructor(){this.Vc=new Map}static get instance(){return kn||(kn=new __PRIVATE_TestingHooksSpiImpl,function __PRIVATE_setTestingHooksSpi(e){if(Wt)throw new Error(“a TestingHooksSpi instance is already set”);Wt=e}(kn)),kn}ht(e){this.Vc.forEach((i=>i(e)))}onExistenceFilterMismatch(e){const i=Symbol(),s=this.Vc;return s.set(i,e),()=>s.delete(i)}}let kn=null;!function __PRIVATE_registerFirestore(s,o=!0){!function __PRIVATE_setSDKVersion(e){_e=e}(h),e(new Component(“firestore”,((e,{instanceIdentifier:i,options:s})=>{const _=e.getProvider(“app”).getImmediate(),h=new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e.getProvider(“auth-internal”)),new __PRIVATE_FirebaseAppCheckTokenProvider(_,e.getProvider(“app-check-internal”)),function __PRIVATE_databaseIdFromApp(e,i){if(!Object.prototype.hasOwnProperty.apply(e.options,[“projectId”]))throw new FirestoreError(de.INVALID_ARGUMENT,'”projectId” not provided in firebase.initializeApp.’);return new DatabaseId(e.options.projectId,i)}(_,i),_);return s=Object.assign({useFetchStreams:o},s),h._setSettings(s),h}),”PUBLIC”).setMultipleInstances(!0)),i(ce,le,s),i(ce,le,”esm2017″)}();export{AbstractUserDataWriter,AggregateField,AggregateQuerySnapshot,Bytes,Cn as CACHE_SIZE_UNLIMITED,CollectionReference,DocumentReference,DocumentSnapshot,FieldPath,FieldValue,Firestore,FirestoreError,GeoPoint,LoadBundleTask,PersistentCacheIndexManager,Query,QueryCompositeFilterConstraint,QueryConstraint,QueryDocumentSnapshot,QueryEndAtConstraint,QueryFieldFilterConstraint,QueryLimitConstraint,QueryOrderByConstraint,QuerySnapshot,QueryStartAtConstraint,SnapshotMetadata,Timestamp,Transaction,VectorValue,WriteBatch,__PRIVATE_AutoId as _AutoId,ByteString as _ByteString,DatabaseId as _DatabaseId,DocumentKey as _DocumentKey,__PRIVATE_EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider,__PRIVATE_EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider,FieldPath$1 as _FieldPath,TestingHooks as _TestingHooks,__PRIVATE_cast as _cast,__PRIVATE_debugAssert as _debugAssert,_internalAggregationQueryToProtoRunAggregationQueryRequest,_internalQueryToProtoQueryTarget,__PRIVATE_isBase64Available as _isBase64Available,__PRIVATE_logWarn as _logWarn,__PRIVATE_validateIsNotUsedTogether as _validateIsNotUsedTogether,addDoc,aggregateFieldEqual,aggregateQuerySnapshotEqual,and,arrayRemove,arrayUnion,average,clearIndexedDbPersistence,collection,collectionGroup,connectFirestoreEmulator,count,deleteAllPersistentCacheIndexes,deleteDoc,deleteField,disableNetwork,disablePersistentCacheIndexAutoCreation,doc,documentId,enableIndexedDbPersistence,enableMultiTabIndexedDbPersistence,enableNetwork,enablePersistentCacheIndexAutoCreation,endAt,endBefore,ensureFirestoreConfigured,executeWrite,getAggregateFromServer,getCountFromServer,getDoc,getDocFromCache,getDocFromServer,getDocs,getDocsFromCache,getDocsFromServer,getFirestore,getPersistentCacheIndexManager,increment,initializeFirestore,limit,limitToLast,loadBundle,memoryEagerGarbageCollector,memoryLocalCache,memoryLruGarbageCollector,namedQuery,onSnapshot,onSnapshotsInSync,or,orderBy,persistentLocalCache,persistentMultipleTabManager,persistentSingleTabManager,query,queryEqual,refEqual,runTransaction,serverTimestamp,setDoc,setIndexConfiguration,setLogLevel,snapshotEqual,startAfter,startAt,sum,terminate,updateDoc,vector,waitForPendingWrites,where,writeBatch};
//# sourceMappingURL=firebase-firestore.js.map