Без опису
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

firebase-firestore-compat.js.map 2.2MB

1
  1. {"version":3,"file":"firebase-firestore-compat.js","sources":["../logger/src/logger.ts","../util/src/crypt.ts","../util/src/defaults.ts","../util/src/global.ts","../util/src/environment.ts","../util/src/errors.ts","../util/src/compat.ts","../component/src/component.ts","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/base.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/disposable.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/array/array.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/event.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserfeature.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/internal.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/util.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/reflect/reflect.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/useragent/useragent.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/browser.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/useragent/engine.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xhrio.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/browserevent.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtype.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenable.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenablekey.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listener.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/listenermap.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/object/object.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/events.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventtarget.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/json.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/workqueue.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/run.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/freelist.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throwexception.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/timer/timer.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/async/throttle.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/events/eventhandler.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchanneldebug.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/requeststats.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/errorcode.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/eventtype.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttpfactory.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/xmlhttp.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/channelrequest.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/environment.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbase.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/uri.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/disposable/dispose.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wirev8.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/string/string.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/forwardchannelrequestpool.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/structs/structs.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/uri/utils.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/wire.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/functions/functions.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/nativejsonprocessor.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/netutils.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/fetchxmlhttpfactory.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/json/hybrid.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/httpstatus.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/net/rpc/httpcors.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchannel/webchannelbasetransport.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransport.js","../webchannel-wrapper/dist/temp/src/index.js","../firestore/dist/index.esm2017.js","../webchannel-wrapper/node_modules/google-closure-library/closure/goog/labs/net/webchanneltransportfactory.js","../util/src/emulator.ts","../firestore-compat/src/index.ts","../firestore-compat/src/config.ts","../firestore-compat/src/util/input_validation.ts","../firestore-compat/src/api/blob.ts","../firestore-compat/src/api/observer.ts","../firestore-compat/src/api/database.ts","../firestore-compat/src/api/field_path.ts","../firestore-compat/src/api/field_value.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport type LogLevelString =\n | 'debug'\n | 'verbose'\n | 'info'\n | 'warn'\n | 'error'\n | 'silent';\n\nexport interface LogOptions {\n level: LogLevelString;\n}\n\nexport type LogCallback = (callbackParams: LogCallbackParams) => void;\n\nexport interface LogCallbackParams {\n level: LogLevelString;\n message: string;\n args: unknown[];\n type: string;\n}\n\n/**\n * A container for all of the Logger instances\n */\nexport const instances: Logger[] = [];\n\n/**\n * The JS SDK supports 5 log levels and also allows a user the ability to\n * silence the logs altogether.\n *\n * The order is a follows:\n * DEBUG < VERBOSE < INFO < WARN < ERROR\n *\n * All of the log types above the current log level will be captured (i.e. if\n * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and\n * `VERBOSE` logs will not)\n */\nexport enum LogLevel {\n DEBUG,\n VERBOSE,\n INFO,\n WARN,\n ERROR,\n SILENT\n}\n\nconst levelStringToEnum: { [key in LogLevelString]: LogLevel } = {\n 'debug': LogLevel.DEBUG,\n 'verbose': LogLevel.VERBOSE,\n 'info': LogLevel.INFO,\n 'warn': LogLevel.WARN,\n 'error': LogLevel.ERROR,\n 'silent': LogLevel.SILENT\n};\n\n/**\n * The default log level\n */\nconst defaultLogLevel: LogLevel = LogLevel.INFO;\n\n/**\n * We allow users the ability to pass their own log handler. We will pass the\n * type of log, the current log level, and any other arguments passed (i.e. the\n * messages that the user wants to log) to this function.\n */\nexport type LogHandler = (\n loggerInstance: Logger,\n logType: LogLevel,\n ...args: unknown[]\n) => void;\n\n/**\n * By default, `console.debug` is not displayed in the developer console (in\n * chrome). To avoid forcing users to have to opt-in to these logs twice\n * (i.e. once for firebase, and once in the console), we are sending `DEBUG`\n * logs to the `console.log` function.\n */\nconst ConsoleMethod = {\n [LogLevel.DEBUG]: 'log',\n [LogLevel.VERBOSE]: 'log',\n [LogLevel.INFO]: 'info',\n [LogLevel.WARN]: 'warn',\n [LogLevel.ERROR]: 'error'\n};\n\n/**\n * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR\n * messages on to their corresponding console counterparts (if the log method\n * is supported by the current log level)\n */\nconst defaultLogHandler: LogHandler = (instance, logType, ...args): void => {\n if (logType < instance.logLevel) {\n return;\n }\n const now = new Date().toISOString();\n const method = ConsoleMethod[logType as keyof typeof ConsoleMethod];\n if (method) {\n console[method as 'log' | 'info' | 'warn' | 'error'](\n `[${now}] ${instance.name}:`,\n ...args\n );\n } else {\n throw new Error(\n `Attempted to log a message with an invalid logType (value: ${logType})`\n );\n }\n};\n\nexport class Logger {\n /**\n * Gives you an instance of a Logger to capture messages according to\n * Firebase's logging scheme.\n *\n * @param name The name that the logs will be associated with\n */\n constructor(public name: string) {\n /**\n * Capture the current instance for later use\n */\n instances.push(this);\n }\n\n /**\n * The log level of the given Logger instance.\n */\n private _logLevel = defaultLogLevel;\n\n get logLevel(): LogLevel {\n return this._logLevel;\n }\n\n set logLevel(val: LogLevel) {\n if (!(val in LogLevel)) {\n throw new TypeError(`Invalid value \"${val}\" assigned to \\`logLevel\\``);\n }\n this._logLevel = val;\n }\n\n // Workaround for setter/getter having to be the same type.\n setLogLevel(val: LogLevel | LogLevelString): void {\n this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val;\n }\n\n /**\n * The main (internal) log handler for the Logger instance.\n * Can be set to a new function in internal package code but not by user.\n */\n private _logHandler: LogHandler = defaultLogHandler;\n get logHandler(): LogHandler {\n return this._logHandler;\n }\n set logHandler(val: LogHandler) {\n if (typeof val !== 'function') {\n throw new TypeError('Value assigned to `logHandler` must be a function');\n }\n this._logHandler = val;\n }\n\n /**\n * The optional, additional, user-defined log handler for the Logger instance.\n */\n private _userLogHandler: LogHandler | null = null;\n get userLogHandler(): LogHandler | null {\n return this._userLogHandler;\n }\n set userLogHandler(val: LogHandler | null) {\n this._userLogHandler = val;\n }\n\n /**\n * The functions below are all based on the `console` interface\n */\n\n debug(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);\n this._logHandler(this, LogLevel.DEBUG, ...args);\n }\n log(...args: unknown[]): void {\n this._userLogHandler &&\n this._userLogHandler(this, LogLevel.VERBOSE, ...args);\n this._logHandler(this, LogLevel.VERBOSE, ...args);\n }\n info(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);\n this._logHandler(this, LogLevel.INFO, ...args);\n }\n warn(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);\n this._logHandler(this, LogLevel.WARN, ...args);\n }\n error(...args: unknown[]): void {\n this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);\n this._logHandler(this, LogLevel.ERROR, ...args);\n }\n}\n\nexport function setLogLevel(level: LogLevelString | LogLevel): void {\n instances.forEach(inst => {\n inst.setLogLevel(level);\n });\n}\n\nexport function setUserLogHandler(\n logCallback: LogCallback | null,\n options?: LogOptions\n): void {\n for (const instance of instances) {\n let customLogLevel: LogLevel | null = null;\n if (options && options.level) {\n customLogLevel = levelStringToEnum[options.level];\n }\n if (logCallback === null) {\n instance.userLogHandler = null;\n } else {\n instance.userLogHandler = (\n instance: Logger,\n level: LogLevel,\n ...args: unknown[]\n ) => {\n const message = args\n .map(arg => {\n if (arg == null) {\n return null;\n } else if (typeof arg === 'string') {\n return arg;\n } else if (typeof arg === 'number' || typeof arg === 'boolean') {\n return arg.toString();\n } else if (arg instanceof Error) {\n return arg.message;\n } else {\n try {\n return JSON.stringify(arg);\n } catch (ignored) {\n return null;\n }\n }\n })\n .filter(arg => arg)\n .join(' ');\n if (level >= (customLogLevel ?? instance.logLevel)) {\n logCallback({\n level: LogLevel[level].toLowerCase() as LogLevelString,\n message,\n args,\n type: instance.name\n });\n }\n };\n }\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst stringToByteArray = function (str: string): number[] {\n // TODO(user): Use native implementations if/when available\n const out: number[] = [];\n let p = 0;\n for (let i = 0; i < str.length; i++) {\n let c = str.charCodeAt(i);\n if (c < 128) {\n out[p++] = c;\n } else if (c < 2048) {\n out[p++] = (c >> 6) | 192;\n out[p++] = (c & 63) | 128;\n } else if (\n (c & 0xfc00) === 0xd800 &&\n i + 1 < str.length &&\n (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00\n ) {\n // Surrogate Pair\n c = 0x10000 + ((c & 0x03ff) << 10) + (str.charCodeAt(++i) & 0x03ff);\n out[p++] = (c >> 18) | 240;\n out[p++] = ((c >> 12) & 63) | 128;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n } else {\n out[p++] = (c >> 12) | 224;\n out[p++] = ((c >> 6) & 63) | 128;\n out[p++] = (c & 63) | 128;\n }\n }\n return out;\n};\n\n/**\n * Turns an array of numbers into the string given by the concatenation of the\n * characters to which the numbers correspond.\n * @param bytes Array of numbers representing characters.\n * @return Stringification of the array.\n */\nconst byteArrayToString = function (bytes: number[]): string {\n // TODO(user): Use native implementations if/when available\n const out: string[] = [];\n let pos = 0,\n c = 0;\n while (pos < bytes.length) {\n const c1 = bytes[pos++];\n if (c1 < 128) {\n out[c++] = String.fromCharCode(c1);\n } else if (c1 > 191 && c1 < 224) {\n const c2 = bytes[pos++];\n out[c++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));\n } else if (c1 > 239 && c1 < 365) {\n // Surrogate Pair\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n const c4 = bytes[pos++];\n const u =\n (((c1 & 7) << 18) | ((c2 & 63) << 12) | ((c3 & 63) << 6) | (c4 & 63)) -\n 0x10000;\n out[c++] = String.fromCharCode(0xd800 + (u >> 10));\n out[c++] = String.fromCharCode(0xdc00 + (u & 1023));\n } else {\n const c2 = bytes[pos++];\n const c3 = bytes[pos++];\n out[c++] = String.fromCharCode(\n ((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)\n );\n }\n }\n return out.join('');\n};\n\ninterface Base64 {\n byteToCharMap_: { [key: number]: string } | null;\n charToByteMap_: { [key: string]: number } | null;\n byteToCharMapWebSafe_: { [key: number]: string } | null;\n charToByteMapWebSafe_: { [key: string]: number } | null;\n ENCODED_VALS_BASE: string;\n readonly ENCODED_VALS: string;\n readonly ENCODED_VALS_WEBSAFE: string;\n HAS_NATIVE_SUPPORT: boolean;\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string;\n encodeString(input: string, webSafe?: boolean): string;\n decodeString(input: string, webSafe: boolean): string;\n decodeStringToByteArray(input: string, webSafe: boolean): number[];\n init_(): void;\n}\n\n// We define it as an object literal instead of a class because a class compiled down to es5 can't\n// be treeshaked. https://github.com/rollup/rollup/issues/1691\n// Static lookup maps, lazily populated by init_()\nexport const base64: Base64 = {\n /**\n * Maps bytes to characters.\n */\n byteToCharMap_: null,\n\n /**\n * Maps characters to bytes.\n */\n charToByteMap_: null,\n\n /**\n * Maps bytes to websafe characters.\n * @private\n */\n byteToCharMapWebSafe_: null,\n\n /**\n * Maps websafe characters to bytes.\n * @private\n */\n charToByteMapWebSafe_: null,\n\n /**\n * Our default alphabet, shared between\n * ENCODED_VALS and ENCODED_VALS_WEBSAFE\n */\n ENCODED_VALS_BASE:\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz' + '0123456789',\n\n /**\n * Our default alphabet. Value 64 (=) is special; it means \"nothing.\"\n */\n get ENCODED_VALS() {\n return this.ENCODED_VALS_BASE + '+/=';\n },\n\n /**\n * Our websafe alphabet.\n */\n get ENCODED_VALS_WEBSAFE() {\n return this.ENCODED_VALS_BASE + '-_.';\n },\n\n /**\n * Whether this browser supports the atob and btoa functions. This extension\n * started at Mozilla but is now implemented by many browsers. We use the\n * ASSUME_* variables to avoid pulling in the full useragent detection library\n * but still allowing the standard per-browser compilations.\n *\n */\n HAS_NATIVE_SUPPORT: typeof atob === 'function',\n\n /**\n * Base64-encode an array of bytes.\n *\n * @param input An array of bytes (numbers with\n * value in [0, 255]) to encode.\n * @param webSafe Boolean indicating we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeByteArray(input: number[] | Uint8Array, webSafe?: boolean): string {\n if (!Array.isArray(input)) {\n throw Error('encodeByteArray takes an array as a parameter');\n }\n\n this.init_();\n\n const byteToCharMap = webSafe\n ? this.byteToCharMapWebSafe_!\n : this.byteToCharMap_!;\n\n const output = [];\n\n for (let i = 0; i < input.length; i += 3) {\n const byte1 = input[i];\n const haveByte2 = i + 1 < input.length;\n const byte2 = haveByte2 ? input[i + 1] : 0;\n const haveByte3 = i + 2 < input.length;\n const byte3 = haveByte3 ? input[i + 2] : 0;\n\n const outByte1 = byte1 >> 2;\n const outByte2 = ((byte1 & 0x03) << 4) | (byte2 >> 4);\n let outByte3 = ((byte2 & 0x0f) << 2) | (byte3 >> 6);\n let outByte4 = byte3 & 0x3f;\n\n if (!haveByte3) {\n outByte4 = 64;\n\n if (!haveByte2) {\n outByte3 = 64;\n }\n }\n\n output.push(\n byteToCharMap[outByte1],\n byteToCharMap[outByte2],\n byteToCharMap[outByte3],\n byteToCharMap[outByte4]\n );\n }\n\n return output.join('');\n },\n\n /**\n * Base64-encode a string.\n *\n * @param input A string to encode.\n * @param webSafe If true, we should use the\n * alternative alphabet.\n * @return The base64 encoded string.\n */\n encodeString(input: string, webSafe?: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return btoa(input);\n }\n return this.encodeByteArray(stringToByteArray(input), webSafe);\n },\n\n /**\n * Base64-decode a string.\n *\n * @param input to decode.\n * @param webSafe True if we should use the\n * alternative alphabet.\n * @return string representing the decoded value.\n */\n decodeString(input: string, webSafe: boolean): string {\n // Shortcut for Mozilla browsers that implement\n // a native base64 encoder in the form of \"btoa/atob\"\n if (this.HAS_NATIVE_SUPPORT && !webSafe) {\n return atob(input);\n }\n return byteArrayToString(this.decodeStringToByteArray(input, webSafe));\n },\n\n /**\n * Base64-decode a string.\n *\n * In base-64 decoding, groups of four characters are converted into three\n * bytes. If the encoder did not apply padding, the input length may not\n * be a multiple of 4.\n *\n * In this case, the last group will have fewer than 4 characters, and\n * padding will be inferred. If the group has one or two characters, it decodes\n * to one byte. If the group has three characters, it decodes to two bytes.\n *\n * @param input Input to decode.\n * @param webSafe True if we should use the web-safe alphabet.\n * @return bytes representing the decoded value.\n */\n decodeStringToByteArray(input: string, webSafe: boolean): number[] {\n this.init_();\n\n const charToByteMap = webSafe\n ? this.charToByteMapWebSafe_!\n : this.charToByteMap_!;\n\n const output: number[] = [];\n\n for (let i = 0; i < input.length; ) {\n const byte1 = charToByteMap[input.charAt(i++)];\n\n const haveByte2 = i < input.length;\n const byte2 = haveByte2 ? charToByteMap[input.charAt(i)] : 0;\n ++i;\n\n const haveByte3 = i < input.length;\n const byte3 = haveByte3 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n const haveByte4 = i < input.length;\n const byte4 = haveByte4 ? charToByteMap[input.charAt(i)] : 64;\n ++i;\n\n if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {\n throw Error();\n }\n\n const outByte1 = (byte1 << 2) | (byte2 >> 4);\n output.push(outByte1);\n\n if (byte3 !== 64) {\n const outByte2 = ((byte2 << 4) & 0xf0) | (byte3 >> 2);\n output.push(outByte2);\n\n if (byte4 !== 64) {\n const outByte3 = ((byte3 << 6) & 0xc0) | byte4;\n output.push(outByte3);\n }\n }\n }\n\n return output;\n },\n\n /**\n * Lazy static initialization function. Called before\n * accessing any of the static map variables.\n * @private\n */\n init_() {\n if (!this.byteToCharMap_) {\n this.byteToCharMap_ = {};\n this.charToByteMap_ = {};\n this.byteToCharMapWebSafe_ = {};\n this.charToByteMapWebSafe_ = {};\n\n // We want quick mappings back and forth, so we precompute two maps.\n for (let i = 0; i < this.ENCODED_VALS.length; i++) {\n this.byteToCharMap_[i] = this.ENCODED_VALS.charAt(i);\n this.charToByteMap_[this.byteToCharMap_[i]] = i;\n this.byteToCharMapWebSafe_[i] = this.ENCODED_VALS_WEBSAFE.charAt(i);\n this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i]] = i;\n\n // Be forgiving when decoding and correctly decode both encodings.\n if (i >= this.ENCODED_VALS_BASE.length) {\n this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i)] = i;\n this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i)] = i;\n }\n }\n }\n }\n};\n\n/**\n * URL-safe base64 encoding\n */\nexport const base64Encode = function (str: string): string {\n const utf8Bytes = stringToByteArray(str);\n return base64.encodeByteArray(utf8Bytes, true);\n};\n\n/**\n * URL-safe base64 encoding (without \".\" padding in the end).\n * e.g. Used in JSON Web Token (JWT) parts.\n */\nexport const base64urlEncodeWithoutPadding = function (str: string): string {\n // Use base64url encoding and remove padding in the end (dot characters).\n return base64Encode(str).replace(/\\./g, '');\n};\n\n/**\n * URL-safe base64 decoding\n *\n * NOTE: DO NOT use the global atob() function - it does NOT support the\n * base64Url variant encoding.\n *\n * @param str To be decoded\n * @return Decoded result, if possible\n */\nexport const base64Decode = function (str: string): string | null {\n try {\n return base64.decodeString(str, true);\n } catch (e) {\n console.error('base64Decode failed: ', e);\n }\n return null;\n};\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64Decode } from './crypt';\nimport { getGlobal } from './global';\n\n/**\n * Keys for experimental properties on the `FirebaseDefaults` object.\n * @public\n */\nexport type ExperimentalKey = 'authTokenSyncURL' | 'authIdTokenMaxAge';\n\n/**\n * An object that can be injected into the environment as __FIREBASE_DEFAULTS__,\n * either as a property of globalThis, a shell environment variable, or a\n * cookie.\n *\n * This object can be used to automatically configure and initialize\n * a Firebase app as well as any emulators.\n *\n * @public\n */\nexport interface FirebaseDefaults {\n config?: Record<string, string>;\n emulatorHosts?: Record<string, string>;\n _authTokenSyncURL?: string;\n _authIdTokenMaxAge?: number;\n /**\n * Override Firebase's runtime environment detection and\n * force the SDK to act as if it were in the specified environment.\n */\n forceEnvironment?: 'browser' | 'node';\n [key: string]: unknown;\n}\n\ndeclare global {\n // Need `var` for this to work.\n // eslint-disable-next-line no-var\n var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined;\n}\n\nconst getDefaultsFromGlobal = (): FirebaseDefaults | undefined =>\n getGlobal().__FIREBASE_DEFAULTS__;\n\n/**\n * Attempt to read defaults from a JSON string provided to\n * process(.)env(.)__FIREBASE_DEFAULTS__ or a JSON file whose path is in\n * process(.)env(.)__FIREBASE_DEFAULTS_PATH__\n * The dots are in parens because certain compilers (Vite?) cannot\n * handle seeing that variable in comments.\n * See https://github.com/firebase/firebase-js-sdk/issues/6838\n */\nconst getDefaultsFromEnvVariable = (): FirebaseDefaults | undefined => {\n if (typeof process === 'undefined' || typeof process.env === 'undefined') {\n return;\n }\n const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__;\n if (defaultsJsonString) {\n return JSON.parse(defaultsJsonString);\n }\n};\n\nconst getDefaultsFromCookie = (): FirebaseDefaults | undefined => {\n if (typeof document === 'undefined') {\n return;\n }\n let match;\n try {\n match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);\n } catch (e) {\n // Some environments such as Angular Universal SSR have a\n // `document` object but error on accessing `document.cookie`.\n return;\n }\n const decoded = match && base64Decode(match[1]);\n return decoded && JSON.parse(decoded);\n};\n\n/**\n * Get the __FIREBASE_DEFAULTS__ object. It checks in order:\n * (1) if such an object exists as a property of `globalThis`\n * (2) if such an object was provided on a shell environment variable\n * (3) if such an object exists in a cookie\n * @public\n */\nexport const getDefaults = (): FirebaseDefaults | undefined => {\n try {\n return (\n getDefaultsFromGlobal() ||\n getDefaultsFromEnvVariable() ||\n getDefaultsFromCookie()\n );\n } catch (e) {\n /**\n * Catch-all for being unable to get __FIREBASE_DEFAULTS__ due\n * to any environment case we have not accounted for. Log to\n * info instead of swallowing so we can find these unknown cases\n * and add paths for them if needed.\n */\n console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e}`);\n return;\n }\n};\n\n/**\n * Returns emulator host stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a URL host formatted like `127.0.0.1:9999` or `[::1]:4000` if available\n * @public\n */\nexport const getDefaultEmulatorHost = (\n productName: string\n): string | undefined => getDefaults()?.emulatorHosts?.[productName];\n\n/**\n * Returns emulator hostname and port stored in the __FIREBASE_DEFAULTS__ object\n * for the given product.\n * @returns a pair of hostname and port like `[\"::1\", 4000]` if available\n * @public\n */\nexport const getDefaultEmulatorHostnameAndPort = (\n productName: string\n): [hostname: string, port: number] | undefined => {\n const host = getDefaultEmulatorHost(productName);\n if (!host) {\n return undefined;\n }\n const separatorIndex = host.lastIndexOf(':'); // Finding the last since IPv6 addr also has colons.\n if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {\n throw new Error(`Invalid host ${host} with no separate hostname and port!`);\n }\n // eslint-disable-next-line no-restricted-globals\n const port = parseInt(host.substring(separatorIndex + 1), 10);\n if (host[0] === '[') {\n // Bracket-quoted `[ipv6addr]:port` => return \"ipv6addr\" (without brackets).\n return [host.substring(1, separatorIndex - 1), port];\n } else {\n return [host.substring(0, separatorIndex), port];\n }\n};\n\n/**\n * Returns Firebase app config stored in the __FIREBASE_DEFAULTS__ object.\n * @public\n */\nexport const getDefaultAppConfig = (): Record<string, string> | undefined =>\n getDefaults()?.config;\n\n/**\n * Returns an experimental setting on the __FIREBASE_DEFAULTS__ object (properties\n * prefixed by \"_\")\n * @public\n */\nexport const getExperimentalSetting = <T extends ExperimentalKey>(\n name: T\n): FirebaseDefaults[`_${T}`] =>\n getDefaults()?.[`_${name}`] as FirebaseDefaults[`_${T}`];\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Polyfill for `globalThis` object.\n * @returns the `globalThis` object for the given environment.\n * @public\n */\nexport function getGlobal(): typeof globalThis {\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n throw new Error('Unable to locate global object.');\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CONSTANTS } from './constants';\nimport { getDefaults } from './defaults';\n\n/**\n * Returns navigator.userAgent string or '' if it's not defined.\n * @return user agent string\n */\nexport function getUA(): string {\n if (\n typeof navigator !== 'undefined' &&\n typeof navigator['userAgent'] === 'string'\n ) {\n return navigator['userAgent'];\n } else {\n return '';\n }\n}\n\n/**\n * Detect Cordova / PhoneGap / Ionic frameworks on a mobile device.\n *\n * Deliberately does not rely on checking `file://` URLs (as this fails PhoneGap\n * in the Ripple emulator) nor Cordova `onDeviceReady`, which would normally\n * wait for a callback.\n */\nexport function isMobileCordova(): boolean {\n return (\n typeof window !== 'undefined' &&\n // @ts-ignore Setting up an broadly applicable index signature for Window\n // just to deal with this case would probably be a bad idea.\n !!(window['cordova'] || window['phonegap'] || window['PhoneGap']) &&\n /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA())\n );\n}\n\n/**\n * Detect Node.js.\n *\n * @return true if Node.js environment is detected or specified.\n */\n// Node detection logic from: https://github.com/iliakan/detect-node/\nexport function isNode(): boolean {\n const forceEnvironment = getDefaults()?.forceEnvironment;\n if (forceEnvironment === 'node') {\n return true;\n } else if (forceEnvironment === 'browser') {\n return false;\n }\n\n try {\n return (\n Object.prototype.toString.call(global.process) === '[object process]'\n );\n } catch (e) {\n return false;\n }\n}\n\n/**\n * Detect Browser Environment\n */\nexport function isBrowser(): boolean {\n return typeof self === 'object' && self.self === self;\n}\n\n/**\n * Detect browser extensions (Chrome and Firefox at least).\n */\ninterface BrowserRuntime {\n id?: unknown;\n}\ndeclare const chrome: { runtime?: BrowserRuntime };\ndeclare const browser: { runtime?: BrowserRuntime };\nexport function isBrowserExtension(): boolean {\n const runtime =\n typeof chrome === 'object'\n ? chrome.runtime\n : typeof browser === 'object'\n ? browser.runtime\n : undefined;\n return typeof runtime === 'object' && runtime.id !== undefined;\n}\n\n/**\n * Detect React Native.\n *\n * @return true if ReactNative environment is detected.\n */\nexport function isReactNative(): boolean {\n return (\n typeof navigator === 'object' && navigator['product'] === 'ReactNative'\n );\n}\n\n/** Detects Electron apps. */\nexport function isElectron(): boolean {\n return getUA().indexOf('Electron/') >= 0;\n}\n\n/** Detects Internet Explorer. */\nexport function isIE(): boolean {\n const ua = getUA();\n return ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;\n}\n\n/** Detects Universal Windows Platform apps. */\nexport function isUWP(): boolean {\n return getUA().indexOf('MSAppHost/') >= 0;\n}\n\n/**\n * Detect whether the current SDK build is the Node version.\n *\n * @return true if it's the Node SDK build.\n */\nexport function isNodeSdk(): boolean {\n return CONSTANTS.NODE_CLIENT === true || CONSTANTS.NODE_ADMIN === true;\n}\n\n/** Returns true if we are running in Safari. */\nexport function isSafari(): boolean {\n return (\n !isNode() &&\n navigator.userAgent.includes('Safari') &&\n !navigator.userAgent.includes('Chrome')\n );\n}\n\n/**\n * This method checks if indexedDB is supported by current browser/service worker context\n * @return true if indexedDB is supported by current browser/service worker context\n */\nexport function isIndexedDBAvailable(): boolean {\n try {\n return typeof indexedDB === 'object';\n } catch (e) {\n return false;\n }\n}\n\n/**\n * This method validates browser/sw context for indexedDB by opening a dummy indexedDB database and reject\n * if errors occur during the database open operation.\n *\n * @throws exception if current browser/sw context can't run idb.open (ex: Safari iframe, Firefox\n * private browsing)\n */\nexport function validateIndexedDBOpenable(): Promise<boolean> {\n return new Promise((resolve, reject) => {\n try {\n let preExist: boolean = true;\n const DB_CHECK_NAME =\n 'validate-browser-context-for-indexeddb-analytics-module';\n const request = self.indexedDB.open(DB_CHECK_NAME);\n request.onsuccess = () => {\n request.result.close();\n // delete database only when it doesn't pre-exist\n if (!preExist) {\n self.indexedDB.deleteDatabase(DB_CHECK_NAME);\n }\n resolve(true);\n };\n request.onupgradeneeded = () => {\n preExist = false;\n };\n\n request.onerror = () => {\n reject(request.error?.message || '');\n };\n } catch (error) {\n reject(error);\n }\n });\n}\n\n/**\n *\n * This method checks whether cookie is enabled within current browser\n * @return true if cookie is enabled within current browser\n */\nexport function areCookiesEnabled(): boolean {\n if (typeof navigator === 'undefined' || !navigator.cookieEnabled) {\n return false;\n }\n return true;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @fileoverview Standardized Firebase Error.\n *\n * Usage:\n *\n * // Typescript string literals for type-safe codes\n * type Err =\n * 'unknown' |\n * 'object-not-found'\n * ;\n *\n * // Closure enum for type-safe error codes\n * // at-enum {string}\n * var Err = {\n * UNKNOWN: 'unknown',\n * OBJECT_NOT_FOUND: 'object-not-found',\n * }\n *\n * let errors: Map<Err, string> = {\n * 'generic-error': \"Unknown error\",\n * 'file-not-found': \"Could not find file: {$file}\",\n * };\n *\n * // Type-safe function - must pass a valid error code as param.\n * let error = new ErrorFactory<Err>('service', 'Service', errors);\n *\n * ...\n * throw error.create(Err.GENERIC);\n * ...\n * throw error.create(Err.FILE_NOT_FOUND, {'file': fileName});\n * ...\n * // Service: Could not file file: foo.txt (service/file-not-found).\n *\n * catch (e) {\n * assert(e.message === \"Could not find file: foo.txt.\");\n * if ((e as FirebaseError)?.code === 'service/file-not-found') {\n * console.log(\"Could not read file: \" + e['file']);\n * }\n * }\n */\n\nexport type ErrorMap<ErrorCode extends string> = {\n readonly [K in ErrorCode]: string;\n};\n\nconst ERROR_NAME = 'FirebaseError';\n\nexport interface StringLike {\n toString(): string;\n}\n\nexport interface ErrorData {\n [key: string]: unknown;\n}\n\n// Based on code from:\n// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error#Custom_Error_Types\nexport class FirebaseError extends Error {\n /** The custom name for all FirebaseErrors. */\n readonly name: string = ERROR_NAME;\n\n constructor(\n /** The error code for this error. */\n readonly code: string,\n message: string,\n /** Custom data for this error. */\n public customData?: Record<string, unknown>\n ) {\n super(message);\n\n // Fix For ES5\n // https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, FirebaseError.prototype);\n\n // Maintains proper stack trace for where our error was thrown.\n // Only available on V8.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, ErrorFactory.prototype.create);\n }\n }\n}\n\nexport class ErrorFactory<\n ErrorCode extends string,\n ErrorParams extends { readonly [K in ErrorCode]?: ErrorData } = {}\n> {\n constructor(\n private readonly service: string,\n private readonly serviceName: string,\n private readonly errors: ErrorMap<ErrorCode>\n ) {}\n\n create<K extends ErrorCode>(\n code: K,\n ...data: K extends keyof ErrorParams ? [ErrorParams[K]] : []\n ): FirebaseError {\n const customData = (data[0] as ErrorData) || {};\n const fullCode = `${this.service}/${code}`;\n const template = this.errors[code];\n\n const message = template ? replaceTemplate(template, customData) : 'Error';\n // Service Name: Error message (service/code).\n const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;\n\n const error = new FirebaseError(fullCode, fullMessage, customData);\n\n return error;\n }\n}\n\nfunction replaceTemplate(template: string, data: ErrorData): string {\n return template.replace(PATTERN, (_, key) => {\n const value = data[key];\n return value != null ? String(value) : `<${key}?>`;\n });\n}\n\nconst PATTERN = /\\{\\$([^}]+)}/g;\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport interface Compat<T> {\n _delegate: T;\n}\n\nexport function getModularInstance<ExpService>(\n service: Compat<ExpService> | ExpService\n): ExpService {\n if (service && (service as Compat<ExpService>)._delegate) {\n return (service as Compat<ExpService>)._delegate;\n } else {\n return service as ExpService;\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport {\n InstantiationMode,\n InstanceFactory,\n ComponentType,\n Dictionary,\n Name,\n onInstanceCreatedCallback\n} from './types';\n\n/**\n * Component for service name T, e.g. `auth`, `auth-internal`\n */\nexport class Component<T extends Name = Name> {\n multipleInstances = false;\n /**\n * Properties to be added to the service namespace\n */\n serviceProps: Dictionary = {};\n\n instantiationMode = InstantiationMode.LAZY;\n\n onInstanceCreated: onInstanceCreatedCallback<T> | null = null;\n\n /**\n *\n * @param name The public service name, e.g. app, auth, firestore, database\n * @param instanceFactory Service factory responsible for creating the public interface\n * @param type whether the service provided by the component is public or private\n */\n constructor(\n readonly name: T,\n readonly instanceFactory: InstanceFactory<T>,\n readonly type: ComponentType\n ) {}\n\n setInstantiationMode(mode: InstantiationMode): this {\n this.instantiationMode = mode;\n return this;\n }\n\n setMultipleInstances(multipleInstances: boolean): this {\n this.multipleInstances = multipleInstances;\n return this;\n }\n\n setServiceProps(props: Dictionary): this {\n this.serviceProps = props;\n return this;\n }\n\n setInstanceCreatedCallback(callback: onInstanceCreatedCallback<T>): this {\n this.onInstanceCreated = callback;\n return this;\n }\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Bootstrap for the Google JS Library (Closure).\n *\n * In uncompiled mode base.js will attempt to load Closure's deps file, unless\n * the global <code>CLOSURE_NO_DEPS</code> is set to true. This allows projects\n * to include their own deps file(s) from different locations.\n *\n * Avoid including base.js more than once. This is strictly discouraged and not\n * supported. goog.require(...) won't work properly in that case.\n *\n * @provideGoog\n */\n\n\n/**\n * @define {boolean} Overridden to true by the compiler.\n */\nvar COMPILED = false;\n\n\n/**\n * Base namespace for the Closure library. Checks to see goog is already\n * defined in the current scope before assigning to prevent clobbering if\n * base.js is loaded more than once.\n *\n * @const\n */\nvar goog = goog || {};\n\n/**\n * Reference to the global object.\n * https://www.ecma-international.org/ecma-262/9.0/index.html#sec-global-object\n *\n * More info on this implementation here:\n * https://docs.google.com/document/d/1NAeW4Wk7I7FV0Y2tcUFvQdGMc89k2vdgSXInw8_nvCI/edit\n *\n * @const\n * @suppress {undefinedVars} self won't be referenced unless `this` is falsy.\n * @type {!Global}\n */\ngoog.global =\n // Check `this` first for backwards compatibility.\n // Valid unless running as an ES module or in a function wrapper called\n // without setting `this` properly.\n // Note that base.js can't usefully be imported as an ES module, but it may\n // be compiled into bundles that are loadable as ES modules.\n this ||\n // https://developer.mozilla.org/en-US/docs/Web/API/Window/self\n // For in-page browser environments and workers.\n self;\n\n\n/**\n * A hook for overriding the define values in uncompiled mode.\n *\n * In uncompiled mode, `CLOSURE_UNCOMPILED_DEFINES` may be defined before\n * loading base.js. If a key is defined in `CLOSURE_UNCOMPILED_DEFINES`,\n * `goog.define` will use the value instead of the default value. This\n * allows flags to be overwritten without compilation (this is normally\n * accomplished with the compiler's \"define\" flag).\n *\n * Example:\n * <pre>\n * var CLOSURE_UNCOMPILED_DEFINES = {'goog.DEBUG': false};\n * </pre>\n *\n * @type {Object<string, (string|number|boolean)>|undefined}\n */\ngoog.global.CLOSURE_UNCOMPILED_DEFINES;\n\n\n/**\n * A hook for overriding the define values in uncompiled or compiled mode,\n * like CLOSURE_UNCOMPILED_DEFINES but effective in compiled code. In\n * uncompiled code CLOSURE_UNCOMPILED_DEFINES takes precedence.\n *\n * Also unlike CLOSURE_UNCOMPILED_DEFINES the values must be number, boolean or\n * string literals or the compiler will emit an error.\n *\n * While any @define value may be set, only those set with goog.define will be\n * effective for uncompiled code.\n *\n * Example:\n * <pre>\n * var CLOSURE_DEFINES = {'goog.DEBUG': false} ;\n * </pre>\n *\n * Currently the Closure Compiler will only recognize very simple definitions of\n * this value when looking for values to apply to compiled code and ignore all\n * other references. Specifically, it looks the value defined at the variable\n * declaration, as with the example above.\n *\n * TODO(user): Improve the recognized definitions.\n *\n * @type {!Object<string, (string|number|boolean)>|null|undefined}\n */\ngoog.global.CLOSURE_DEFINES;\n\n\n/**\n * Builds an object structure for the provided namespace path, ensuring that\n * names that already exist are not overwritten. For example:\n * \"a.b.c\" -> a = {};a.b={};a.b.c={};\n * Used by goog.provide and goog.exportSymbol.\n * @param {string} name The name of the object that this file defines.\n * @param {*=} object The object to expose at the end of the path.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether object should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @param {?Object=} objectToExportTo The object to add the path to; if this\n * field is not specified, its value defaults to `goog.global`.\n * @private\n */\ngoog.exportPath_ = function(name, object, overwriteImplicit, objectToExportTo) {\n var parts = name.split('.');\n var cur = objectToExportTo || goog.global;\n\n // Internet Explorer exhibits strange behavior when throwing errors from\n // methods externed in this manner. See the testExportSymbolExceptions in\n // base_test.html for an example.\n if (!(parts[0] in cur) && typeof cur.execScript != 'undefined') {\n cur.execScript('var ' + parts[0]);\n }\n\n for (var part; parts.length && (part = parts.shift());) {\n if (!parts.length && object !== undefined) {\n if (!overwriteImplicit && goog.isObject(object) &&\n goog.isObject(cur[part])) {\n // Merge properties on object (the input parameter) with the existing\n // implicitly defined namespace, so as to not clobber previously\n // defined child namespaces.\n for (var prop in object) {\n if (object.hasOwnProperty(prop)) {\n cur[part][prop] = object[prop];\n }\n }\n } else {\n // Either there is no existing implicit namespace, or overwriteImplicit\n // is set to true, so directly assign object (the input parameter) to\n // the namespace.\n cur[part] = object;\n }\n } else if (cur[part] && cur[part] !== Object.prototype[part]) {\n cur = cur[part];\n } else {\n cur = cur[part] = {};\n }\n }\n};\n\n\n/**\n * Defines a named value. In uncompiled mode, the value is retrieved from\n * CLOSURE_DEFINES or CLOSURE_UNCOMPILED_DEFINES if the object is defined and\n * has the property specified, and otherwise used the defined defaultValue.\n * When compiled the default can be overridden using the compiler options or the\n * value set in the CLOSURE_DEFINES object. Returns the defined value so that it\n * can be used safely in modules. Note that the value type MUST be either\n * boolean, number, or string.\n *\n * @param {string} name The distinguished name to provide.\n * @param {T} defaultValue\n * @return {T} The defined value.\n * @template T\n */\ngoog.define = function(name, defaultValue) {\n var value = defaultValue;\n if (!COMPILED) {\n var uncompiledDefines = goog.global.CLOSURE_UNCOMPILED_DEFINES;\n var defines = goog.global.CLOSURE_DEFINES;\n if (uncompiledDefines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (uncompiledDefines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(uncompiledDefines, name)) {\n value = uncompiledDefines[name];\n } else if (\n defines &&\n // Anti DOM-clobbering runtime check (b/37736576).\n /** @type {?} */ (defines).nodeType === undefined &&\n Object.prototype.hasOwnProperty.call(defines, name)) {\n value = defines[name];\n }\n }\n return value;\n};\n\n\n/**\n * @define {number} Integer year indicating the set of browser features that are\n * guaranteed to be present. This is defined to include exactly features that\n * work correctly on all \"modern\" browsers that are stable on January 1 of the\n * specified year. For example,\n * ```js\n * if (goog.FEATURESET_YEAR >= 2019) {\n * // use APIs known to be available on all major stable browsers Jan 1, 2019\n * } else {\n * // polyfill for older browsers\n * }\n * ```\n * This is intended to be the primary define for removing\n * unnecessary browser compatibility code (such as ponyfills and workarounds),\n * and should inform the default value for most other defines:\n * ```js\n * const ASSUME_NATIVE_PROMISE =\n * goog.define('ASSUME_NATIVE_PROMISE', goog.FEATURESET_YEAR >= 2016);\n * ```\n *\n * The default assumption is that IE9 is the lowest supported browser, which was\n * first available Jan 1, 2012.\n *\n * TODO(user): Reference more thorough documentation when it's available.\n */\ngoog.FEATURESET_YEAR = goog.define('goog.FEATURESET_YEAR', 2012);\n\n\n/**\n * @define {boolean} DEBUG is provided as a convenience so that debugging code\n * that should not be included in a production. It can be easily stripped\n * by specifying --define goog.DEBUG=false to the Closure Compiler aka\n * JSCompiler. For example, most toString() methods should be declared inside an\n * \"if (goog.DEBUG)\" conditional because they are generally used for debugging\n * purposes and it is difficult for the JSCompiler to statically determine\n * whether they are used.\n */\ngoog.DEBUG = goog.define('goog.DEBUG', true);\n\n\n/**\n * @define {string} LOCALE defines the locale being used for compilation. It is\n * used to select locale specific data to be compiled in js binary. BUILD rule\n * can specify this value by \"--define goog.LOCALE=<locale_name>\" as a compiler\n * option.\n *\n * Take into account that the locale code format is important. You should use\n * the canonical Unicode format with hyphen as a delimiter. Language must be\n * lowercase, Language Script - Capitalized, Region - UPPERCASE.\n * There are few examples: pt-BR, en, en-US, sr-Latin-BO, zh-Hans-CN.\n *\n * See more info about locale codes here:\n * http://www.unicode.org/reports/tr35/#Unicode_Language_and_Locale_Identifiers\n *\n * For language codes you should use values defined by ISO 693-1. See it here\n * http://www.w3.org/WAI/ER/IG/ert/iso639.htm. There is only one exception from\n * this rule: the Hebrew language. For legacy reasons the old code (iw) should\n * be used instead of the new code (he).\n *\n */\ngoog.LOCALE = goog.define('goog.LOCALE', 'en'); // default to en\n\n\n/**\n * This method is intended to be used for bookkeeping purposes. We would\n * like to distinguish uses of goog.LOCALE used for code stripping purposes\n * and uses of goog.LOCALE for other uses (such as URL parameters).\n *\n * This allows us to ban direct uses of goog.LOCALE and to ensure that all\n * code has been transformed to our new localization build scheme.\n *\n * @return {string}\n *\n */\ngoog.getLocale = function() {\n return goog.LOCALE;\n};\n\n\n/**\n * @define {boolean} Whether this code is running on trusted sites.\n *\n * On untrusted sites, several native functions can be defined or overridden by\n * external libraries like Prototype, Datejs, and JQuery and setting this flag\n * to false forces closure to use its own implementations when possible.\n *\n * If your JavaScript can be loaded by a third party site and you are wary about\n * relying on non-standard implementations, specify\n * \"--define goog.TRUSTED_SITE=false\" to the compiler.\n */\ngoog.TRUSTED_SITE = goog.define('goog.TRUSTED_SITE', true);\n\n\n/**\n * @define {boolean} Whether code that calls {@link goog.setTestOnly} should\n * be disallowed in the compilation unit.\n */\ngoog.DISALLOW_TEST_ONLY_CODE =\n goog.define('goog.DISALLOW_TEST_ONLY_CODE', COMPILED && !goog.DEBUG);\n\n\n/**\n * @define {boolean} Whether to use a Chrome app CSP-compliant method for\n * loading scripts via goog.require. @see appendScriptSrcNode_.\n */\ngoog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING =\n goog.define('goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING', false);\n\n\n/**\n * Defines a namespace in Closure.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * The presence of one or more goog.provide() calls in a file indicates\n * that the file defines the given objects/namespaces.\n * Provided symbols must not be null or undefined.\n *\n * In addition, goog.provide() creates the object stubs for a namespace\n * (for example, goog.provide(\"goog.foo.bar\") will create the object\n * goog.foo.bar if it does not already exist).\n *\n * Build tools also scan for provide/require/module statements\n * to discern dependencies, build dependency files (see deps.js), etc.\n *\n * @see goog.require\n * @see goog.module\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * deprecated Use goog.module (see b/159289405)\n */\ngoog.provide = function(name) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.provide cannot be used within a module.');\n }\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n }\n\n goog.constructNamespace_(name);\n};\n\n\n/**\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\".\n * @param {?Object=} object The object to embed in the namespace.\n * @param {boolean=} overwriteImplicit If object is set and a previous call\n * implicitly constructed the namespace given by name, this parameter\n * controls whether opt_obj should overwrite the implicitly constructed\n * namespace or be merged into it. Defaults to false.\n * @private\n */\ngoog.constructNamespace_ = function(name, object, overwriteImplicit) {\n if (!COMPILED) {\n delete goog.implicitNamespaces_[name];\n\n var namespace = name;\n while ((namespace = namespace.substring(0, namespace.lastIndexOf('.')))) {\n if (goog.getObjectByName(namespace)) {\n break;\n }\n goog.implicitNamespaces_[namespace] = true;\n }\n }\n\n goog.exportPath_(name, object, overwriteImplicit);\n};\n\n\n/**\n * According to the CSP3 spec a nonce must be a valid base64 string.\n * @see https://www.w3.org/TR/CSP3/#grammardef-base64-value\n * @private @const\n */\ngoog.NONCE_PATTERN_ = /^[\\w+/_-]+[=]{0,2}$/;\n\n\n/**\n * Returns CSP nonce, if set for any script tag.\n * @param {?Window=} opt_window The window context used to retrieve the nonce.\n * Defaults to global context.\n * @return {string} CSP nonce or empty string if no nonce is present.\n * @private\n */\ngoog.getScriptNonce_ = function(opt_window) {\n var doc = (opt_window || goog.global).document;\n var script = doc.querySelector && doc.querySelector('script[nonce]');\n if (script) {\n // Try to get the nonce from the IDL property first, because browsers that\n // implement additional nonce protection features (currently only Chrome) to\n // prevent nonce stealing via CSS do not expose the nonce via attributes.\n // See https://github.com/whatwg/html/issues/2369\n var nonce = script['nonce'] || script.getAttribute('nonce');\n if (nonce && goog.NONCE_PATTERN_.test(nonce)) {\n return nonce;\n }\n }\n return '';\n};\n\n\n/**\n * Module identifier validation regexp.\n * Note: This is a conservative check, it is very possible to be more lenient,\n * the primary exclusion here is \"/\" and \"\\\" and a leading \".\", these\n * restrictions are intended to leave the door open for using goog.require\n * with relative file paths rather than module identifiers.\n * @private\n */\ngoog.VALID_MODULE_RE_ = /^[a-zA-Z_$][a-zA-Z0-9._$]*$/;\n\n\n/**\n * Defines a module in Closure.\n *\n * Marks that this file must be loaded as a module and claims the namespace.\n *\n * A namespace may only be defined once in a codebase. It may be defined using\n * goog.provide() or goog.module().\n *\n * goog.module() has three requirements:\n * - goog.module may not be used in the same file as goog.provide.\n * - goog.module must be the first statement in the file.\n * - only one goog.module is allowed per file.\n *\n * When a goog.module annotated file is loaded, it is enclosed in\n * a strict function closure. This means that:\n * - any variables declared in a goog.module file are private to the file\n * (not global), though the compiler is expected to inline the module.\n * - The code must obey all the rules of \"strict\" JavaScript.\n * - the file will be marked as \"use strict\"\n *\n * NOTE: unlike goog.provide, goog.module does not declare any symbols by\n * itself. If declared symbols are desired, use\n * goog.module.declareLegacyNamespace().\n *\n *\n * See the public goog.module proposal: http://goo.gl/Va1hin\n *\n * @param {string} name Namespace provided by this file in the form\n * \"goog.package.part\", is expected but not required.\n * @return {void}\n */\ngoog.module = function(name) {\n if (typeof name !== 'string' || !name ||\n name.search(goog.VALID_MODULE_RE_) == -1) {\n throw new Error('Invalid module identifier');\n }\n if (!goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'Module ' + name + ' has been loaded incorrectly. Note, ' +\n 'modules cannot be loaded as normal scripts. They require some kind of ' +\n 'pre-processing step. You\\'re likely trying to load a module via a ' +\n 'script tag or as a part of a concatenated bundle without rewriting the ' +\n 'module. For more info see: ' +\n 'https://github.com/google/closure-library/wiki/goog.module:-an-ES6-module-like-alternative-to-goog.provide.');\n }\n if (goog.moduleLoaderState_.moduleName) {\n throw new Error('goog.module may only be called once per module.');\n }\n\n // Store the module name for the loader.\n goog.moduleLoaderState_.moduleName = name;\n if (!COMPILED) {\n // Ensure that the same namespace isn't provided twice.\n // A goog.module/goog.provide maps a goog.require to a specific file\n if (goog.isProvided_(name)) {\n throw new Error('Namespace \"' + name + '\" already declared.');\n }\n delete goog.implicitNamespaces_[name];\n }\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n *\n * Note: This is not an alternative to goog.require, it does not\n * indicate a hard dependency, instead it is used to indicate\n * an optional dependency or to access the exports of a module\n * that has already been loaded.\n * @suppress {missingProvide}\n */\ngoog.module.get = function(name) {\n return goog.module.getInternal_(name);\n};\n\n\n/**\n * @param {string} name The module identifier.\n * @return {?} The module exports for an already loaded module or null.\n * @private\n */\ngoog.module.getInternal_ = function(name) {\n if (!COMPILED) {\n if (name in goog.loadedModules_) {\n return goog.loadedModules_[name].exports;\n } else if (!goog.implicitNamespaces_[name]) {\n var ns = goog.getObjectByName(name);\n return ns != null ? ns : null;\n }\n }\n return null;\n};\n\n\n/**\n * Types of modules the debug loader can load.\n * @enum {string}\n */\ngoog.ModuleType = {\n ES6: 'es6',\n GOOG: 'goog'\n};\n\n\n/**\n * @private {?{\n * moduleName: (string|undefined),\n * declareLegacyNamespace:boolean,\n * type: ?goog.ModuleType\n * }}\n */\ngoog.moduleLoaderState_ = null;\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module or an es6 module is currently being\n * initialized.\n */\ngoog.isInModuleLoader_ = function() {\n return goog.isInGoogModuleLoader_() || goog.isInEs6ModuleLoader_();\n};\n\n\n/**\n * @private\n * @return {boolean} Whether a goog.module is currently being initialized.\n */\ngoog.isInGoogModuleLoader_ = function() {\n return !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.GOOG;\n};\n\n\n/**\n * @private\n * @return {boolean} Whether an es6 module is currently being initialized.\n */\ngoog.isInEs6ModuleLoader_ = function() {\n var inLoader = !!goog.moduleLoaderState_ &&\n goog.moduleLoaderState_.type == goog.ModuleType.ES6;\n\n if (inLoader) {\n return true;\n }\n\n var jscomp = goog.global['$jscomp'];\n\n if (jscomp) {\n // jscomp may not have getCurrentModulePath if this is a compiled bundle\n // that has some of the runtime, but not all of it. This can happen if\n // optimizations are turned on so the unused runtime is removed but renaming\n // and Closure pass are off (so $jscomp is still named $jscomp and the\n // goog.provide/require calls still exist).\n if (typeof jscomp.getCurrentModulePath != 'function') {\n return false;\n }\n\n // Bundled ES6 module.\n return !!jscomp.getCurrentModulePath();\n }\n\n return false;\n};\n\n\n/**\n * Provide the module's exports as a globally accessible object under the\n * module's declared name. This is intended to ease migration to goog.module\n * for files that have existing usages.\n * @suppress {missingProvide}\n */\ngoog.module.declareLegacyNamespace = function() {\n if (!COMPILED && !goog.isInGoogModuleLoader_()) {\n throw new Error(\n 'goog.module.declareLegacyNamespace must be called from ' +\n 'within a goog.module');\n }\n if (!COMPILED && !goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.module must be called prior to ' +\n 'goog.module.declareLegacyNamespace.');\n }\n goog.moduleLoaderState_.declareLegacyNamespace = true;\n};\n\n\n/**\n * Associates an ES6 module with a Closure module ID so that is available via\n * goog.require. The associated ID acts like a goog.module ID - it does not\n * create any global names, it is merely available via goog.require /\n * goog.module.get / goog.forwardDeclare / goog.requireType. goog.require and\n * goog.module.get will return the entire module as if it was import *'d. This\n * allows Closure files to reference ES6 modules for the sake of migration.\n *\n * @param {string} namespace\n * @suppress {missingProvide}\n */\ngoog.declareModuleId = function(namespace) {\n if (!COMPILED) {\n if (!goog.isInEs6ModuleLoader_()) {\n throw new Error(\n 'goog.declareModuleId may only be called from ' +\n 'within an ES6 module');\n }\n if (goog.moduleLoaderState_ && goog.moduleLoaderState_.moduleName) {\n throw new Error(\n 'goog.declareModuleId may only be called once per module.');\n }\n if (namespace in goog.loadedModules_) {\n throw new Error(\n 'Module with namespace \"' + namespace + '\" already exists.');\n }\n }\n if (goog.moduleLoaderState_) {\n // Not bundled - debug loading.\n goog.moduleLoaderState_.moduleName = namespace;\n } else {\n // Bundled - not debug loading, no module loader state.\n var jscomp = goog.global['$jscomp'];\n if (!jscomp || typeof jscomp.getCurrentModulePath != 'function') {\n throw new Error(\n 'Module with namespace \"' + namespace +\n '\" has been loaded incorrectly.');\n }\n var exports = jscomp.require(jscomp.getCurrentModulePath());\n goog.loadedModules_[namespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: namespace\n };\n }\n};\n\n\n/**\n * Marks that the current file should only be used for testing, and never for\n * live code in production.\n *\n * In the case of unit tests, the message may optionally be an exact namespace\n * for the test (e.g. 'goog.stringTest'). The linter will then ignore the extra\n * provide (if not explicitly defined in the code).\n *\n * @param {string=} opt_message Optional message to add to the error that's\n * raised when used in production code.\n */\ngoog.setTestOnly = function(opt_message) {\n if (goog.DISALLOW_TEST_ONLY_CODE) {\n opt_message = opt_message || '';\n throw new Error(\n 'Importing test-only code into non-debug environment' +\n (opt_message ? ': ' + opt_message : '.'));\n }\n};\n\n\n/**\n * Forward declares a symbol. This is an indication to the compiler that the\n * symbol may be used in the source yet is not required and may not be provided\n * in compilation.\n *\n * The most common usage of forward declaration is code that takes a type as a\n * function parameter but does not need to require it. By forward declaring\n * instead of requiring, no hard dependency is made, and (if not required\n * elsewhere) the namespace may never be required and thus, not be pulled\n * into the JavaScript binary. If it is required elsewhere, it will be type\n * checked as normal.\n *\n * Before using goog.forwardDeclare, please read the documentation at\n * https://github.com/google/closure-compiler/wiki/Bad-Type-Annotation to\n * understand the options and tradeoffs when working with forward declarations.\n *\n * @param {string} name The namespace to forward declare in the form of\n * \"goog.package.part\".\n * @deprecated See go/noforwarddeclaration, Use `goog.requireType` instead.\n */\ngoog.forwardDeclare = function(name) {};\n\n\n/**\n * Forward declare type information. Used to assign types to goog.global\n * referenced object that would otherwise result in unknown type references\n * and thus block property disambiguation.\n */\ngoog.forwardDeclare('Document');\ngoog.forwardDeclare('HTMLScriptElement');\ngoog.forwardDeclare('XMLHttpRequest');\n\n\nif (!COMPILED) {\n /**\n * Check if the given name has been goog.provided. This will return false for\n * names that are available only as implicit namespaces.\n * @param {string} name name of the object to look for.\n * @return {boolean} Whether the name has been provided.\n * @private\n */\n goog.isProvided_ = function(name) {\n return (name in goog.loadedModules_) ||\n (!goog.implicitNamespaces_[name] && goog.getObjectByName(name) != null);\n };\n\n /**\n * Namespaces implicitly defined by goog.provide. For example,\n * goog.provide('goog.events.Event') implicitly declares that 'goog' and\n * 'goog.events' must be namespaces.\n *\n * @type {!Object<string, (boolean|undefined)>}\n * @private\n */\n goog.implicitNamespaces_ = {'goog.module': true};\n\n // NOTE: We add goog.module as an implicit namespace as goog.module is defined\n // here and because the existing module package has not been moved yet out of\n // the goog.module namespace. This satisifies both the debug loader and\n // ahead-of-time dependency management.\n}\n\n\n/**\n * Returns an object based on its fully qualified external name. The object\n * is not found if null or undefined. If you are using a compilation pass that\n * renames property names beware that using this function will not find renamed\n * properties.\n *\n * @param {string} name The fully qualified name.\n * @param {Object=} opt_obj The object within which to look; default is\n * |goog.global|.\n * @return {?} The value (object or primitive) or, if not found, null.\n */\ngoog.getObjectByName = function(name, opt_obj) {\n var parts = name.split('.');\n var cur = opt_obj || goog.global;\n for (var i = 0; i < parts.length; i++) {\n cur = cur[parts[i]];\n if (cur == null) {\n return null;\n }\n }\n return cur;\n};\n\n\n/**\n * Adds a dependency from a file to the files it requires.\n * @param {string} relPath The path to the js file.\n * @param {!Array<string>} provides An array of strings with\n * the names of the objects this file provides.\n * @param {!Array<string>} requires An array of strings with\n * the names of the objects this file requires.\n * @param {boolean|!Object<string>=} opt_loadFlags Parameters indicating\n * how the file must be loaded. The boolean 'true' is equivalent\n * to {'module': 'goog'} for backwards-compatibility. Valid properties\n * and values include {'module': 'goog'} and {'lang': 'es6'}.\n */\ngoog.addDependency = function(relPath, provides, requires, opt_loadFlags) {\n if (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n goog.debugLoader_.addDependency(relPath, provides, requires, opt_loadFlags);\n }\n};\n\n\n// NOTE(nnaze): The debug DOM loader was included in base.js as an original way\n// to do \"debug-mode\" development. The dependency system can sometimes be\n// confusing, as can the debug DOM loader's asynchronous nature.\n//\n// With the DOM loader, a call to goog.require() is not blocking -- the script\n// will not load until some point after the current script. If a namespace is\n// needed at runtime, it needs to be defined in a previous script, or loaded via\n// require() with its registered dependencies.\n//\n// User-defined namespaces may need their own deps file. For a reference on\n// creating a deps file, see:\n// Externally: https://developers.google.com/closure/library/docs/depswriter\n//\n// Because of legacy clients, the DOM loader can't be easily removed from\n// base.js. Work was done to make it disableable or replaceable for\n// different environments (DOM-less JavaScript interpreters like Rhino or V8,\n// for example). See bootstrap/ for more information.\n\n\n/**\n * @define {boolean} Whether to enable the debug loader.\n *\n * If enabled, a call to goog.require() will attempt to load the namespace by\n * appending a script tag to the DOM (if the namespace has been registered).\n *\n * If disabled, goog.require() will simply assert that the namespace has been\n * provided (and depend on the fact that some outside tool correctly ordered\n * the script).\n */\ngoog.ENABLE_DEBUG_LOADER = goog.define('goog.ENABLE_DEBUG_LOADER', true);\n\n\n/**\n * @param {string} msg\n * @private\n */\ngoog.logToConsole_ = function(msg) {\n if (goog.global.console) {\n goog.global.console['error'](msg);\n }\n};\n\n\n/**\n * Implements a system for the dynamic resolution of dependencies that works in\n * parallel with the BUILD system.\n *\n * Note that all calls to goog.require will be stripped by the compiler.\n *\n * @see goog.provide\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?} If called within a goog.module or ES6 module file, the associated\n * namespace or module otherwise null.\n */\ngoog.require = function(namespace) {\n if (!COMPILED) {\n // Might need to lazy load on old IE.\n if (goog.ENABLE_DEBUG_LOADER) {\n goog.debugLoader_.requested(namespace);\n }\n\n // If the object already exists we do not need to do anything.\n if (goog.isProvided_(namespace)) {\n if (goog.isInModuleLoader_()) {\n return goog.module.getInternal_(namespace);\n }\n } else if (goog.ENABLE_DEBUG_LOADER) {\n var moduleLoaderState = goog.moduleLoaderState_;\n goog.moduleLoaderState_ = null;\n try {\n goog.debugLoader_.load_(namespace);\n } finally {\n goog.moduleLoaderState_ = moduleLoaderState;\n }\n }\n\n return null;\n }\n};\n\n\n/**\n * Requires a symbol for its type information. This is an indication to the\n * compiler that the symbol may appear in type annotations, yet it is not\n * referenced at runtime.\n *\n * When called within a goog.module or ES6 module file, the return value may be\n * assigned to or destructured into a variable, but it may not be otherwise used\n * in code outside of a type annotation.\n *\n * Note that all calls to goog.requireType will be stripped by the compiler.\n *\n * @param {string} namespace Namespace (as was given in goog.provide,\n * goog.module, or goog.declareModuleId) in the form\n * \"goog.package.part\".\n * @return {?}\n */\ngoog.requireType = function(namespace) {\n // Return an empty object so that single-level destructuring of the return\n // value doesn't crash at runtime when using the debug loader. Multi-level\n // destructuring isn't supported.\n return {};\n};\n\n\n/**\n * Path for included scripts.\n * @type {string}\n */\ngoog.basePath = '';\n\n\n/**\n * A hook for overriding the base path.\n * @type {string|undefined}\n */\ngoog.global.CLOSURE_BASE_PATH;\n\n\n/**\n * Whether to attempt to load Closure's deps file. By default, when uncompiled,\n * deps files will attempt to be loaded.\n * @type {boolean|undefined}\n */\ngoog.global.CLOSURE_NO_DEPS;\n\n\n/**\n * A function to import a single script. This is meant to be overridden when\n * Closure is being run in non-HTML contexts, such as web workers. It's defined\n * in the global scope so that it can be set before base.js is loaded, which\n * allows deps.js to be imported properly.\n *\n * The first parameter the script source, which is a relative URI. The second,\n * optional parameter is the script contents, in the event the script needed\n * transformation. It should return true if the script was imported, false\n * otherwise.\n * @type {(function(string, string=): boolean)|undefined}\n */\ngoog.global.CLOSURE_IMPORT_SCRIPT;\n\n\n/**\n * Null function used for default values of callbacks, etc.\n * @return {void} Nothing.\n * @deprecated use '()=>{}' or 'function(){}' instead.\n */\ngoog.nullFunction = function() {};\n\n\n/**\n * When defining a class Foo with an abstract method bar(), you can do:\n * Foo.prototype.bar = goog.abstractMethod\n *\n * Now if a subclass of Foo fails to override bar(), an error will be thrown\n * when bar() is invoked.\n *\n * @type {!Function}\n * @throws {Error} when invoked to indicate the method should be overridden.\n * @deprecated Use \"@abstract\" annotation instead of goog.abstractMethod in new\n * code. See\n * https://github.com/google/closure-compiler/wiki/@abstract-classes-and-methods\n */\ngoog.abstractMethod = function() {\n throw new Error('unimplemented abstract method');\n};\n\n\n/**\n * Adds a `getInstance` static method that always returns the same\n * instance object.\n * @param {!Function} ctor The constructor for the class to add the static\n * method to.\n * @suppress {missingProperties} 'instance_' isn't a property on 'Function'\n * but we don't have a better type to use here.\n */\ngoog.addSingletonGetter = function(ctor) {\n // instance_ is immediately set to prevent issues with sealed constructors\n // such as are encountered when a constructor is returned as the export object\n // of a goog.module in unoptimized code.\n // Delcare type to avoid conformance violations that ctor.instance_ is unknown\n /** @type {undefined|!Object} @suppress {underscore} */\n ctor.instance_ = undefined;\n ctor.getInstance = function() {\n if (ctor.instance_) {\n return ctor.instance_;\n }\n if (goog.DEBUG) {\n // NOTE: JSCompiler can't optimize away Array#push.\n goog.instantiatedSingletons_[goog.instantiatedSingletons_.length] = ctor;\n }\n // Cast to avoid conformance violations that ctor.instance_ is unknown\n return /** @type {!Object|undefined} */ (ctor.instance_) = new ctor;\n };\n};\n\n\n/**\n * All singleton classes that have been instantiated, for testing. Don't read\n * it directly, use the `goog.testing.singleton` module. The compiler\n * removes this variable if unused.\n * @type {!Array<!Function>}\n * @private\n */\ngoog.instantiatedSingletons_ = [];\n\n\n/**\n * @define {boolean} Whether to load goog.modules using `eval` when using\n * the debug loader. This provides a better debugging experience as the\n * source is unmodified and can be edited using Chrome Workspaces or similar.\n * However in some environments the use of `eval` is banned\n * so we provide an alternative.\n */\ngoog.LOAD_MODULE_USING_EVAL = goog.define('goog.LOAD_MODULE_USING_EVAL', true);\n\n\n/**\n * @define {boolean} Whether the exports of goog.modules should be sealed when\n * possible.\n */\ngoog.SEAL_MODULE_EXPORTS = goog.define('goog.SEAL_MODULE_EXPORTS', goog.DEBUG);\n\n\n/**\n * The registry of initialized modules:\n * The module identifier or path to module exports map.\n * @private @const {!Object<string, {exports:?,type:string,moduleId:string}>}\n */\ngoog.loadedModules_ = {};\n\n\n/**\n * True if the debug loader enabled and used.\n * @const {boolean}\n */\ngoog.DEPENDENCIES_ENABLED = !COMPILED && goog.ENABLE_DEBUG_LOADER;\n\n\n/**\n * @define {string} How to decide whether to transpile. Valid values\n * are 'always', 'never', and 'detect'. The default ('detect') is to\n * use feature detection to determine which language levels need\n * transpilation.\n */\n// NOTE(sdh): we could expand this to accept a language level to bypass\n// detection: e.g. goog.TRANSPILE == 'es5' would transpile ES6 files but\n// would leave ES3 and ES5 files alone.\ngoog.TRANSPILE = goog.define('goog.TRANSPILE', 'detect');\n\n/**\n * @define {boolean} If true assume that ES modules have already been\n * transpiled by the jscompiler (in the same way that transpile.js would\n * transpile them - to jscomp modules). Useful only for servers that wish to use\n * the debug loader and transpile server side. Thus this is only respected if\n * goog.TRANSPILE is \"never\".\n */\ngoog.ASSUME_ES_MODULES_TRANSPILED =\n goog.define('goog.ASSUME_ES_MODULES_TRANSPILED', false);\n\n\n/**\n * @define {string} If a file needs to be transpiled what the output language\n * should be. By default this is the highest language level this file detects\n * the current environment supports. Generally this flag should not be set, but\n * it could be useful to override. Example: If the current environment supports\n * ES6 then by default ES7+ files will be transpiled to ES6, unless this is\n * overridden.\n *\n * Valid values include: es3, es5, es6, es7, and es8. Anything not recognized\n * is treated as es3.\n *\n * Note that setting this value does not force transpilation. Just if\n * transpilation occurs this will be the output. So this is most useful when\n * goog.TRANSPILE is set to 'always' and then forcing the language level to be\n * something lower than what the environment detects.\n */\ngoog.TRANSPILE_TO_LANGUAGE = goog.define('goog.TRANSPILE_TO_LANGUAGE', '');\n\n\n/**\n * @define {string} Path to the transpiler. Executing the script at this\n * path (relative to base.js) should define a function $jscomp.transpile.\n */\ngoog.TRANSPILER = goog.define('goog.TRANSPILER', 'transpile.js');\n\n\n/**\n * @define {string} Trusted Types policy name. If non-empty then Closure will\n * use Trusted Types.\n */\ngoog.TRUSTED_TYPES_POLICY_NAME =\n goog.define('goog.TRUSTED_TYPES_POLICY_NAME', 'goog');\n\n\n/**\n * @package {?boolean}\n * Visible for testing.\n */\ngoog.hasBadLetScoping = null;\n\n\n/**\n * @param {function(?):?|string} moduleDef The module definition.\n */\ngoog.loadModule = function(moduleDef) {\n // NOTE: we allow function definitions to be either in the from\n // of a string to eval (which keeps the original source intact) or\n // in a eval forbidden environment (CSP) we allow a function definition\n // which in its body must call `goog.module`, and return the exports\n // of the module.\n var previousState = goog.moduleLoaderState_;\n try {\n goog.moduleLoaderState_ = {\n moduleName: '',\n declareLegacyNamespace: false,\n type: goog.ModuleType.GOOG\n };\n var origExports = {};\n var exports = origExports;\n if (typeof moduleDef === 'function') {\n exports = moduleDef.call(undefined, exports);\n } else if (typeof moduleDef === 'string') {\n exports = goog.loadModuleFromSource_.call(undefined, exports, moduleDef);\n } else {\n throw new Error('Invalid module definition');\n }\n\n var moduleName = goog.moduleLoaderState_.moduleName;\n if (typeof moduleName === 'string' && moduleName) {\n // Don't seal legacy namespaces as they may be used as a parent of\n // another namespace\n if (goog.moduleLoaderState_.declareLegacyNamespace) {\n // Whether exports was overwritten via default export assignment.\n // This is important for legacy namespaces as it dictates whether\n // previously a previously loaded implicit namespace should be clobbered\n // or not.\n var isDefaultExport = origExports !== exports;\n goog.constructNamespace_(moduleName, exports, isDefaultExport);\n } else if (\n goog.SEAL_MODULE_EXPORTS && Object.seal &&\n typeof exports == 'object' && exports != null) {\n Object.seal(exports);\n }\n\n var data = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: goog.moduleLoaderState_.moduleName\n };\n goog.loadedModules_[moduleName] = data;\n } else {\n throw new Error('Invalid module name \\\"' + moduleName + '\\\"');\n }\n } finally {\n goog.moduleLoaderState_ = previousState;\n }\n};\n\n\n/**\n * @private @const\n */\ngoog.loadModuleFromSource_ =\n /** @type {function(!Object, string):?} */ (function(exports) {\n // NOTE: we avoid declaring parameters or local variables here to avoid\n // masking globals or leaking values into the module definition.\n 'use strict';\n eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(arguments[1]));\n return exports;\n });\n\n\n/**\n * Normalize a file path by removing redundant \"..\" and extraneous \".\" file\n * path components.\n * @param {string} path\n * @return {string}\n * @private\n */\ngoog.normalizePath_ = function(path) {\n var components = path.split('/');\n var i = 0;\n while (i < components.length) {\n if (components[i] == '.') {\n components.splice(i, 1);\n } else if (\n i && components[i] == '..' && components[i - 1] &&\n components[i - 1] != '..') {\n components.splice(--i, 2);\n } else {\n i++;\n }\n }\n return components.join('/');\n};\n\n\n/**\n * Provides a hook for loading a file when using Closure's goog.require() API\n * with goog.modules. In particular this hook is provided to support Node.js.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_LOAD_FILE_SYNC;\n\n\n/**\n * Loads file by synchronous XHR. Should not be used in production environments.\n * @param {string} src Source URL.\n * @return {?string} File contents, or null if load failed.\n * @private\n */\ngoog.loadFileSync_ = function(src) {\n if (goog.global.CLOSURE_LOAD_FILE_SYNC) {\n return goog.global.CLOSURE_LOAD_FILE_SYNC(src);\n } else {\n try {\n /** @type {XMLHttpRequest} */\n var xhr = new goog.global['XMLHttpRequest']();\n xhr.open('get', src, false);\n xhr.send();\n // NOTE: Successful http: requests have a status of 200, but successful\n // file: requests may have a status of zero. Any other status, or a\n // thrown exception (particularly in case of file: requests) indicates\n // some sort of error, which we treat as a missing or unavailable file.\n return xhr.status == 0 || xhr.status == 200 ? xhr.responseText : null;\n } catch (err) {\n // No need to rethrow or log, since errors should show up on their own.\n return null;\n }\n }\n};\n\n\n/**\n * Lazily retrieves the transpiler and applies it to the source.\n * @param {string} code JS code.\n * @param {string} path Path to the code.\n * @param {string} target Language level output.\n * @return {string} The transpiled code.\n * @private\n */\ngoog.transpile_ = function(code, path, target) {\n var jscomp = goog.global['$jscomp'];\n if (!jscomp) {\n goog.global['$jscomp'] = jscomp = {};\n }\n var transpile = jscomp.transpile;\n if (!transpile) {\n var transpilerPath = goog.basePath + goog.TRANSPILER;\n var transpilerCode = goog.loadFileSync_(transpilerPath);\n if (transpilerCode) {\n // This must be executed synchronously, since by the time we know we\n // need it, we're about to load and write the ES6 code synchronously,\n // so a normal script-tag load will be too slow. Wrapped in a function\n // so that code is eval'd in the global scope.\n (function() {\n (0, eval)(transpilerCode + '\\n//# sourceURL=' + transpilerPath);\n }).call(goog.global);\n // Even though the transpiler is optional, if $gwtExport is found, it's\n // a sign the transpiler was loaded and the $jscomp.transpile *should*\n // be there.\n if (goog.global['$gwtExport'] && goog.global['$gwtExport']['$jscomp'] &&\n !goog.global['$gwtExport']['$jscomp']['transpile']) {\n throw new Error(\n 'The transpiler did not properly export the \"transpile\" ' +\n 'method. $gwtExport: ' + JSON.stringify(goog.global['$gwtExport']));\n }\n // transpile.js only exports a single $jscomp function, transpile. We\n // grab just that and add it to the existing definition of $jscomp which\n // contains the polyfills.\n goog.global['$jscomp'].transpile =\n goog.global['$gwtExport']['$jscomp']['transpile'];\n jscomp = goog.global['$jscomp'];\n transpile = jscomp.transpile;\n }\n }\n if (!transpile) {\n // The transpiler is an optional component. If it's not available then\n // replace it with a pass-through function that simply logs.\n var suffix = ' requires transpilation but no transpiler was found.';\n transpile = jscomp.transpile = function(code, path) {\n // TODO(sdh): figure out some way to get this error to show up\n // in test results, noting that the failure may occur in many\n // different ways, including in loadModule() before the test\n // runner even comes up.\n goog.logToConsole_(path + suffix);\n return code;\n };\n }\n // Note: any transpilation errors/warnings will be logged to the console.\n return transpile(code, path, target);\n};\n\n//==============================================================================\n// Language Enhancements\n//==============================================================================\n\n\n/**\n * This is a \"fixed\" version of the typeof operator. It differs from the typeof\n * operator in such a way that null returns 'null' and arrays return 'array'.\n * @param {?} value The value to get the type of.\n * @return {string} The name of the type.\n */\ngoog.typeOf = function(value) {\n var s = typeof value;\n\n if (s != 'object') {\n return s;\n }\n\n if (!value) {\n return 'null';\n }\n\n if (Array.isArray(value)) {\n return 'array';\n }\n return s;\n};\n\n\n/**\n * Returns true if the object looks like an array. To qualify as array like\n * the value needs to be either a NodeList or an object with a Number length\n * property. Note that for this function neither strings nor functions are\n * considered \"array-like\".\n *\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an array.\n */\ngoog.isArrayLike = function(val) {\n var type = goog.typeOf(val);\n // We do not use goog.isObject here in order to exclude function values.\n return type == 'array' || type == 'object' && typeof val.length == 'number';\n};\n\n\n/**\n * Returns true if the object looks like a Date. To qualify as Date-like the\n * value needs to be an object and have a getFullYear() function.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is a like a Date.\n */\ngoog.isDateLike = function(val) {\n return goog.isObject(val) && typeof val.getFullYear == 'function';\n};\n\n\n/**\n * Returns true if the specified value is an object. This includes arrays and\n * functions.\n * @param {?} val Variable to test.\n * @return {boolean} Whether variable is an object.\n */\ngoog.isObject = function(val) {\n var type = typeof val;\n return type == 'object' && val != null || type == 'function';\n // return Object(val) === val also works, but is slower, especially if val is\n // not an object.\n};\n\n\n/**\n * Gets a unique ID for an object. This mutates the object so that further calls\n * with the same object as a parameter returns the same value. The unique ID is\n * guaranteed to be unique across the current session amongst objects that are\n * passed into `getUid`. There is no guarantee that the ID is unique or\n * consistent across sessions. It is unsafe to generate unique ID for function\n * prototypes.\n *\n * @param {Object} obj The object to get the unique ID for.\n * @return {number} The unique ID for the object.\n */\ngoog.getUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n return Object.prototype.hasOwnProperty.call(obj, goog.UID_PROPERTY_) &&\n obj[goog.UID_PROPERTY_] ||\n (obj[goog.UID_PROPERTY_] = ++goog.uidCounter_);\n};\n\n\n/**\n * Whether the given object is already assigned a unique ID.\n *\n * This does not modify the object.\n *\n * @param {!Object} obj The object to check.\n * @return {boolean} Whether there is an assigned unique id for the object.\n */\ngoog.hasUid = function(obj) {\n return !!obj[goog.UID_PROPERTY_];\n};\n\n\n/**\n * Removes the unique ID from an object. This is useful if the object was\n * previously mutated using `goog.getUid` in which case the mutation is\n * undone.\n * @param {Object} obj The object to remove the unique ID field from.\n */\ngoog.removeUid = function(obj) {\n // TODO(arv): Make the type stricter, do not accept null.\n\n // In IE, DOM nodes are not instances of Object and throw an exception if we\n // try to delete. Instead we try to use removeAttribute.\n if (obj !== null && 'removeAttribute' in obj) {\n obj.removeAttribute(goog.UID_PROPERTY_);\n }\n\n try {\n delete obj[goog.UID_PROPERTY_];\n } catch (ex) {\n }\n};\n\n\n/**\n * Name for unique ID property. Initialized in a way to help avoid collisions\n * with other closure JavaScript on the same page.\n * @type {string}\n * @private\n */\ngoog.UID_PROPERTY_ = 'closure_uid_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * Counter for UID.\n * @type {number}\n * @private\n */\ngoog.uidCounter_ = 0;\n\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n *\n * WARNINGS:\n * <code>goog.cloneObject</code> does not detect reference loops. Objects that\n * refer to themselves will cause infinite recursion.\n *\n * <code>goog.cloneObject</code> is unaware of unique identifiers, and copies\n * UIDs created by <code>getUid</code> into cloned results.\n *\n * @param {*} obj The value to clone.\n * @return {*} A clone of the input value.\n * @deprecated goog.cloneObject is unsafe. Prefer the goog.object methods.\n */\ngoog.cloneObject = function(obj) {\n var type = goog.typeOf(obj);\n if (type == 'object' || type == 'array') {\n if (typeof obj.clone === 'function') {\n return obj.clone();\n }\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n }\n var clone = type == 'array' ? [] : {};\n for (var key in obj) {\n clone[key] = goog.cloneObject(obj[key]);\n }\n return clone;\n }\n\n return obj;\n};\n\n\n/**\n * A native implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindNative_ = function(fn, selfObj, var_args) {\n return /** @type {!Function} */ (fn.call.apply(fn.bind, arguments));\n};\n\n\n/**\n * A pure-JS implementation of goog.bind.\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @private\n */\ngoog.bindJs_ = function(fn, selfObj, var_args) {\n if (!fn) {\n throw new Error();\n }\n\n if (arguments.length > 2) {\n var boundArgs = Array.prototype.slice.call(arguments, 2);\n return function() {\n // Prepend the bound arguments to the current arguments.\n var newArgs = Array.prototype.slice.call(arguments);\n Array.prototype.unshift.apply(newArgs, boundArgs);\n return fn.apply(selfObj, newArgs);\n };\n\n } else {\n return function() {\n return fn.apply(selfObj, arguments);\n };\n }\n};\n\n\n/**\n * Partially applies this function to a particular 'this object' and zero or\n * more arguments. The result is a new function with some arguments of the first\n * function pre-filled and the value of this 'pre-specified'.\n *\n * Remaining arguments specified at call-time are appended to the pre-specified\n * ones.\n *\n * Also see: {@link #partial}.\n *\n * Usage:\n * <pre>var barMethBound = goog.bind(myFunction, myObj, 'arg1', 'arg2');\n * barMethBound('arg3', 'arg4');</pre>\n *\n * @param {?function(this:T, ...)} fn A function to partially apply.\n * @param {T} selfObj Specifies the object which this should point to when the\n * function is run.\n * @param {...*} var_args Additional arguments that are partially applied to the\n * function.\n * @return {!Function} A partially-applied form of the function goog.bind() was\n * invoked as a method of.\n * @template T\n * @suppress {deprecated} See above.\n * @deprecated use `=> {}` or Function.prototype.bind instead.\n */\ngoog.bind = function(fn, selfObj, var_args) {\n // TODO(nicksantos): narrow the type signature.\n if (Function.prototype.bind &&\n // NOTE(nicksantos): Somebody pulled base.js into the default Chrome\n // extension environment. This means that for Chrome extensions, they get\n // the implementation of Function.prototype.bind that calls goog.bind\n // instead of the native one. Even worse, we don't want to introduce a\n // circular dependency between goog.bind and Function.prototype.bind, so\n // we have to hack this to make sure it works correctly.\n Function.prototype.bind.toString().indexOf('native code') != -1) {\n goog.bind = goog.bindNative_;\n } else {\n goog.bind = goog.bindJs_;\n }\n return goog.bind.apply(null, arguments);\n};\n\n\n/**\n * Like goog.bind(), except that a 'this object' is not required. Useful when\n * the target function is already bound.\n *\n * Usage:\n * var g = goog.partial(f, arg1, arg2);\n * g(arg3, arg4);\n *\n * @param {Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.partial = function(fn, var_args) {\n var args = Array.prototype.slice.call(arguments, 1);\n return function() {\n // Clone the array (with slice()) and append additional arguments\n // to the existing arguments.\n var newArgs = args.slice();\n newArgs.push.apply(newArgs, arguments);\n return fn.apply(/** @type {?} */ (this), newArgs);\n };\n};\n\n\n/**\n * Copies all the members of a source object to a target object. This method\n * does not work on all browsers for all objects that contain keys such as\n * toString or hasOwnProperty. Use goog.object.extend for this purpose.\n *\n * NOTE: Some have advocated for the use of goog.mixin to setup classes\n * with multiple inheritence (traits, mixins, etc). However, as it simply\n * uses \"for in\", this is not compatible with ES6 classes whose methods are\n * non-enumerable. Changing this, would break cases where non-enumerable\n * properties are not expected.\n *\n * @param {Object} target Target.\n * @param {Object} source Source.\n * @deprecated Prefer Object.assign\n */\ngoog.mixin = function(target, source) {\n for (var x in source) {\n target[x] = source[x];\n }\n\n // For IE7 or lower, the for-in-loop does not contain any properties that are\n // not enumerable on the prototype object (for example, isPrototypeOf from\n // Object.prototype) but also it will not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n};\n\n\n/**\n * @return {number} An integer value representing the number of milliseconds\n * between midnight, January 1, 1970 and the current time.\n * @deprecated Use Date.now\n */\ngoog.now = function() {\n return Date.now();\n};\n\n\n/**\n * Evals JavaScript in the global scope.\n *\n * Throws an exception if neither execScript or eval is defined.\n * @param {string|!TrustedScript} script JavaScript string.\n */\ngoog.globalEval = function(script) {\n (0, eval)(script);\n};\n\n\n/**\n * Optional map of CSS class names to obfuscated names used with\n * goog.getCssName().\n * @private {!Object<string, string>|undefined}\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMapping_;\n\n\n/**\n * Optional obfuscation style for CSS class names. Should be set to either\n * 'BY_WHOLE' or 'BY_PART' if defined.\n * @type {string|undefined}\n * @private\n * @see goog.setCssNameMapping\n */\ngoog.cssNameMappingStyle_;\n\n\n\n/**\n * A hook for modifying the default behavior goog.getCssName. The function\n * if present, will receive the standard output of the goog.getCssName as\n * its input.\n *\n * @type {(function(string):string)|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAP_FN;\n\n\n/**\n * Handles strings that are intended to be used as CSS class names.\n *\n * This function works in tandem with @see goog.setCssNameMapping.\n *\n * Without any mapping set, the arguments are simple joined with a hyphen and\n * passed through unaltered.\n *\n * When there is a mapping, there are two possible styles in which these\n * mappings are used. In the BY_PART style, each part (i.e. in between hyphens)\n * of the passed in css name is rewritten according to the map. In the BY_WHOLE\n * style, the full css name is looked up in the map directly. If a rewrite is\n * not specified by the map, the compiler will output a warning.\n *\n * When the mapping is passed to the compiler, it will replace calls to\n * goog.getCssName with the strings from the mapping, e.g.\n * var x = goog.getCssName('foo');\n * var y = goog.getCssName(this.baseClass, 'active');\n * becomes:\n * var x = 'foo';\n * var y = this.baseClass + '-active';\n *\n * If one argument is passed it will be processed, if two are passed only the\n * modifier will be processed, as it is assumed the first argument was generated\n * as a result of calling goog.getCssName.\n *\n * @param {string} className The class name.\n * @param {string=} opt_modifier A modifier to be appended to the class name.\n * @return {string} The class name or the concatenation of the class name and\n * the modifier.\n */\ngoog.getCssName = function(className, opt_modifier) {\n // String() is used for compatibility with compiled soy where the passed\n // className can be non-string objects.\n if (String(className).charAt(0) == '.') {\n throw new Error(\n 'className passed in goog.getCssName must not start with \".\".' +\n ' You passed: ' + className);\n }\n\n var getMapping = function(cssName) {\n return goog.cssNameMapping_[cssName] || cssName;\n };\n\n var renameByParts = function(cssName) {\n // Remap all the parts individually.\n var parts = cssName.split('-');\n var mapped = [];\n for (var i = 0; i < parts.length; i++) {\n mapped.push(getMapping(parts[i]));\n }\n return mapped.join('-');\n };\n\n var rename;\n if (goog.cssNameMapping_) {\n rename =\n goog.cssNameMappingStyle_ == 'BY_WHOLE' ? getMapping : renameByParts;\n } else {\n rename = function(a) {\n return a;\n };\n }\n\n var result =\n opt_modifier ? className + '-' + rename(opt_modifier) : rename(className);\n\n // The special CLOSURE_CSS_NAME_MAP_FN allows users to specify further\n // processing of the class name.\n if (goog.global.CLOSURE_CSS_NAME_MAP_FN) {\n return goog.global.CLOSURE_CSS_NAME_MAP_FN(result);\n }\n\n return result;\n};\n\n\n/**\n * Sets the map to check when returning a value from goog.getCssName(). Example:\n * <pre>\n * goog.setCssNameMapping({\n * \"goog\": \"a\",\n * \"disabled\": \"b\",\n * });\n *\n * var x = goog.getCssName('goog');\n * // The following evaluates to: \"a a-b\".\n * goog.getCssName('goog') + ' ' + goog.getCssName(x, 'disabled')\n * </pre>\n * When declared as a map of string literals to string literals, the JSCompiler\n * will replace all calls to goog.getCssName() using the supplied map if the\n * --process_closure_primitives flag is set.\n *\n * @param {!Object} mapping A map of strings to strings where keys are possible\n * arguments to goog.getCssName() and values are the corresponding values\n * that should be returned.\n * @param {string=} opt_style The style of css name mapping. There are two valid\n * options: 'BY_PART', and 'BY_WHOLE'.\n * @see goog.getCssName for a description.\n */\ngoog.setCssNameMapping = function(mapping, opt_style) {\n goog.cssNameMapping_ = mapping;\n goog.cssNameMappingStyle_ = opt_style;\n};\n\n\n/**\n * To use CSS renaming in compiled mode, one of the input files should have a\n * call to goog.setCssNameMapping() with an object literal that the JSCompiler\n * can extract and use to replace all calls to goog.getCssName(). In uncompiled\n * mode, JavaScript code should be loaded before this base.js file that declares\n * a global variable, CLOSURE_CSS_NAME_MAPPING, which is used below. This is\n * to ensure that the mapping is loaded before any calls to goog.getCssName()\n * are made in uncompiled mode.\n *\n * A hook for overriding the CSS name mapping.\n * @type {!Object<string, string>|undefined}\n */\ngoog.global.CLOSURE_CSS_NAME_MAPPING;\n\n\nif (!COMPILED && goog.global.CLOSURE_CSS_NAME_MAPPING) {\n // This does not call goog.setCssNameMapping() because the JSCompiler\n // requires that goog.setCssNameMapping() be called with an object literal.\n goog.cssNameMapping_ = goog.global.CLOSURE_CSS_NAME_MAPPING;\n}\n\n\n/**\n * Gets a localized message.\n *\n * This function is a compiler primitive. If you give the compiler a localized\n * message bundle, it will replace the string at compile-time with a localized\n * version, and expand goog.getMsg call to a concatenated string.\n *\n * Messages must be initialized in the form:\n * <code>\n * var MSG_NAME = goog.getMsg('Hello {$placeholder}', {'placeholder': 'world'});\n * </code>\n *\n * This function produces a string which should be treated as plain text. Use\n * {@link goog.html.SafeHtmlFormatter} in conjunction with goog.getMsg to\n * produce SafeHtml.\n *\n * @param {string} str Translatable string, places holders in the form {$foo}.\n * @param {Object<string, string>=} opt_values Maps place holder name to value.\n * @param {{html: (boolean|undefined),\n * unescapeHtmlEntities: (boolean|undefined)}=} opt_options Options:\n * html: Escape '<' in str to '&lt;'. Used by Closure Templates where the\n * generated code size and performance is critical which is why {@link\n * goog.html.SafeHtmlFormatter} is not used. The value must be literal true\n * or false.\n * unescapeHtmlEntities: Unescape common html entities: &gt;, &lt;, &apos;,\n * &quot; and &amp;. Used for messages not in HTML context, such as with\n * `textContent` property.\n * @return {string} message with placeholders filled.\n */\ngoog.getMsg = function(str, opt_values, opt_options) {\n if (opt_options && opt_options.html) {\n // Note that '&' is not replaced because the translation can contain HTML\n // entities.\n str = str.replace(/</g, '&lt;');\n }\n if (opt_options && opt_options.unescapeHtmlEntities) {\n // Note that \"&amp;\" must be the last to avoid \"creating\" new entities.\n str = str.replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&apos;/g, '\\'')\n .replace(/&quot;/g, '\"')\n .replace(/&amp;/g, '&');\n }\n if (opt_values) {\n str = str.replace(/\\{\\$([^}]+)}/g, function(match, key) {\n return (opt_values != null && key in opt_values) ? opt_values[key] :\n match;\n });\n }\n return str;\n};\n\n\n/**\n * Gets a localized message. If the message does not have a translation, gives a\n * fallback message.\n *\n * This is useful when introducing a new message that has not yet been\n * translated into all languages.\n *\n * This function is a compiler primitive. Must be used in the form:\n * <code>var x = goog.getMsgWithFallback(MSG_A, MSG_B);</code>\n * where MSG_A and MSG_B were initialized with goog.getMsg.\n *\n * @param {string} a The preferred message.\n * @param {string} b The fallback message.\n * @return {string} The best translated message.\n */\ngoog.getMsgWithFallback = function(a, b) {\n return a;\n};\n\n\n/**\n * Exposes an unobfuscated global namespace path for the given object.\n * Note that fields of the exported object *will* be obfuscated, unless they are\n * exported in turn via this function or goog.exportProperty.\n *\n * Also handy for making public items that are defined in anonymous closures.\n *\n * ex. goog.exportSymbol('public.path.Foo', Foo);\n *\n * ex. goog.exportSymbol('public.path.Foo.staticFunction', Foo.staticFunction);\n * public.path.Foo.staticFunction();\n *\n * ex. goog.exportSymbol('public.path.Foo.prototype.myMethod',\n * Foo.prototype.myMethod);\n * new public.path.Foo().myMethod();\n *\n * @param {string} publicPath Unobfuscated name to export.\n * @param {*} object Object the name should point to.\n * @param {?Object=} objectToExportTo The object to add the path to; default\n * is goog.global.\n */\ngoog.exportSymbol = function(publicPath, object, objectToExportTo) {\n goog.exportPath_(\n publicPath, object, /* overwriteImplicit= */ true, objectToExportTo);\n};\n\n\n/**\n * Exports a property unobfuscated into the object's namespace.\n * ex. goog.exportProperty(Foo, 'staticFunction', Foo.staticFunction);\n * ex. goog.exportProperty(Foo.prototype, 'myMethod', Foo.prototype.myMethod);\n * @param {Object} object Object whose static property is being exported.\n * @param {string} publicName Unobfuscated name to export.\n * @param {*} symbol Object the name should point to.\n */\ngoog.exportProperty = function(object, publicName, symbol) {\n object[publicName] = symbol;\n};\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * Usage:\n * <pre>\n * function ParentClass(a, b) { }\n * ParentClass.prototype.foo = function(a) { };\n *\n * function ChildClass(a, b, c) {\n * ChildClass.base(this, 'constructor', a, b);\n * }\n * goog.inherits(ChildClass, ParentClass);\n *\n * var child = new ChildClass('a', 'b', 'see');\n * child.foo(); // This works.\n * </pre>\n *\n * @param {!Function} childCtor Child class.\n * @param {!Function} parentCtor Parent class.\n * @suppress {strictMissingProperties} superClass_ and base is not defined on\n * Function.\n * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.inherits = function(childCtor, parentCtor) {\n /** @constructor */\n function tempCtor() {}\n tempCtor.prototype = parentCtor.prototype;\n childCtor.superClass_ = parentCtor.prototype;\n childCtor.prototype = new tempCtor();\n /** @override */\n childCtor.prototype.constructor = childCtor;\n\n /**\n * Calls superclass constructor/method.\n *\n * This function is only available if you use goog.inherits to\n * express inheritance relationships between classes.\n *\n * NOTE: This is a replacement for goog.base and for superClass_\n * property defined in childCtor.\n *\n * @param {!Object} me Should always be \"this\".\n * @param {string} methodName The method name to call. Calling\n * superclass constructor can be done with the special string\n * 'constructor'.\n * @param {...*} var_args The arguments to pass to superclass\n * method/constructor.\n * @return {*} The return value of the superclass method/constructor.\n */\n childCtor.base = function(me, methodName, var_args) {\n // Copying using loop to avoid deop due to passing arguments object to\n // function. This is faster in many JS engines as of late 2014.\n var args = new Array(arguments.length - 2);\n for (var i = 2; i < arguments.length; i++) {\n args[i - 2] = arguments[i];\n }\n return parentCtor.prototype[methodName].apply(me, args);\n };\n};\n\n\n/**\n * Allow for aliasing within scope functions. This function exists for\n * uncompiled code - in compiled code the calls will be inlined and the aliases\n * applied. In uncompiled code the function is simply run since the aliases as\n * written are valid JavaScript.\n *\n *\n * @param {function()} fn Function to call. This function can contain aliases\n * to namespaces (e.g. \"var dom = goog.dom\") or classes\n * (e.g. \"var Timer = goog.Timer\").\n * @deprecated Use goog.module instead.\n */\ngoog.scope = function(fn) {\n if (goog.isInModuleLoader_()) {\n throw new Error('goog.scope is not supported within a module.');\n }\n fn.call(goog.global);\n};\n\n\n/*\n * To support uncompiled, strict mode bundles that use eval to divide source\n * like so:\n * eval('someSource;//# sourceUrl sourcefile.js');\n * We need to export the globally defined symbols \"goog\" and \"COMPILED\".\n * Exporting \"goog\" breaks the compiler optimizations, so we required that\n * be defined externally.\n * NOTE: We don't use goog.exportSymbol here because we don't want to trigger\n * extern generation when that compiler option is enabled.\n */\nif (!COMPILED) {\n goog.global['COMPILED'] = COMPILED;\n}\n\n\n//==============================================================================\n// goog.defineClass implementation\n//==============================================================================\n\n\n/**\n * Creates a restricted form of a Closure \"class\":\n * - from the compiler's perspective, the instance returned from the\n * constructor is sealed (no new properties may be added). This enables\n * better checks.\n * - the compiler will rewrite this definition to a form that is optimal\n * for type checking and optimization (initially this will be a more\n * traditional form).\n *\n * @param {Function} superClass The superclass, Object or null.\n * @param {goog.defineClass.ClassDescriptor} def\n * An object literal describing\n * the class. It may have the following properties:\n * \"constructor\": the constructor function\n * \"statics\": an object literal containing methods to add to the constructor\n * as \"static\" methods or a function that will receive the constructor\n * function as its only parameter to which static properties can\n * be added.\n * all other properties are added to the prototype.\n * @return {!Function} The class constructor.\n * @deprecated Use ECMAScript class syntax instead.\n */\ngoog.defineClass = function(superClass, def) {\n // TODO(johnlenz): consider making the superClass an optional parameter.\n var constructor = def.constructor;\n var statics = def.statics;\n // Wrap the constructor prior to setting up the prototype and static methods.\n if (!constructor || constructor == Object.prototype.constructor) {\n constructor = function() {\n throw new Error(\n 'cannot instantiate an interface (no constructor defined).');\n };\n }\n\n var cls = goog.defineClass.createSealingConstructor_(constructor, superClass);\n if (superClass) {\n goog.inherits(cls, superClass);\n }\n\n // Remove all the properties that should not be copied to the prototype.\n delete def.constructor;\n delete def.statics;\n\n goog.defineClass.applyProperties_(cls.prototype, def);\n if (statics != null) {\n if (statics instanceof Function) {\n statics(cls);\n } else {\n goog.defineClass.applyProperties_(cls, statics);\n }\n }\n\n return cls;\n};\n\n\n/**\n * @typedef {{\n * constructor: (!Function|undefined),\n * statics: (Object|undefined|function(Function):void)\n * }}\n */\ngoog.defineClass.ClassDescriptor;\n\n\n/**\n * @define {boolean} Whether the instances returned by goog.defineClass should\n * be sealed when possible.\n *\n * When sealing is disabled the constructor function will not be wrapped by\n * goog.defineClass, making it incompatible with ES6 class methods.\n */\ngoog.defineClass.SEAL_CLASS_INSTANCES =\n goog.define('goog.defineClass.SEAL_CLASS_INSTANCES', goog.DEBUG);\n\n\n/**\n * If goog.defineClass.SEAL_CLASS_INSTANCES is enabled and Object.seal is\n * defined, this function will wrap the constructor in a function that seals the\n * results of the provided constructor function.\n *\n * @param {!Function} ctr The constructor whose results maybe be sealed.\n * @param {Function} superClass The superclass constructor.\n * @return {!Function} The replacement constructor.\n * @private\n */\ngoog.defineClass.createSealingConstructor_ = function(ctr, superClass) {\n if (!goog.defineClass.SEAL_CLASS_INSTANCES) {\n // Do now wrap the constructor when sealing is disabled. Angular code\n // depends on this for injection to work properly.\n return ctr;\n }\n\n // NOTE: The sealing behavior has been removed\n\n /**\n * @this {Object}\n * @return {?}\n */\n var wrappedCtr = function() {\n // Don't seal an instance of a subclass when it calls the constructor of\n // its super class as there is most likely still setup to do.\n var instance = ctr.apply(this, arguments) || this;\n instance[goog.UID_PROPERTY_] = instance[goog.UID_PROPERTY_];\n\n return instance;\n };\n\n return wrappedCtr;\n};\n\n\n\n// TODO(johnlenz): share these values with the goog.object\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n * @private\n * @const\n */\ngoog.defineClass.OBJECT_PROTOTYPE_FIELDS_ = [\n 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',\n 'toLocaleString', 'toString', 'valueOf'\n];\n\n\n// TODO(johnlenz): share this function with the goog.object\n/**\n * @param {!Object} target The object to add properties to.\n * @param {!Object} source The object to copy properties from.\n * @private\n */\ngoog.defineClass.applyProperties_ = function(target, source) {\n // TODO(johnlenz): update this to support ES5 getters/setters\n\n var key;\n for (key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n for (var i = 0; i < goog.defineClass.OBJECT_PROTOTYPE_FIELDS_.length; i++) {\n key = goog.defineClass.OBJECT_PROTOTYPE_FIELDS_[i];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n};\n\n/**\n * Returns the parameter.\n * @param {string} s\n * @return {string}\n * @private\n */\ngoog.identity_ = function(s) {\n return s;\n};\n\n\n/**\n * Creates Trusted Types policy if Trusted Types are supported by the browser.\n * The policy just blesses any string as a Trusted Type. It is not visibility\n * restricted because anyone can also call trustedTypes.createPolicy directly.\n * However, the allowed names should be restricted by a HTTP header and the\n * reference to the created policy should be visibility restricted.\n * @param {string} name\n * @return {?TrustedTypePolicy}\n */\ngoog.createTrustedTypesPolicy = function(name) {\n var policy = null;\n var policyFactory = goog.global.trustedTypes;\n if (!policyFactory || !policyFactory.createPolicy) {\n return policy;\n }\n // trustedTypes.createPolicy throws if called with a name that is already\n // registered, even in report-only mode. Until the API changes, catch the\n // error not to break the applications functionally. In such case, the code\n // will fall back to using regular Safe Types.\n // TODO(koto): Remove catching once createPolicy API stops throwing.\n try {\n policy = policyFactory.createPolicy(name, {\n createHTML: goog.identity_,\n createScript: goog.identity_,\n createScriptURL: goog.identity_\n });\n } catch (e) {\n goog.logToConsole_(e.message);\n }\n return policy;\n};\n\n// There's a bug in the compiler where without collapse properties the\n// Closure namespace defines do not guard code correctly. To help reduce code\n// size also check for !COMPILED even though it redundant until this is fixed.\nif (!COMPILED && goog.DEPENDENCIES_ENABLED) {\n\n\n /**\n * Tries to detect whether the current browser is Edge, based on the user\n * agent. This matches only pre-Chromium Edge.\n * @see https://docs.microsoft.com/en-us/microsoft-edge/web-platform/user-agent-string\n * @return {boolean} True if the current browser is Edge.\n * @private\n */\n goog.isEdge_ = function() {\n var userAgent = goog.global.navigator && goog.global.navigator.userAgent ?\n goog.global.navigator.userAgent :\n '';\n var edgeRe = /Edge\\/(\\d+)(\\.\\d)*/i;\n return !!userAgent.match(edgeRe);\n };\n\n\n /**\n * Tries to detect whether is in the context of an HTML document.\n * @return {boolean} True if it looks like HTML document.\n * @private\n */\n goog.inHtmlDocument_ = function() {\n /** @type {!Document} */\n var doc = goog.global.document;\n return doc != null && 'write' in doc; // XULDocument misses write.\n };\n\n\n /**\n * We'd like to check for if the document readyState is 'loading'; however\n * there are bugs on IE 10 and below where the readyState being anything other\n * than 'complete' is not reliable.\n * @return {boolean}\n * @private\n */\n goog.isDocumentLoading_ = function() {\n // attachEvent is available on IE 6 thru 10 only, and thus can be used to\n // detect those browsers.\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n return doc.attachEvent ? doc.readyState != 'complete' :\n doc.readyState == 'loading';\n };\n\n\n /**\n * Tries to detect the base path of base.js script that bootstraps Closure.\n * @private\n */\n goog.findBasePath_ = function() {\n if (goog.global.CLOSURE_BASE_PATH != undefined &&\n // Anti DOM-clobbering runtime check (b/37736576).\n typeof goog.global.CLOSURE_BASE_PATH === 'string') {\n goog.basePath = goog.global.CLOSURE_BASE_PATH;\n return;\n } else if (!goog.inHtmlDocument_()) {\n return;\n }\n /** @type {!Document} */\n var doc = goog.global.document;\n // If we have a currentScript available, use it exclusively.\n var currentScript = doc.currentScript;\n if (currentScript) {\n var scripts = [currentScript];\n } else {\n var scripts = doc.getElementsByTagName('SCRIPT');\n }\n // Search backwards since the current script is in almost all cases the one\n // that has base.js.\n for (var i = scripts.length - 1; i >= 0; --i) {\n var script = /** @type {!HTMLScriptElement} */ (scripts[i]);\n var src = script.src;\n var qmark = src.lastIndexOf('?');\n var l = qmark == -1 ? src.length : qmark;\n if (src.substr(l - 7, 7) == 'base.js') {\n goog.basePath = src.substr(0, l - 7);\n return;\n }\n }\n };\n\n goog.findBasePath_();\n\n /** @struct @constructor @final */\n goog.Transpiler = function() {\n /** @private {?Object<string, boolean>} */\n this.requiresTranspilation_ = null;\n /** @private {string} */\n this.transpilationTarget_ = goog.TRANSPILE_TO_LANGUAGE;\n };\n /**\n * Returns a newly created map from language mode string to a boolean\n * indicating whether transpilation should be done for that mode as well as\n * the highest level language that this environment supports.\n *\n * Guaranteed invariant:\n * For any two modes, l1 and l2 where l2 is a newer mode than l1,\n * `map[l1] == true` implies that `map[l2] == true`.\n *\n * Note this method is extracted and used elsewhere, so it cannot rely on\n * anything external (it should easily be able to be transformed into a\n * standalone, top level function).\n *\n * @private\n * @return {{\n * target: string,\n * map: !Object<string, boolean>\n * }}\n */\n goog.Transpiler.prototype.createRequiresTranspilation_ = function() {\n var transpilationTarget = 'es3';\n var /** !Object<string, boolean> */ requiresTranspilation = {'es3': false};\n var transpilationRequiredForAllLaterModes = false;\n\n /**\n * Adds an entry to requiresTranspliation for the given language mode.\n *\n * IMPORTANT: Calls must be made in order from oldest to newest language\n * mode.\n * @param {string} modeName\n * @param {function(): boolean} isSupported Returns true if the JS engine\n * supports the given mode.\n */\n function addNewerLanguageTranspilationCheck(modeName, isSupported) {\n if (transpilationRequiredForAllLaterModes) {\n requiresTranspilation[modeName] = true;\n } else if (isSupported()) {\n transpilationTarget = modeName;\n requiresTranspilation[modeName] = false;\n } else {\n requiresTranspilation[modeName] = true;\n transpilationRequiredForAllLaterModes = true;\n }\n }\n\n /**\n * Does the given code evaluate without syntax errors and return a truthy\n * result?\n */\n function /** boolean */ evalCheck(/** string */ code) {\n try {\n return !!eval(goog.CLOSURE_EVAL_PREFILTER_.createScript(code));\n } catch (ignored) {\n return false;\n }\n }\n\n // Identify ES3-only browsers by their incorrect treatment of commas.\n addNewerLanguageTranspilationCheck('es5', function() {\n return evalCheck('[1,].length==1');\n });\n addNewerLanguageTranspilationCheck('es6', function() {\n // Edge has a non-deterministic (i.e., not reproducible) bug with ES6:\n // https://github.com/Microsoft/ChakraCore/issues/1496.\n if (goog.isEdge_()) {\n // The Reflect.construct test below is flaky on Edge. It can sometimes\n // pass or fail on 40 15.15063, so just exit early for Edge and treat\n // it as ES5. Until we're on a more up to date version just always use\n // ES5. See https://github.com/Microsoft/ChakraCore/issues/3217.\n return false;\n }\n // Test es6: [FF50 (?), Edge 14 (?), Chrome 50]\n // (a) default params (specifically shadowing locals),\n // (b) destructuring, (c) block-scoped functions,\n // (d) for-of (const), (e) new.target/Reflect.construct\n var es6fullTest =\n 'class X{constructor(){if(new.target!=String)throw 1;this.x=42}}' +\n 'let q=Reflect.construct(X,[],String);if(q.x!=42||!(q instanceof ' +\n 'String))throw 1;for(const a of[2,3]){if(a==2)continue;function ' +\n 'f(z={a}){let a=0;return z.a}{function f(){return 0;}}return f()' +\n '==3}';\n\n return evalCheck('(()=>{\"use strict\";' + es6fullTest + '})()');\n });\n // ** and **= are the only new features in 'es7'\n addNewerLanguageTranspilationCheck('es7', function() {\n return evalCheck('2**3==8');\n });\n // async functions are the only new features in 'es8'\n addNewerLanguageTranspilationCheck('es8', function() {\n return evalCheck('async()=>1,1');\n });\n addNewerLanguageTranspilationCheck('es9', function() {\n return evalCheck('({...rest}={}),1');\n });\n // optional catch binding, unescaped unicode paragraph separator in strings\n addNewerLanguageTranspilationCheck('es_2019', function() {\n return evalCheck('let r;try{r=\"\\u2029\"}catch{};r');\n });\n // optional chaining, nullish coalescing\n // untested/unsupported: bigint, import meta\n addNewerLanguageTranspilationCheck('es_2020', function() {\n return evalCheck('null?.x??1');\n });\n addNewerLanguageTranspilationCheck('es_next', function() {\n return false; // assume it always need to transpile\n });\n return {target: transpilationTarget, map: requiresTranspilation};\n };\n\n\n /**\n * Determines whether the given language needs to be transpiled.\n * @param {string} lang\n * @param {string|undefined} module\n * @return {boolean}\n */\n goog.Transpiler.prototype.needsTranspile = function(lang, module) {\n if (goog.TRANSPILE == 'always') {\n return true;\n } else if (goog.TRANSPILE == 'never') {\n return false;\n } else if (!this.requiresTranspilation_) {\n var obj = this.createRequiresTranspilation_();\n this.requiresTranspilation_ = obj.map;\n this.transpilationTarget_ = this.transpilationTarget_ || obj.target;\n }\n if (lang in this.requiresTranspilation_) {\n if (this.requiresTranspilation_[lang]) {\n return true;\n } else if (\n goog.inHtmlDocument_() && module == 'es6' &&\n !('noModule' in goog.global.document.createElement('script'))) {\n return true;\n } else {\n return false;\n }\n } else {\n throw new Error('Unknown language mode: ' + lang);\n }\n };\n\n\n /**\n * Lazily retrieves the transpiler and applies it to the source.\n * @param {string} code JS code.\n * @param {string} path Path to the code.\n * @return {string} The transpiled code.\n */\n goog.Transpiler.prototype.transpile = function(code, path) {\n // TODO(johnplaisted): We should delete goog.transpile_ and just have this\n // function. But there's some compile error atm where goog.global is being\n // stripped incorrectly without this.\n return goog.transpile_(code, path, this.transpilationTarget_);\n };\n\n\n /** @private @final {!goog.Transpiler} */\n goog.transpiler_ = new goog.Transpiler();\n\n /**\n * Rewrites closing script tags in input to avoid ending an enclosing script\n * tag.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n goog.protectScriptTag_ = function(str) {\n return str.replace(/<\\/(SCRIPT)/ig, '\\\\x3c/$1');\n };\n\n\n /**\n * A debug loader is responsible for downloading and executing javascript\n * files in an unbundled, uncompiled environment.\n *\n * This can be custimized via the setDependencyFactory method, or by\n * CLOSURE_IMPORT_SCRIPT/CLOSURE_LOAD_FILE_SYNC.\n *\n * @struct @constructor @final @private\n */\n goog.DebugLoader_ = function() {\n /** @private @const {!Object<string, !goog.Dependency>} */\n this.dependencies_ = {};\n /** @private @const {!Object<string, string>} */\n this.idToPath_ = {};\n /** @private @const {!Object<string, boolean>} */\n this.written_ = {};\n /** @private @const {!Array<!goog.Dependency>} */\n this.loadingDeps_ = [];\n /** @private {!Array<!goog.Dependency>} */\n this.depsToLoad_ = [];\n /** @private {boolean} */\n this.paused_ = false;\n /** @private {!goog.DependencyFactory} */\n this.factory_ = new goog.DependencyFactory(goog.transpiler_);\n /** @private @const {!Object<string, !Function>} */\n this.deferredCallbacks_ = {};\n /** @private @const {!Array<string>} */\n this.deferredQueue_ = [];\n };\n\n /**\n * @param {!Array<string>} namespaces\n * @param {function(): undefined} callback Function to call once all the\n * namespaces have loaded.\n */\n goog.DebugLoader_.prototype.bootstrap = function(namespaces, callback) {\n var cb = callback;\n function resolve() {\n if (cb) {\n goog.global.setTimeout(cb, 0);\n cb = null;\n }\n }\n\n if (!namespaces.length) {\n resolve();\n return;\n }\n\n var deps = [];\n for (var i = 0; i < namespaces.length; i++) {\n var path = this.getPathFromDeps_(namespaces[i]);\n if (!path) {\n throw new Error('Unregonized namespace: ' + namespaces[i]);\n }\n deps.push(this.dependencies_[path]);\n }\n\n var require = goog.require;\n var loaded = 0;\n for (var i = 0; i < namespaces.length; i++) {\n require(namespaces[i]);\n deps[i].onLoad(function() {\n if (++loaded == namespaces.length) {\n resolve();\n }\n });\n }\n };\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.DebugLoader_.prototype.loadClosureDeps = function() {\n // Circumvent addDependency, which would try to transpile deps.js if\n // transpile is set to always.\n var relPath = 'deps.js';\n this.depsToLoad_.push(this.factory_.createDependency(\n goog.normalizePath_(goog.basePath + relPath), relPath, [], [], {},\n false));\n this.loadDeps_();\n };\n\n\n /**\n * Notifies the debug loader when a dependency has been requested.\n *\n * @param {string} absPathOrId Path of the dependency or goog id.\n * @param {boolean=} opt_force\n */\n goog.DebugLoader_.prototype.requested = function(absPathOrId, opt_force) {\n var path = this.getPathFromDeps_(absPathOrId);\n if (path &&\n (opt_force || this.areDepsLoaded_(this.dependencies_[path].requires))) {\n var callback = this.deferredCallbacks_[path];\n if (callback) {\n delete this.deferredCallbacks_[path];\n callback();\n }\n }\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.DebugLoader_.prototype.setDependencyFactory = function(factory) {\n this.factory_ = factory;\n };\n\n\n /**\n * Travserses the dependency graph and queues the given dependency, and all of\n * its transitive dependencies, for loading and then starts loading if not\n * paused.\n *\n * @param {string} namespace\n * @private\n */\n goog.DebugLoader_.prototype.load_ = function(namespace) {\n if (!this.getPathFromDeps_(namespace)) {\n var errorMessage = 'goog.require could not find: ' + namespace;\n goog.logToConsole_(errorMessage);\n } else {\n var loader = this;\n\n var deps = [];\n\n /** @param {string} namespace */\n var visit = function(namespace) {\n var path = loader.getPathFromDeps_(namespace);\n\n if (!path) {\n throw new Error('Bad dependency path or symbol: ' + namespace);\n }\n\n if (loader.written_[path]) {\n return;\n }\n\n loader.written_[path] = true;\n\n var dep = loader.dependencies_[path];\n for (var i = 0; i < dep.requires.length; i++) {\n if (!goog.isProvided_(dep.requires[i])) {\n visit(dep.requires[i]);\n }\n }\n\n deps.push(dep);\n };\n\n visit(namespace);\n\n var wasLoading = !!this.depsToLoad_.length;\n this.depsToLoad_ = this.depsToLoad_.concat(deps);\n\n if (!this.paused_ && !wasLoading) {\n this.loadDeps_();\n }\n }\n };\n\n\n /**\n * Loads any queued dependencies until they are all loaded or paused.\n *\n * @private\n */\n goog.DebugLoader_.prototype.loadDeps_ = function() {\n var loader = this;\n var paused = this.paused_;\n\n while (this.depsToLoad_.length && !paused) {\n (function() {\n var loadCallDone = false;\n var dep = loader.depsToLoad_.shift();\n\n var loaded = false;\n loader.loading_(dep);\n\n var controller = {\n pause: function() {\n if (loadCallDone) {\n throw new Error('Cannot call pause after the call to load.');\n } else {\n paused = true;\n }\n },\n resume: function() {\n if (loadCallDone) {\n loader.resume_();\n } else {\n // Some dep called pause and then resume in the same load call.\n // Just keep running this same loop.\n paused = false;\n }\n },\n loaded: function() {\n if (loaded) {\n throw new Error('Double call to loaded.');\n }\n\n loaded = true;\n loader.loaded_(dep);\n },\n pending: function() {\n // Defensive copy.\n var pending = [];\n for (var i = 0; i < loader.loadingDeps_.length; i++) {\n pending.push(loader.loadingDeps_[i]);\n }\n return pending;\n },\n /**\n * @param {goog.ModuleType} type\n */\n setModuleState: function(type) {\n goog.moduleLoaderState_ = {\n type: type,\n moduleName: '',\n declareLegacyNamespace: false\n };\n },\n /** @type {function(string, string, string=)} */\n registerEs6ModuleExports: function(\n path, exports, opt_closureNamespace) {\n if (opt_closureNamespace) {\n goog.loadedModules_[opt_closureNamespace] = {\n exports: exports,\n type: goog.ModuleType.ES6,\n moduleId: opt_closureNamespace || ''\n };\n }\n },\n /** @type {function(string, ?)} */\n registerGoogModuleExports: function(moduleId, exports) {\n goog.loadedModules_[moduleId] = {\n exports: exports,\n type: goog.ModuleType.GOOG,\n moduleId: moduleId\n };\n },\n clearModuleState: function() {\n goog.moduleLoaderState_ = null;\n },\n defer: function(callback) {\n if (loadCallDone) {\n throw new Error(\n 'Cannot register with defer after the call to load.');\n }\n loader.defer_(dep, callback);\n },\n areDepsLoaded: function() {\n return loader.areDepsLoaded_(dep.requires);\n }\n };\n\n try {\n dep.load(controller);\n } finally {\n loadCallDone = true;\n }\n })();\n }\n\n if (paused) {\n this.pause_();\n }\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.pause_ = function() {\n this.paused_ = true;\n };\n\n\n /** @private */\n goog.DebugLoader_.prototype.resume_ = function() {\n if (this.paused_) {\n this.paused_ = false;\n this.loadDeps_();\n }\n };\n\n\n /**\n * Marks the given dependency as loading (load has been called but it has not\n * yet marked itself as finished). Useful for dependencies that want to know\n * what else is loading. Example: goog.modules cannot eval if there are\n * loading dependencies.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loading_ = function(dep) {\n this.loadingDeps_.push(dep);\n };\n\n\n /**\n * Marks the given dependency as having finished loading and being available\n * for require.\n *\n * @param {!goog.Dependency} dep\n * @private\n */\n goog.DebugLoader_.prototype.loaded_ = function(dep) {\n for (var i = 0; i < this.loadingDeps_.length; i++) {\n if (this.loadingDeps_[i] == dep) {\n this.loadingDeps_.splice(i, 1);\n break;\n }\n }\n\n for (var i = 0; i < this.deferredQueue_.length; i++) {\n if (this.deferredQueue_[i] == dep.path) {\n this.deferredQueue_.splice(i, 1);\n break;\n }\n }\n\n if (this.loadingDeps_.length == this.deferredQueue_.length &&\n !this.depsToLoad_.length) {\n // Something has asked to load these, but they may not be directly\n // required again later, so load them now that we know we're done loading\n // everything else. e.g. a goog module entry point.\n while (this.deferredQueue_.length) {\n this.requested(this.deferredQueue_.shift(), true);\n }\n }\n\n dep.loaded();\n };\n\n\n /**\n * @param {!Array<string>} pathsOrIds\n * @return {boolean}\n * @private\n */\n goog.DebugLoader_.prototype.areDepsLoaded_ = function(pathsOrIds) {\n for (var i = 0; i < pathsOrIds.length; i++) {\n var path = this.getPathFromDeps_(pathsOrIds[i]);\n if (!path ||\n (!(path in this.deferredCallbacks_) &&\n !goog.isProvided_(pathsOrIds[i]))) {\n return false;\n }\n }\n\n return true;\n };\n\n\n /**\n * @param {string} absPathOrId\n * @return {?string}\n * @private\n */\n goog.DebugLoader_.prototype.getPathFromDeps_ = function(absPathOrId) {\n if (absPathOrId in this.idToPath_) {\n return this.idToPath_[absPathOrId];\n } else if (absPathOrId in this.dependencies_) {\n return absPathOrId;\n } else {\n return null;\n }\n };\n\n\n /**\n * @param {!goog.Dependency} dependency\n * @param {!Function} callback\n * @private\n */\n goog.DebugLoader_.prototype.defer_ = function(dependency, callback) {\n this.deferredCallbacks_[dependency.path] = callback;\n this.deferredQueue_.push(dependency.path);\n };\n\n\n /**\n * Interface for goog.Dependency implementations to have some control over\n * loading of dependencies.\n *\n * @record\n */\n goog.LoadController = function() {};\n\n\n /**\n * Tells the controller to halt loading of more dependencies.\n */\n goog.LoadController.prototype.pause = function() {};\n\n\n /**\n * Tells the controller to resume loading of more dependencies if paused.\n */\n goog.LoadController.prototype.resume = function() {};\n\n\n /**\n * Tells the controller that this dependency has finished loading.\n *\n * This causes this to be removed from pending() and any load callbacks to\n * fire.\n */\n goog.LoadController.prototype.loaded = function() {};\n\n\n /**\n * List of dependencies on which load has been called but which have not\n * called loaded on their controller. This includes the current dependency.\n *\n * @return {!Array<!goog.Dependency>}\n */\n goog.LoadController.prototype.pending = function() {};\n\n\n /**\n * Registers an object as an ES6 module's exports so that goog.modules may\n * require it by path.\n *\n * @param {string} path Full path of the module.\n * @param {?} exports\n * @param {string=} opt_closureNamespace Closure namespace to associate with\n * this module.\n */\n goog.LoadController.prototype.registerEs6ModuleExports = function(\n path, exports, opt_closureNamespace) {};\n\n\n /**\n * Sets the current module state.\n *\n * @param {goog.ModuleType} type Type of module.\n */\n goog.LoadController.prototype.setModuleState = function(type) {};\n\n\n /**\n * Clears the current module state.\n */\n goog.LoadController.prototype.clearModuleState = function() {};\n\n\n /**\n * Registers a callback to call once the dependency is actually requested\n * via goog.require + all of the immediate dependencies have been loaded or\n * all other files have been loaded. Allows for lazy loading until\n * require'd without pausing dependency loading, which is needed on old IE.\n *\n * @param {!Function} callback\n */\n goog.LoadController.prototype.defer = function(callback) {};\n\n\n /**\n * @return {boolean}\n */\n goog.LoadController.prototype.areDepsLoaded = function() {};\n\n\n /**\n * Basic super class for all dependencies Closure Library can load.\n *\n * This default implementation is designed to load untranspiled, non-module\n * scripts in a web broswer.\n *\n * For transpiled non-goog.module files {@see goog.TranspiledDependency}.\n * For goog.modules see {@see goog.GoogModuleDependency}.\n * For untranspiled ES6 modules {@see goog.Es6ModuleDependency}.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n */\n goog.Dependency = function(\n path, relativePath, provides, requires, loadFlags) {\n /** @const */\n this.path = path;\n /** @const */\n this.relativePath = relativePath;\n /** @const */\n this.provides = provides;\n /** @const */\n this.requires = requires;\n /** @const */\n this.loadFlags = loadFlags;\n /** @private {boolean} */\n this.loaded_ = false;\n /** @private {!Array<function()>} */\n this.loadCallbacks_ = [];\n };\n\n\n /**\n * @return {string} The pathname part of this dependency's path if it is a\n * URI.\n */\n goog.Dependency.prototype.getPathName = function() {\n var pathName = this.path;\n var protocolIndex = pathName.indexOf('://');\n if (protocolIndex >= 0) {\n pathName = pathName.substring(protocolIndex + 3);\n var slashIndex = pathName.indexOf('/');\n if (slashIndex >= 0) {\n pathName = pathName.substring(slashIndex + 1);\n }\n }\n return pathName;\n };\n\n\n /**\n * @param {function()} callback Callback to fire as soon as this has loaded.\n * @final\n */\n goog.Dependency.prototype.onLoad = function(callback) {\n if (this.loaded_) {\n callback();\n } else {\n this.loadCallbacks_.push(callback);\n }\n };\n\n\n /**\n * Marks this dependency as loaded and fires any callbacks registered with\n * onLoad.\n * @final\n */\n goog.Dependency.prototype.loaded = function() {\n this.loaded_ = true;\n var callbacks = this.loadCallbacks_;\n this.loadCallbacks_ = [];\n for (var i = 0; i < callbacks.length; i++) {\n callbacks[i]();\n }\n };\n\n\n /**\n * Whether or not document.written / appended script tags should be deferred.\n *\n * @private {boolean}\n */\n goog.Dependency.defer_ = false;\n\n\n /**\n * Map of script ready / state change callbacks. Old IE cannot handle putting\n * these properties on goog.global.\n *\n * @private @const {!Object<string, function(?):undefined>}\n */\n goog.Dependency.callbackMap_ = {};\n\n\n /**\n * @param {function(...?):?} callback\n * @return {string}\n * @private\n */\n goog.Dependency.registerCallback_ = function(callback) {\n var key = Math.random().toString(32);\n goog.Dependency.callbackMap_[key] = callback;\n return key;\n };\n\n\n /**\n * @param {string} key\n * @private\n */\n goog.Dependency.unregisterCallback_ = function(key) {\n delete goog.Dependency.callbackMap_[key];\n };\n\n\n /**\n * @param {string} key\n * @param {...?} var_args\n * @private\n * @suppress {unusedPrivateMembers}\n */\n goog.Dependency.callback_ = function(key, var_args) {\n if (key in goog.Dependency.callbackMap_) {\n var callback = goog.Dependency.callbackMap_[key];\n var args = [];\n for (var i = 1; i < arguments.length; i++) {\n args.push(arguments[i]);\n }\n callback.apply(undefined, args);\n } else {\n var errorMessage = 'Callback key ' + key +\n ' does not exist (was base.js loaded more than once?).';\n throw Error(errorMessage);\n }\n };\n\n\n /**\n * Starts loading this dependency. This dependency can pause loading if it\n * needs to and resume it later via the controller interface.\n *\n * When this is loaded it should call controller.loaded(). Note that this will\n * end up calling the loaded method of this dependency; there is no need to\n * call it explicitly.\n *\n * @param {!goog.LoadController} controller\n */\n goog.Dependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n if (this.relativePath == 'deps.js') {\n // Some old code is relying on base.js auto loading deps.js failing with\n // no error before later setting CLOSURE_IMPORT_SCRIPT.\n // CLOSURE_IMPORT_SCRIPT should be set *before* base.js is loaded, or\n // CLOSURE_NO_DEPS set to true.\n goog.logToConsole_(\n 'Consider setting CLOSURE_IMPORT_SCRIPT before loading base.js, ' +\n 'or setting CLOSURE_NO_DEPS to true.');\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n // If the user tries to require a new symbol after document load,\n // something has gone terribly wrong. Doing a document.write would\n // wipe out the page. This does not apply to the CSP-compliant method\n // of writing script tags.\n if (doc.readyState == 'complete' &&\n !goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING) {\n // Certain test frameworks load base.js multiple times, which tries\n // to write deps.js each time. If that happens, just fail silently.\n // These frameworks wipe the page between each load of base.js, so this\n // is OK.\n var isDeps = /\\bdeps.js$/.test(this.path);\n if (isDeps) {\n controller.loaded();\n return;\n } else {\n throw Error('Cannot write \"' + this.path + '\" after document load');\n }\n }\n\n var nonce = goog.getScriptNonce_();\n if (!goog.ENABLE_CHROME_APP_SAFE_SCRIPT_LOADING &&\n goog.isDocumentLoading_()) {\n var key;\n var callback = function(script) {\n if (script.readyState && script.readyState != 'complete') {\n script.onload = callback;\n return;\n }\n goog.Dependency.unregisterCallback_(key);\n controller.loaded();\n };\n key = goog.Dependency.registerCallback_(callback);\n\n var defer = goog.Dependency.defer_ ? ' defer' : '';\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script src=\"' + this.path + '\"' + nonceAttr + defer +\n ' id=\"script-' + key + '\"><\\/script>';\n\n script += '<script' + nonceAttr + '>';\n\n if (goog.Dependency.defer_) {\n script += 'document.getElementById(\\'script-' + key +\n '\\').onload = function() {\\n' +\n ' goog.Dependency.callback_(\\'' + key + '\\', this);\\n' +\n '};\\n';\n } else {\n script += 'goog.Dependency.callback_(\\'' + key +\n '\\', document.getElementById(\\'script-' + key + '\\'));';\n }\n\n script += '<\\/script>';\n\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = goog.Dependency.defer_;\n scriptEl.async = false;\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n scriptEl.onload = function() {\n scriptEl.onload = null;\n controller.loaded();\n };\n\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(this.path) :\n this.path;\n doc.head.appendChild(scriptEl);\n }\n };\n\n\n /**\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides Should be an empty array.\n * TODO(johnplaisted) add support for adding closure namespaces to ES6\n * modules for interop purposes.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.Dependency}\n */\n goog.Es6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.Es6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(goog.Es6ModuleDependency, goog.Dependency);\n\n\n /**\n * @override\n * @param {!goog.LoadController} controller\n */\n goog.Es6ModuleDependency.prototype.load = function(controller) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n if (goog.global.CLOSURE_IMPORT_SCRIPT(this.path)) {\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n if (!goog.inHtmlDocument_()) {\n goog.logToConsole_(\n 'Cannot use default debug loader outside of HTML documents.');\n controller.pause();\n return;\n }\n\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var dep = this;\n\n // TODO(johnplaisted): Does document.writing really speed up anything? Any\n // difference between this and just waiting for interactive mode and then\n // appending?\n function write(src, contents) {\n var nonceAttr = '';\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n nonceAttr = ' nonce=\"' + nonce + '\"';\n }\n\n if (contents) {\n var script = '<script type=\"module\" crossorigin' + nonceAttr + '>' +\n contents + '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n } else {\n var script = '<script type=\"module\" crossorigin src=\"' + src + '\"' +\n nonceAttr + '></' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n }\n\n function append(src, contents) {\n var scriptEl =\n /** @type {!HTMLScriptElement} */ (doc.createElement('script'));\n scriptEl.defer = true;\n scriptEl.async = false;\n scriptEl.type = 'module';\n scriptEl.setAttribute('crossorigin', true);\n\n // If CSP nonces are used, propagate them to dynamically created scripts.\n // This is necessary to allow nonce-based CSPs without 'strict-dynamic'.\n var nonce = goog.getScriptNonce_();\n if (nonce) {\n scriptEl.nonce = nonce;\n }\n\n if (contents) {\n scriptEl.text = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScript(contents) :\n contents;\n } else {\n scriptEl.src = goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createScriptURL(src) :\n src;\n }\n\n doc.head.appendChild(scriptEl);\n }\n\n var create;\n\n if (goog.isDocumentLoading_()) {\n create = write;\n // We can ONLY call document.write if we are guaranteed that any\n // non-module script tags document.written after this are deferred.\n // Small optimization, in theory document.writing is faster.\n goog.Dependency.defer_ = true;\n } else {\n create = append;\n }\n\n // Write 4 separate tags here:\n // 1) Sets the module state at the correct time (just before execution).\n // 2) A src node for this, which just hopefully lets the browser load it a\n // little early (no need to parse #3).\n // 3) Import the module and register it.\n // 4) Clear the module state at the correct time. Guaranteed to run even\n // if there is an error in the module (#3 will not run if there is an\n // error in the module).\n var beforeKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(beforeKey);\n controller.setModuleState(goog.ModuleType.ES6);\n });\n create(undefined, 'goog.Dependency.callback_(\"' + beforeKey + '\")');\n\n // TODO(johnplaisted): Does this really speed up anything?\n create(this.path, undefined);\n\n var registerKey = goog.Dependency.registerCallback_(function(exports) {\n goog.Dependency.unregisterCallback_(registerKey);\n controller.registerEs6ModuleExports(\n dep.path, exports, goog.moduleLoaderState_.moduleName);\n });\n create(\n undefined,\n 'import * as m from \"' + this.path + '\"; goog.Dependency.callback_(\"' +\n registerKey + '\", m)');\n\n var afterKey = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(afterKey);\n controller.clearModuleState();\n controller.loaded();\n });\n create(undefined, 'goog.Dependency.callback_(\"' + afterKey + '\")');\n };\n\n\n /**\n * Superclass of any dependency that needs to be loaded into memory,\n * transformed, and then eval'd (goog.modules and transpiled files).\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor @abstract\n * @extends {goog.Dependency}\n */\n goog.TransformedDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.TransformedDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @private {?string} */\n this.contents_ = null;\n\n /**\n * Whether to lazily make the synchronous XHR (when goog.require'd) or make\n * the synchronous XHR when initially loading. On FireFox 61 there is a bug\n * where an ES6 module cannot make a synchronous XHR (rather, it can, but if\n * it does then no other ES6 modules will load after).\n *\n * tl;dr we lazy load due to bugs on older browsers and eager load due to\n * bugs on newer ones.\n *\n * https://bugzilla.mozilla.org/show_bug.cgi?id=1477090\n *\n * @private @const {boolean}\n */\n this.lazyFetch_ = !goog.inHtmlDocument_() ||\n !('noModule' in goog.global.document.createElement('script'));\n };\n goog.inherits(goog.TransformedDependency, goog.Dependency);\n\n\n /**\n * @override\n * @param {!goog.LoadController} controller\n */\n goog.TransformedDependency.prototype.load = function(controller) {\n var dep = this;\n\n function fetch() {\n dep.contents_ = goog.loadFileSync_(dep.path);\n\n if (dep.contents_) {\n dep.contents_ = dep.transform(dep.contents_);\n if (dep.contents_) {\n dep.contents_ += '\\n//# sourceURL=' + dep.path;\n }\n }\n }\n\n if (goog.global.CLOSURE_IMPORT_SCRIPT) {\n fetch();\n if (this.contents_ &&\n goog.global.CLOSURE_IMPORT_SCRIPT('', this.contents_)) {\n this.contents_ = null;\n controller.loaded();\n } else {\n controller.pause();\n }\n return;\n }\n\n\n var isEs6 = this.loadFlags['module'] == goog.ModuleType.ES6;\n\n if (!this.lazyFetch_) {\n fetch();\n }\n\n function load() {\n if (dep.lazyFetch_) {\n fetch();\n }\n\n if (!dep.contents_) {\n // loadFileSync_ or transform are responsible. Assume they logged an\n // error.\n return;\n }\n\n if (isEs6) {\n controller.setModuleState(goog.ModuleType.ES6);\n }\n\n var namespace;\n\n try {\n var contents = dep.contents_;\n dep.contents_ = null;\n goog.globalEval(goog.CLOSURE_EVAL_PREFILTER_.createScript(contents));\n if (isEs6) {\n namespace = goog.moduleLoaderState_.moduleName;\n }\n } finally {\n if (isEs6) {\n controller.clearModuleState();\n }\n }\n\n if (isEs6) {\n // Due to circular dependencies this may not be available for require\n // right now.\n goog.global['$jscomp']['require']['ensure'](\n [dep.getPathName()], function() {\n controller.registerEs6ModuleExports(\n dep.path,\n goog.global['$jscomp']['require'](dep.getPathName()),\n namespace);\n });\n }\n\n controller.loaded();\n }\n\n // Do not fetch now; in FireFox 47 the synchronous XHR doesn't block all\n // events. If we fetched now and then document.write'd the contents the\n // document.write would be an eval and would execute too soon! Instead write\n // a script tag to fetch and eval synchronously at the correct time.\n function fetchInOwnScriptThenLoad() {\n /** @type {!HTMLDocument} */\n var doc = goog.global.document;\n\n var key = goog.Dependency.registerCallback_(function() {\n goog.Dependency.unregisterCallback_(key);\n load();\n });\n\n var nonce = goog.getScriptNonce_();\n var nonceAttr = nonce ? ' nonce=\"' + nonce + '\"' : '';\n var script = '<script' + nonceAttr + '>' +\n goog.protectScriptTag_('goog.Dependency.callback_(\"' + key + '\");') +\n '</' +\n 'script>';\n doc.write(\n goog.TRUSTED_TYPES_POLICY_ ?\n goog.TRUSTED_TYPES_POLICY_.createHTML(script) :\n script);\n }\n\n // If one thing is pending it is this.\n var anythingElsePending = controller.pending().length > 1;\n\n // Additionally if we are meant to defer scripts but the page is still\n // loading (e.g. an ES6 module is loading) then also defer. Or if we are\n // meant to defer and anything else is pending then defer (those may be\n // scripts that did not need transformation and are just script tags with\n // defer set to true, and we need to evaluate after that deferred script).\n var needsAsyncLoading = goog.Dependency.defer_ &&\n (anythingElsePending || goog.isDocumentLoading_());\n\n if (needsAsyncLoading) {\n // Note that we only defer when we have to rather than 100% of the time.\n // Always defering would work, but then in theory the order of\n // goog.require calls would then matter. We want to enforce that most of\n // the time the order of the require calls does not matter.\n controller.defer(function() {\n load();\n });\n return;\n }\n // TODO(johnplaisted): Externs are missing onreadystatechange for\n // HTMLDocument.\n /** @type {?} */\n var doc = goog.global.document;\n\n var isInternetExplorerOrEdge = goog.inHtmlDocument_() &&\n ('ActiveXObject' in goog.global || goog.isEdge_());\n\n // Don't delay in any version of IE or pre-Chromium Edge. There's a bug\n // around this that will cause out of order script execution. This means\n // that on older IE ES6 modules will load too early (while the document is\n // still loading + the dom is not available). The other option is to load\n // too late (when the document is complete and the onload even will never\n // fire). This seems to be the lesser of two evils as scripts already act\n // like the former.\n if (isEs6 && goog.inHtmlDocument_() && goog.isDocumentLoading_() &&\n !isInternetExplorerOrEdge) {\n goog.Dependency.defer_ = true;\n // Transpiled ES6 modules still need to load like regular ES6 modules,\n // aka only after the document is interactive.\n controller.pause();\n var oldCallback = doc.onreadystatechange;\n doc.onreadystatechange = function() {\n if (doc.readyState == 'interactive') {\n doc.onreadystatechange = oldCallback;\n load();\n controller.resume();\n }\n if (typeof oldCallback === 'function') {\n oldCallback.apply(undefined, arguments);\n }\n };\n } else {\n // Always eval on old IE.\n if (!goog.inHtmlDocument_() || !goog.isDocumentLoading_()) {\n load();\n } else {\n fetchInOwnScriptThenLoad();\n }\n }\n };\n\n\n /**\n * @param {string} contents\n * @return {string}\n * @abstract\n */\n goog.TransformedDependency.prototype.transform = function(contents) {};\n\n\n /**\n * Any non-goog.module dependency which needs to be transpiled before eval.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.TranspiledDependency = function(\n path, relativePath, provides, requires, loadFlags, transpiler) {\n goog.TranspiledDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @protected @const*/\n this.transpiler = transpiler;\n };\n goog.inherits(goog.TranspiledDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.TranspiledDependency.prototype.transform = function(contents) {\n // Transpile with the pathname so that ES6 modules are domain agnostic.\n return this.transpiler.transpile(contents, this.getPathName());\n };\n\n\n /**\n * An ES6 module dependency that was transpiled to a jscomp module outside\n * of the debug loader, e.g. server side.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.PreTranspiledEs6ModuleDependency = function(\n path, relativePath, provides, requires, loadFlags) {\n goog.PreTranspiledEs6ModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n };\n goog.inherits(\n goog.PreTranspiledEs6ModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.PreTranspiledEs6ModuleDependency.prototype.transform = function(\n contents) {\n return contents;\n };\n\n\n /**\n * A goog.module, transpiled or not. Will always perform some minimal\n * transformation even when not transpiled to wrap in a goog.loadModule\n * statement.\n *\n * @param {string} path Absolute path of this script.\n * @param {string} relativePath Path of this script relative to goog.basePath.\n * @param {!Array<string>} provides goog.provided or goog.module symbols\n * in this file.\n * @param {!Array<string>} requires goog symbols or relative paths to Closure\n * this depends on.\n * @param {!Object<string, string>} loadFlags\n * @param {boolean} needsTranspile\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n * @extends {goog.TransformedDependency}\n */\n goog.GoogModuleDependency = function(\n path, relativePath, provides, requires, loadFlags, needsTranspile,\n transpiler) {\n goog.GoogModuleDependency.base(\n this, 'constructor', path, relativePath, provides, requires, loadFlags);\n /** @private @const */\n this.needsTranspile_ = needsTranspile;\n /** @private @const */\n this.transpiler_ = transpiler;\n };\n goog.inherits(goog.GoogModuleDependency, goog.TransformedDependency);\n\n\n /**\n * @override\n * @param {string} contents\n * @return {string}\n */\n goog.GoogModuleDependency.prototype.transform = function(contents) {\n if (this.needsTranspile_) {\n contents = this.transpiler_.transpile(contents, this.getPathName());\n }\n\n if (!goog.LOAD_MODULE_USING_EVAL || goog.global.JSON === undefined) {\n return '' +\n 'goog.loadModule(function(exports) {' +\n '\"use strict\";' + contents +\n '\\n' + // terminate any trailing single line comment.\n ';return exports' +\n '});' +\n '\\n//# sourceURL=' + this.path + '\\n';\n } else {\n return '' +\n 'goog.loadModule(' +\n goog.global.JSON.stringify(\n contents + '\\n//# sourceURL=' + this.path + '\\n') +\n ');';\n }\n };\n\n\n /**\n * @param {string} relPath\n * @param {!Array<string>|undefined} provides\n * @param {!Array<string>} requires\n * @param {boolean|!Object<string>=} opt_loadFlags\n * @see goog.addDependency\n */\n goog.DebugLoader_.prototype.addDependency = function(\n relPath, provides, requires, opt_loadFlags) {\n provides = provides || [];\n relPath = relPath.replace(/\\\\/g, '/');\n var path = goog.normalizePath_(goog.basePath + relPath);\n if (!opt_loadFlags || typeof opt_loadFlags === 'boolean') {\n opt_loadFlags = opt_loadFlags ? {'module': goog.ModuleType.GOOG} : {};\n }\n var dep = this.factory_.createDependency(\n path, relPath, provides, requires, opt_loadFlags,\n goog.transpiler_.needsTranspile(\n opt_loadFlags['lang'] || 'es3', opt_loadFlags['module']));\n this.dependencies_[path] = dep;\n for (var i = 0; i < provides.length; i++) {\n this.idToPath_[provides[i]] = path;\n }\n this.idToPath_[relPath] = path;\n };\n\n\n /**\n * Creates goog.Dependency instances for the debug loader to load.\n *\n * Should be overridden to have the debug loader use custom subclasses of\n * goog.Dependency.\n *\n * @param {!goog.Transpiler} transpiler\n * @struct @constructor\n */\n goog.DependencyFactory = function(transpiler) {\n /** @protected @const */\n this.transpiler = transpiler;\n };\n\n\n /**\n * @param {string} path Absolute path of the file.\n * @param {string} relativePath Path relative to closure’s base.js.\n * @param {!Array<string>} provides Array of provided goog.provide/module ids.\n * @param {!Array<string>} requires Array of required goog.provide/module /\n * relative ES6 module paths.\n * @param {!Object<string, string>} loadFlags\n * @param {boolean} needsTranspile True if the file needs to be transpiled\n * per the goog.Transpiler.\n * @return {!goog.Dependency}\n */\n goog.DependencyFactory.prototype.createDependency = function(\n path, relativePath, provides, requires, loadFlags, needsTranspile) {\n\n if (loadFlags['module'] == goog.ModuleType.GOOG) {\n return new goog.GoogModuleDependency(\n path, relativePath, provides, requires, loadFlags, needsTranspile,\n this.transpiler);\n } else if (needsTranspile) {\n return new goog.TranspiledDependency(\n path, relativePath, provides, requires, loadFlags, this.transpiler);\n } else {\n if (loadFlags['module'] == goog.ModuleType.ES6) {\n if (goog.TRANSPILE == 'never' && goog.ASSUME_ES_MODULES_TRANSPILED) {\n return new goog.PreTranspiledEs6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n } else {\n return new goog.Es6ModuleDependency(\n path, relativePath, provides, requires, loadFlags);\n }\n } else {\n return new goog.Dependency(\n path, relativePath, provides, requires, loadFlags);\n }\n }\n };\n\n\n /** @private @const */\n goog.debugLoader_ = new goog.DebugLoader_();\n\n\n /**\n * Loads the Closure Dependency file.\n *\n * Exposed a public function so CLOSURE_NO_DEPS can be set to false, base\n * loaded, setDependencyFactory called, and then this called. i.e. allows\n * custom loading of the deps file.\n */\n goog.loadClosureDeps = function() {\n goog.debugLoader_.loadClosureDeps();\n };\n\n\n /**\n * Sets the dependency factory, which can be used to create custom\n * goog.Dependency implementations to control how dependencies are loaded.\n *\n * Note: if you wish to call this function and provide your own implemnetation\n * it is a wise idea to set CLOSURE_NO_DEPS to true, otherwise the dependency\n * file and all of its goog.addDependency calls will use the default factory.\n * You can call goog.loadClosureDeps to load the Closure dependency file\n * later, after your factory is injected.\n *\n * @param {!goog.DependencyFactory} factory\n */\n goog.setDependencyFactory = function(factory) {\n goog.debugLoader_.setDependencyFactory(factory);\n };\n\n\n /**\n * Trusted Types policy for the debug loader.\n * @private @const {?TrustedTypePolicy}\n */\n goog.TRUSTED_TYPES_POLICY_ = goog.TRUSTED_TYPES_POLICY_NAME ?\n goog.createTrustedTypesPolicy(goog.TRUSTED_TYPES_POLICY_NAME + '#base') :\n null;\n\n if (!goog.global.CLOSURE_NO_DEPS) {\n goog.debugLoader_.loadClosureDeps();\n }\n\n\n /**\n * Bootstraps the given namespaces and calls the callback once they are\n * available either via goog.require. This is a replacement for using\n * `goog.require` to bootstrap Closure JavaScript. Previously a `goog.require`\n * in an HTML file would guarantee that the require'd namespace was available\n * in the next immediate script tag. With ES6 modules this no longer a\n * guarantee.\n *\n * @param {!Array<string>} namespaces\n * @param {function(): ?} callback Function to call once all the namespaces\n * have loaded. Always called asynchronously.\n */\n goog.bootstrap = function(namespaces, callback) {\n goog.debugLoader_.bootstrap(namespaces, callback);\n };\n}\n\n\nif (!COMPILED) {\n var isChrome87 = false;\n // Cannot run check for Chrome <87 bug in case of strict CSP environments.\n // TODO(user): Remove once Chrome <87 bug is no longer a problem.\n try {\n isChrome87 = eval(goog.global.trustedTypes.emptyScript) !==\n goog.global.trustedTypes.emptyScript;\n } catch (err) {\n }\n\n /**\n * Trusted Types for running dev servers.\n *\n * @private @const\n */\n goog.CLOSURE_EVAL_PREFILTER_ =\n // Detect Chrome <87 bug with TT and eval.\n goog.global.trustedTypes && isChrome87 &&\n goog.createTrustedTypesPolicy('goog#base#devonly#eval') ||\n {createScript: goog.identity_};\n}\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implements the disposable interface.\n */\n\ngoog.provide('goog.Disposable');\n\ngoog.require('goog.disposable.IDisposable');\ngoog.require('goog.dispose');\n/**\n * TODO(user): Remove this require.\n * @suppress {extraRequire}\n */\ngoog.require('goog.disposeAll');\n\n/**\n * Class that provides the basic implementation for disposable objects. If your\n * class holds references or resources that can't be collected by standard GC,\n * it should extend this class or implement the disposable interface (defined\n * in goog.disposable.IDisposable). See description of\n * goog.disposable.IDisposable for examples of cleanup.\n * @constructor\n * @implements {goog.disposable.IDisposable}\n */\ngoog.Disposable = function() {\n 'use strict';\n /**\n * If monitoring the goog.Disposable instances is enabled, stores the creation\n * stack trace of the Disposable instance.\n * @type {string|undefined}\n */\n this.creationStack;\n\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n if (goog.Disposable.INCLUDE_STACK_ON_CREATION) {\n this.creationStack = new Error().stack;\n }\n goog.Disposable.instances_[goog.getUid(this)] = this;\n }\n // Support sealing\n this.disposed_ = this.disposed_;\n this.onDisposeCallbacks_ = this.onDisposeCallbacks_;\n};\n\n\n/**\n * @enum {number} Different monitoring modes for Disposable.\n */\ngoog.Disposable.MonitoringMode = {\n /**\n * No monitoring.\n */\n OFF: 0,\n /**\n * Creating and disposing the goog.Disposable instances is monitored. All\n * disposable objects need to call the `goog.Disposable` base\n * constructor. The PERMANENT mode must be switched on before creating any\n * goog.Disposable instances.\n */\n PERMANENT: 1,\n /**\n * INTERACTIVE mode can be switched on and off on the fly without producing\n * errors. It also doesn't warn if the disposable objects don't call the\n * `goog.Disposable` base constructor.\n */\n INTERACTIVE: 2\n};\n\n\n/**\n * @define {number} The monitoring mode of the goog.Disposable\n * instances. Default is OFF. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.Disposable.MONITORING_MODE =\n goog.define('goog.Disposable.MONITORING_MODE', 0);\n\n\n/**\n * @define {boolean} Whether to attach creation stack to each created disposable\n * instance; This is only relevant for when MonitoringMode != OFF.\n */\ngoog.Disposable.INCLUDE_STACK_ON_CREATION =\n goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true);\n\n\n/**\n * Maps the unique ID of every undisposed `goog.Disposable` object to\n * the object itself.\n * @type {!Object<number, !goog.Disposable>}\n * @private\n */\ngoog.Disposable.instances_ = {};\n\n\n/**\n * @return {!Array<!goog.Disposable>} All `goog.Disposable` objects that\n * haven't been disposed of.\n */\ngoog.Disposable.getUndisposedObjects = function() {\n 'use strict';\n var ret = [];\n for (var id in goog.Disposable.instances_) {\n if (goog.Disposable.instances_.hasOwnProperty(id)) {\n ret.push(goog.Disposable.instances_[Number(id)]);\n }\n }\n return ret;\n};\n\n\n/**\n * Clears the registry of undisposed objects but doesn't dispose of them.\n */\ngoog.Disposable.clearUndisposedObjects = function() {\n 'use strict';\n goog.Disposable.instances_ = {};\n};\n\n\n/**\n * Whether the object has been disposed of.\n * @type {boolean}\n * @private\n */\ngoog.Disposable.prototype.disposed_ = false;\n\n\n/**\n * Callbacks to invoke when this object is disposed.\n * @type {Array<!Function>}\n * @private\n */\ngoog.Disposable.prototype.onDisposeCallbacks_;\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @override\n */\ngoog.Disposable.prototype.isDisposed = function() {\n 'use strict';\n return this.disposed_;\n};\n\n\n/**\n * @return {boolean} Whether the object has been disposed of.\n * @deprecated Use {@link #isDisposed} instead.\n */\ngoog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed;\n\n\n/**\n * Disposes of the object. If the object hasn't already been disposed of, calls\n * {@link #disposeInternal}. Classes that extend `goog.Disposable` should\n * override {@link #disposeInternal} in order to cleanup references, resources\n * and other disposable objects. Reentrant.\n *\n * @return {void} Nothing.\n * @override\n */\ngoog.Disposable.prototype.dispose = function() {\n 'use strict';\n if (!this.disposed_) {\n // Set disposed_ to true first, in case during the chain of disposal this\n // gets disposed recursively.\n this.disposed_ = true;\n this.disposeInternal();\n if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) {\n var uid = goog.getUid(this);\n if (goog.Disposable.MONITORING_MODE ==\n goog.Disposable.MonitoringMode.PERMANENT &&\n !goog.Disposable.instances_.hasOwnProperty(uid)) {\n throw new Error(\n this + ' did not call the goog.Disposable base ' +\n 'constructor or was disposed of after a clearUndisposedObjects ' +\n 'call');\n }\n if (goog.Disposable.MONITORING_MODE !=\n goog.Disposable.MonitoringMode.OFF &&\n this.onDisposeCallbacks_ && this.onDisposeCallbacks_.length > 0) {\n throw new Error(\n this + ' did not empty its onDisposeCallbacks queue. This ' +\n 'probably means it overrode dispose() or disposeInternal() ' +\n 'without calling the superclass\\' method.');\n }\n delete goog.Disposable.instances_[uid];\n }\n }\n};\n\n\n/**\n * Associates a disposable object with this object so that they will be disposed\n * together.\n * @param {goog.disposable.IDisposable} disposable that will be disposed when\n * this object is disposed.\n */\ngoog.Disposable.prototype.registerDisposable = function(disposable) {\n 'use strict';\n this.addOnDisposeCallback(goog.partial(goog.dispose, disposable));\n};\n\n\n/**\n * Invokes a callback function when this object is disposed. Callbacks are\n * invoked in the order in which they were added. If a callback is added to\n * an already disposed Disposable, it will be called immediately.\n * @param {function(this:T):?} callback The callback function.\n * @param {T=} opt_scope An optional scope to call the callback in.\n * @template T\n */\ngoog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) {\n 'use strict';\n if (this.disposed_) {\n opt_scope !== undefined ? callback.call(opt_scope) : callback();\n return;\n }\n if (!this.onDisposeCallbacks_) {\n this.onDisposeCallbacks_ = [];\n }\n\n this.onDisposeCallbacks_.push(\n opt_scope !== undefined ? goog.bind(callback, opt_scope) : callback);\n};\n\n\n/**\n * Performs appropriate cleanup. See description of goog.disposable.IDisposable\n * for examples. Classes that extend `goog.Disposable` should override this\n * method. Not reentrant. To avoid calling it twice, it must only be called from\n * the subclass' `disposeInternal` method. Everywhere else the public `dispose`\n * method must be used. For example:\n *\n * <pre>\n * mypackage.MyClass = function() {\n * mypackage.MyClass.base(this, 'constructor');\n * // Constructor logic specific to MyClass.\n * ...\n * };\n * goog.inherits(mypackage.MyClass, goog.Disposable);\n *\n * mypackage.MyClass.prototype.disposeInternal = function() {\n * // Dispose logic specific to MyClass.\n * ...\n * // Call superclass's disposeInternal at the end of the subclass's, like\n * // in C++, to avoid hard-to-catch issues.\n * mypackage.MyClass.base(this, 'disposeInternal');\n * };\n * </pre>\n *\n * @protected\n */\ngoog.Disposable.prototype.disposeInternal = function() {\n 'use strict';\n if (this.onDisposeCallbacks_) {\n while (this.onDisposeCallbacks_.length) {\n this.onDisposeCallbacks_.shift()();\n }\n }\n};\n\n\n/**\n * Returns True if we can verify the object is disposed.\n * Calls `isDisposed` on the argument if it supports it. If obj\n * is not an object with an isDisposed() method, return false.\n * @param {*} obj The object to investigate.\n * @return {boolean} True if we can verify the object is disposed.\n */\ngoog.Disposable.isDisposed = function(obj) {\n 'use strict';\n if (obj && typeof obj.isDisposed == 'function') {\n return obj.isDisposed();\n }\n return false;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating arrays.\n */\n\n\ngoog.module('goog.array');\ngoog.module.declareLegacyNamespace();\n\nconst asserts = goog.require('goog.asserts');\n\n\n/**\n * @define {boolean} NATIVE_ARRAY_PROTOTYPES indicates whether the code should\n * rely on Array.prototype functions, if available.\n *\n * The Array.prototype functions can be defined by external libraries like\n * Prototype and setting this flag to false forces closure to use its own\n * goog.array implementation.\n *\n * If your javascript can be loaded by a third party site and you are wary about\n * relying on the prototype functions, specify\n * \"--define goog.NATIVE_ARRAY_PROTOTYPES=false\" to the JSCompiler.\n *\n * Setting goog.TRUSTED_SITE to false will automatically set\n * NATIVE_ARRAY_PROTOTYPES to false.\n */\ngoog.NATIVE_ARRAY_PROTOTYPES =\n goog.define('goog.NATIVE_ARRAY_PROTOTYPES', goog.TRUSTED_SITE);\n\n\n/**\n * @define {boolean} If true, JSCompiler will use the native implementation of\n * array functions where appropriate (e.g., `Array#filter`) and remove the\n * unused pure JS implementation.\n */\nconst ASSUME_NATIVE_FUNCTIONS = goog.define(\n 'goog.array.ASSUME_NATIVE_FUNCTIONS', goog.FEATURESET_YEAR > 2012);\nexports.ASSUME_NATIVE_FUNCTIONS = ASSUME_NATIVE_FUNCTIONS;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.last}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nfunction peek(array) {\n return array[array.length - 1];\n}\nexports.peek = peek;\n\n\n/**\n * Returns the last element in an array without removing it.\n * Same as {@link goog.array.peek}.\n * @param {IArrayLike<T>|string} array The array.\n * @return {T} Last item in array.\n * @template T\n */\nexports.last = peek;\n\n// NOTE(arv): Since most of the array functions are generic it allows you to\n// pass an array-like object. Strings have a length and are considered array-\n// like. However, the 'in' operator does not work on strings so we cannot just\n// use the array path even if the browser supports indexing into strings. We\n// therefore end up splitting the string.\n\n\n/**\n * Returns the index of the first element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-indexof}\n *\n * @param {IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at index 0.\n * @return {number} The index of the first matching array element.\n * @template T\n */\nconst indexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.indexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.indexOf.call(arr, obj, opt_fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n const fromIndex = opt_fromIndex == null ?\n 0 :\n (opt_fromIndex < 0 ? Math.max(0, arr.length + opt_fromIndex) :\n opt_fromIndex);\n\n if (typeof arr === 'string') {\n // Array.prototype.indexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.indexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i < arr.length; i++) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.indexOf = indexOf;\n\n\n/**\n * Returns the index of the last element of an array with a specified value, or\n * -1 if the element is not present in the array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-lastindexof}\n *\n * @param {!IArrayLike<T>|string} arr The array to be searched.\n * @param {T} obj The object for which we are searching.\n * @param {?number=} opt_fromIndex The index at which to start the search. If\n * omitted the search starts at the end of the array.\n * @return {number} The index of the last matching array element.\n * @template T\n */\nconst lastIndexOf = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.lastIndexOf) ?\n function(arr, obj, opt_fromIndex) {\n asserts.assert(arr.length != null);\n\n // Firefox treats undefined and null as 0 in the fromIndex argument which\n // leads it to always return -1\n const fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n return Array.prototype.lastIndexOf.call(arr, obj, fromIndex);\n } :\n function(arr, obj, opt_fromIndex) {\n let fromIndex = opt_fromIndex == null ? arr.length - 1 : opt_fromIndex;\n\n if (fromIndex < 0) {\n fromIndex = Math.max(0, arr.length + fromIndex);\n }\n\n if (typeof arr === 'string') {\n // Array.prototype.lastIndexOf uses === so only strings should be found.\n if (typeof obj !== 'string' || obj.length != 1) {\n return -1;\n }\n return arr.lastIndexOf(obj, fromIndex);\n }\n\n for (let i = fromIndex; i >= 0; i--) {\n if (i in arr && arr[i] === obj) return i;\n }\n return -1;\n };\nexports.lastIndexOf = lastIndexOf;\n\n\n/**\n * Calls a function for each element in an array. Skips holes in the array.\n * See {@link http://tinyurl.com/developer-mozilla-org-array-foreach}\n *\n * @param {IArrayLike<T>|string} arr Array or array like object over\n * which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function takes 3 arguments (the element, the index and the\n * array). The return value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @template T,S\n */\nconst forEach = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.forEach) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n Array.prototype.forEach.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n };\nexports.forEach = forEach;\n\n\n/**\n * Calls a function for each element in an array, starting from the last\n * element rather than the first.\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this: S, T, number, ?): ?} f The function to call for every\n * element. This function\n * takes 3 arguments (the element, the index and the array). The return\n * value is ignored.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @template T,S\n */\nfunction forEachRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; --i) {\n if (i in arr2) {\n f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n}\nexports.forEachRight = forEachRight;\n\n\n/**\n * Calls a function for each element in an array, and if the function returns\n * true adds the element to a new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-filter}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?):boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and must\n * return a Boolean. If the return value is true the element is added to the\n * result array. If it is false the element is not included.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {!Array<T>} a new array in which only elements that passed the test\n * are present.\n * @template T,S\n */\nconst filter = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.filter) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.filter.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = [];\n let resLength = 0;\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n const val = arr2[i]; // in case f mutates arr2\n if (f.call(/** @type {?} */ (opt_obj), val, i, arr)) {\n res[resLength++] = val;\n }\n }\n }\n return res;\n };\nexports.filter = filter;\n\n\n/**\n * Calls a function for each element in an array and inserts the result into a\n * new array.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-map}\n *\n * @param {IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): RESULT} f The function to call\n * for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return something. The result will be\n * inserted into a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the results from f.\n * @template THIS, VALUE, RESULT\n */\nconst map = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.map) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.map.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const res = new Array(l);\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2) {\n res[i] = f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr);\n }\n }\n return res;\n };\nexports.map = map;\n\n\n/**\n * Passes every element of an array into a function and accumulates the result.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduce}\n * Note that this implementation differs from the native Array.prototype.reduce\n * in that the initial value is assumed to be defined (the MDN docs linked above\n * recommend not omitting this parameter, although it is technically optional).\n *\n * For example:\n * var a = [1, 2, 3, 4];\n * reduce(a, function(r, v, i, arr) {return r + v;}, 0);\n * returns 10\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Result of evaluating f repeatedly across the values of the array.\n * @template T,S,R\n */\nconst reduce = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduce) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduce.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n let rval = val;\n forEach(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduce = reduce;\n\n\n/**\n * Passes every element of an array into a function and accumulates the result,\n * starting from the last element and working towards the first.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-reduceright}\n *\n * For example:\n * var a = ['a', 'b', 'c'];\n * reduceRight(a, function(r, v, i, arr) {return r + v;}, '');\n * returns 'cba'\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, R, T, number, ?) : R} f The function to call for\n * every element. This function\n * takes 4 arguments (the function's previous result or the initial value,\n * the value of the current array element, the current array index, and the\n * array itself)\n * function(previousValue, currentValue, index, array).\n * @param {?} val The initial value to pass into the function on the first call.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {R} Object returned as a result of evaluating f repeatedly across the\n * values of the array.\n * @template T,S,R\n */\nconst reduceRight = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.reduceRight) ?\n function(arr, f, val, opt_obj) {\n asserts.assert(arr.length != null);\n asserts.assert(f != null);\n if (opt_obj) {\n f = goog.bind(f, opt_obj);\n }\n return Array.prototype.reduceRight.call(arr, f, val);\n } :\n function(arr, f, val, opt_obj) {\n let rval = val;\n forEachRight(arr, function(val, index) {\n rval = f.call(/** @type {?} */ (opt_obj), rval, val, index, arr);\n });\n return rval;\n };\nexports.reduceRight = reduceRight;\n\n\n/**\n * Calls f for each element of an array. If any call returns true, some()\n * returns true (without checking the remaining elements). If all calls\n * return false, some() returns false.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-some}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} true if any element passes the test.\n * @template T,S\n */\nconst some = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.some) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.some.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return true;\n }\n }\n return false;\n };\nexports.some = some;\n\n\n/**\n * Call f for each element of an array. If all calls return true, every()\n * returns true. If any call returns false, every() returns false and\n * does not continue to check the remaining elements.\n *\n * See {@link http://tinyurl.com/developer-mozilla-org-array-every}\n *\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within f.\n * @return {boolean} false if any element fails the test.\n * @template T,S\n */\nconst every = goog.NATIVE_ARRAY_PROTOTYPES &&\n (ASSUME_NATIVE_FUNCTIONS || Array.prototype.every) ?\n function(arr, f, opt_obj) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.every.call(arr, f, opt_obj);\n } :\n function(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && !f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return false;\n }\n }\n return true;\n };\nexports.every = every;\n\n\n/**\n * Counts the array elements that fulfill the predicate, i.e. for which the\n * callback function returns true. Skips holes in the array.\n *\n * @param {!IArrayLike<T>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this: S, T, number, ?): boolean} f The function to call for\n * every element. Takes 3 arguments (the element, the index and the array).\n * @param {S=} opt_obj The object to be used as the value of 'this' within f.\n * @return {number} The number of the matching elements.\n * @template T,S\n */\nfunction count(arr, f, opt_obj) {\n let count = 0;\n forEach(arr, function(element, index, arr) {\n if (f.call(/** @type {?} */ (opt_obj), element, index, arr)) {\n ++count;\n }\n }, opt_obj);\n return count;\n}\nexports.count = count;\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The first array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\nfunction find(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.find = find;\n\n\n/**\n * Search an array for the first element that satisfies a given condition and\n * return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call for\n * every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the first array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\nfunction findIndex(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = 0; i < l; i++) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\nexports.findIndex = findIndex;\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return that element.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {T|null} The last array element that passes the test, or null if no\n * element is found.\n * @template T,S\n */\nfunction findRight(arr, f, opt_obj) {\n const i = findIndexRight(arr, f, opt_obj);\n return i < 0 ? null : typeof arr === 'string' ? arr.charAt(i) : arr[i];\n}\nexports.findRight = findRight;\n\n\n/**\n * Search an array (in reverse order) for the last element that satisfies a\n * given condition and return its index.\n * @param {IArrayLike<T>|string} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The index of the last array element that passes the test,\n * or -1 if no element is found.\n * @template T,S\n */\nfunction findIndexRight(arr, f, opt_obj) {\n const l = arr.length; // must be fixed during loop... see docs\n const arr2 = (typeof arr === 'string') ? arr.split('') : arr;\n for (let i = l - 1; i >= 0; i--) {\n if (i in arr2 && f.call(/** @type {?} */ (opt_obj), arr2[i], i, arr)) {\n return i;\n }\n }\n return -1;\n}\nexports.findIndexRight = findIndexRight;\n\n\n/**\n * Whether the array contains the given object.\n * @param {IArrayLike<?>|string} arr The array to test for the presence of the\n * element.\n * @param {*} obj The object for which to test.\n * @return {boolean} true if obj is present.\n */\nfunction contains(arr, obj) {\n return indexOf(arr, obj) >= 0;\n}\nexports.contains = contains;\n\n\n/**\n * Whether the array is empty.\n * @param {IArrayLike<?>|string} arr The array to test.\n * @return {boolean} true if empty.\n */\nfunction isEmpty(arr) {\n return arr.length == 0;\n}\nexports.isEmpty = isEmpty;\n\n\n/**\n * Clears the array.\n * @param {IArrayLike<?>} arr Array or array like object to clear.\n */\nfunction clear(arr) {\n // For non real arrays we don't have the magic length so we delete the\n // indices.\n if (!Array.isArray(arr)) {\n for (let i = arr.length - 1; i >= 0; i--) {\n delete arr[i];\n }\n }\n arr.length = 0;\n}\nexports.clear = clear;\n\n\n/**\n * Pushes an item into an array, if it's not already in the array.\n * @param {Array<T>} arr Array into which to insert the item.\n * @param {T} obj Value to add.\n * @template T\n */\nfunction insert(arr, obj) {\n if (!contains(arr, obj)) {\n arr.push(obj);\n }\n}\nexports.insert = insert;\n\n\n/**\n * Inserts an object at the given index of the array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {*} obj The object to insert.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\nfunction insertAt(arr, obj, opt_i) {\n splice(arr, opt_i, 0, obj);\n}\nexports.insertAt = insertAt;\n\n\n/**\n * Inserts at the given index of the array, all elements of another array.\n * @param {IArrayLike<?>} arr The array to modify.\n * @param {IArrayLike<?>} elementsToAdd The array of elements to add.\n * @param {number=} opt_i The index at which to insert the object. If omitted,\n * treated as 0. A negative index is counted from the end of the array.\n */\nfunction insertArrayAt(arr, elementsToAdd, opt_i) {\n goog.partial(splice, arr, opt_i, 0).apply(null, elementsToAdd);\n}\nexports.insertArrayAt = insertArrayAt;\n\n\n/**\n * Inserts an object into an array before a specified object.\n * @param {Array<T>} arr The array to modify.\n * @param {T} obj The object to insert.\n * @param {T=} opt_obj2 The object before which obj should be inserted. If obj2\n * is omitted or not found, obj is inserted at the end of the array.\n * @template T\n */\nfunction insertBefore(arr, obj, opt_obj2) {\n let i;\n if (arguments.length == 2 || (i = indexOf(arr, opt_obj2)) < 0) {\n arr.push(obj);\n } else {\n insertAt(arr, obj, i);\n }\n}\nexports.insertBefore = insertBefore;\n\n\n/**\n * Removes the first occurrence of a particular value from an array.\n * @param {IArrayLike<T>} arr Array from which to remove\n * value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\nfunction remove(arr, obj) {\n const i = indexOf(arr, obj);\n let rv;\n if ((rv = i >= 0)) {\n removeAt(arr, i);\n }\n return rv;\n}\nexports.remove = remove;\n\n\n/**\n * Removes the last occurrence of a particular value from an array.\n * @param {!IArrayLike<T>} arr Array from which to remove value.\n * @param {T} obj Object to remove.\n * @return {boolean} True if an element was removed.\n * @template T\n */\nfunction removeLast(arr, obj) {\n const i = lastIndexOf(arr, obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeLast = removeLast;\n\n\n/**\n * Removes from an array the element at index i\n * @param {IArrayLike<?>} arr Array or array like object from which to\n * remove value.\n * @param {number} i The index to remove.\n * @return {boolean} True if an element was removed.\n */\nfunction removeAt(arr, i) {\n asserts.assert(arr.length != null);\n\n // use generic form of splice\n // splice returns the removed items and if successful the length of that\n // will be 1\n return Array.prototype.splice.call(arr, i, 1).length == 1;\n}\nexports.removeAt = removeAt;\n\n\n/**\n * Removes the first value that satisfies the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {boolean} True if an element was removed.\n * @template T,S\n */\nfunction removeIf(arr, f, opt_obj) {\n const i = findIndex(arr, f, opt_obj);\n if (i >= 0) {\n removeAt(arr, i);\n return true;\n }\n return false;\n}\nexports.removeIf = removeIf;\n\n\n/**\n * Removes all values that satisfy the given condition.\n * @param {IArrayLike<T>} arr Array or array\n * like object over which to iterate.\n * @param {?function(this:S, T, number, ?) : boolean} f The function to call\n * for every element. This function\n * takes 3 arguments (the element, the index and the array) and should\n * return a boolean.\n * @param {S=} opt_obj An optional \"this\" context for the function.\n * @return {number} The number of items removed\n * @template T,S\n */\nfunction removeAllIf(arr, f, opt_obj) {\n let removedCount = 0;\n forEachRight(arr, function(val, index) {\n if (f.call(/** @type {?} */ (opt_obj), val, index, arr)) {\n if (removeAt(arr, index)) {\n removedCount++;\n }\n }\n });\n return removedCount;\n}\nexports.removeAllIf = removeAllIf;\n\n\n/**\n * Returns a new array that is the result of joining the arguments. If arrays\n * are passed then their items are added, however, if non-arrays are passed they\n * will be added to the return array as is.\n *\n * Note that ArrayLike objects will be added as is, rather than having their\n * items added.\n *\n * concat([1, 2], [3, 4]) -> [1, 2, 3, 4]\n * concat(0, [1, 2]) -> [0, 1, 2]\n * concat([1, 2], null) -> [1, 2, null]\n *\n * There is bug in all current versions of IE (6, 7 and 8) where arrays created\n * in an iframe become corrupted soon (not immediately) after the iframe is\n * destroyed. This is common if loading data via goog.net.IframeIo, for example.\n * This corruption only affects the concat method which will start throwing\n * Catastrophic Errors (#-2147418113).\n *\n * See http://endoflow.com/scratch/corrupted-arrays.html for a test case.\n *\n * Internally goog.array should use this, so that all methods will continue to\n * work on these broken array objects.\n *\n * @param {...*} var_args Items to concatenate. Arrays will have each item\n * added, while primitives and objects will be added as is.\n * @return {!Array<?>} The new resultant array.\n */\nfunction concat(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.concat = concat;\n\n\n/**\n * Returns a new array that contains the contents of all the arrays passed.\n * @param {...!Array<T>} var_args\n * @return {!Array<T>}\n * @template T\n */\nfunction join(var_args) {\n return Array.prototype.concat.apply([], arguments);\n}\nexports.join = join;\n\n\n/**\n * Converts an object to an array.\n * @param {IArrayLike<T>|string} object The object to convert to an\n * array.\n * @return {!Array<T>} The object converted into an array. If object has a\n * length property, every property indexed with a non-negative number\n * less than length will be included in the result. If object does not\n * have a length property, an empty array will be returned.\n * @template T\n */\nfunction toArray(object) {\n const length = object.length;\n\n // If length is not a number the following is false. This case is kept for\n // backwards compatibility since there are callers that pass objects that are\n // not array like.\n if (length > 0) {\n const rv = new Array(length);\n for (let i = 0; i < length; i++) {\n rv[i] = object[i];\n }\n return rv;\n }\n return [];\n}\nexports.toArray = toArray;\n\n\n/**\n * Does a shallow copy of an array.\n * @param {IArrayLike<T>|string} arr Array or array-like object to\n * clone.\n * @return {!Array<T>} Clone of the input array.\n * @template T\n */\nconst clone = toArray;\nexports.clone = clone;\n\n\n/**\n * Extends an array with another array, element, or \"array like\" object.\n * This function operates 'in-place', it does not create a new Array.\n *\n * Example:\n * var a = [];\n * extend(a, [0, 1]);\n * a; // [0, 1]\n * extend(a, 2);\n * a; // [0, 1, 2]\n *\n * @param {Array<VALUE>} arr1 The array to modify.\n * @param {...(IArrayLike<VALUE>|VALUE)} var_args The elements or arrays of\n * elements to add to arr1.\n * @template VALUE\n */\nfunction extend(arr1, var_args) {\n for (let i = 1; i < arguments.length; i++) {\n const arr2 = arguments[i];\n if (goog.isArrayLike(arr2)) {\n const len1 = arr1.length || 0;\n const len2 = arr2.length || 0;\n arr1.length = len1 + len2;\n for (let j = 0; j < len2; j++) {\n arr1[len1 + j] = arr2[j];\n }\n } else {\n arr1.push(arr2);\n }\n }\n}\nexports.extend = extend;\n\n\n/**\n * Adds or removes elements from an array. This is a generic version of Array\n * splice. This means that it might work on other objects similar to arrays,\n * such as the arguments object.\n *\n * @param {IArrayLike<T>} arr The array to modify.\n * @param {number|undefined} index The index at which to start changing the\n * array. If not defined, treated as 0.\n * @param {number} howMany How many elements to remove (0 means no removal. A\n * value below 0 is treated as zero and so is any other non number. Numbers\n * are floored).\n * @param {...T} var_args Optional, additional elements to insert into the\n * array.\n * @return {!Array<T>} the removed elements.\n * @template T\n */\nfunction splice(arr, index, howMany, var_args) {\n asserts.assert(arr.length != null);\n\n return Array.prototype.splice.apply(arr, slice(arguments, 1));\n}\nexports.splice = splice;\n\n\n/**\n * Returns a new array from a segment of an array. This is a generic version of\n * Array slice. This means that it might work on other objects similar to\n * arrays, such as the arguments object.\n *\n * @param {IArrayLike<T>|string} arr The array from\n * which to copy a segment.\n * @param {number} start The index of the first element to copy.\n * @param {number=} opt_end The index after the last element to copy.\n * @return {!Array<T>} A new array containing the specified segment of the\n * original array.\n * @template T\n */\nfunction slice(arr, start, opt_end) {\n asserts.assert(arr.length != null);\n\n // passing 1 arg to slice is not the same as passing 2 where the second is\n // null or undefined (in that case the second argument is treated as 0).\n // we could use slice on the arguments object and then use apply instead of\n // testing the length\n if (arguments.length <= 2) {\n return Array.prototype.slice.call(arr, start);\n } else {\n return Array.prototype.slice.call(arr, start, opt_end);\n }\n}\nexports.slice = slice;\n\n\n/**\n * Removes all duplicates from an array (retaining only the first\n * occurrence of each array element). This function modifies the\n * array in place and doesn't change the order of the non-duplicate items.\n *\n * For objects, duplicates are identified as having the same unique ID as\n * defined by {@link goog.getUid}.\n *\n * Alternatively you can specify a custom hash function that returns a unique\n * value for each item in the array it should consider unique.\n *\n * Runtime: N,\n * Worstcase space: 2N (no dupes)\n *\n * @param {IArrayLike<T>} arr The array from which to remove\n * duplicates.\n * @param {Array=} opt_rv An optional array in which to return the results,\n * instead of performing the removal inplace. If specified, the original\n * array will remain unchanged.\n * @param {function(T):string=} opt_hashFn An optional function to use to\n * apply to every item in the array. This function should return a unique\n * value for each item in the array it should consider unique.\n * @template T\n */\nfunction removeDuplicates(arr, opt_rv, opt_hashFn) {\n const returnArray = opt_rv || arr;\n const defaultHashFn = function(item) {\n // Prefix each type with a single character representing the type to\n // prevent conflicting keys (e.g. true and 'true').\n return goog.isObject(item) ? 'o' + goog.getUid(item) :\n (typeof item).charAt(0) + item;\n };\n const hashFn = opt_hashFn || defaultHashFn;\n\n let cursorInsert = 0;\n let cursorRead = 0;\n const seen = {};\n\n while (cursorRead < arr.length) {\n const current = arr[cursorRead++];\n const key = hashFn(current);\n if (!Object.prototype.hasOwnProperty.call(seen, key)) {\n seen[key] = true;\n returnArray[cursorInsert++] = current;\n }\n }\n returnArray.length = cursorInsert;\n}\nexports.removeDuplicates = removeDuplicates;\n\n\n/**\n * Searches the specified array for the specified target using the binary\n * search algorithm. If no opt_compareFn is specified, elements are compared\n * using <code>defaultCompare</code>, which compares the elements\n * using the built in < and > operators. This will produce the expected\n * behavior for homogeneous arrays of String(s) and Number(s). The array\n * specified <b>must</b> be sorted in ascending order (as defined by the\n * comparison function). If the array is not sorted, results are undefined.\n * If the array contains multiple instances of the specified target value, the\n * left-most instance will be found.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {TARGET} target The sought value.\n * @param {function(TARGET, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, the target value and an element from your array, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @template TARGET, VALUE\n */\nfunction binarySearch(arr, target, opt_compareFn) {\n return binarySearch_(\n arr, opt_compareFn || defaultCompare, false /* isEvaluator */, target);\n}\nexports.binarySearch = binarySearch;\n\n\n/**\n * Selects an index in the specified array using the binary search algorithm.\n * The evaluator receives an element and determines whether the desired index\n * is before, at, or after it. The evaluator must be consistent (formally,\n * map(map(arr, evaluator, opt_obj), goog.math.sign)\n * must be monotonically non-increasing).\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<VALUE>} arr The array to be searched.\n * @param {function(this:THIS, VALUE, number, ?): number} evaluator\n * Evaluator function that receives 3 arguments (the element, the index and\n * the array). Should return a negative number, zero, or a positive number\n * depending on whether the desired index is before, at, or after the\n * element passed to it.\n * @param {THIS=} opt_obj The object to be used as the value of 'this'\n * within evaluator.\n * @return {number} Index of the leftmost element matched by the evaluator, if\n * such exists; otherwise (-(insertion point) - 1). The insertion point is\n * the index of the first element for which the evaluator returns negative,\n * or arr.length if no such element exists. The return value is non-negative\n * iff a match is found.\n * @template THIS, VALUE\n */\nfunction binarySelect(arr, evaluator, opt_obj) {\n return binarySearch_(\n arr, evaluator, true /* isEvaluator */, undefined /* opt_target */,\n opt_obj);\n}\nexports.binarySelect = binarySelect;\n\n\n/**\n * Implementation of a binary search algorithm which knows how to use both\n * comparison functions and evaluators. If an evaluator is provided, will call\n * the evaluator with the given optional data object, conforming to the\n * interface defined in binarySelect. Otherwise, if a comparison function is\n * provided, will call the comparison function against the given data object.\n *\n * This implementation purposefully does not use goog.bind or goog.partial for\n * performance reasons.\n *\n * Runtime: O(log n)\n *\n * @param {IArrayLike<?>} arr The array to be searched.\n * @param {function(?, ?, ?): number | function(?, ?): number} compareFn\n * Either an evaluator or a comparison function, as defined by binarySearch\n * and binarySelect above.\n * @param {boolean} isEvaluator Whether the function is an evaluator or a\n * comparison function.\n * @param {?=} opt_target If the function is a comparison function, then\n * this is the target to binary search for.\n * @param {Object=} opt_selfObj If the function is an evaluator, this is an\n * optional this object for the evaluator.\n * @return {number} Lowest index of the target value if found, otherwise\n * (-(insertion point) - 1). The insertion point is where the value should\n * be inserted into arr to preserve the sorted property. Return value >= 0\n * iff target is found.\n * @private\n */\nfunction binarySearch_(arr, compareFn, isEvaluator, opt_target, opt_selfObj) {\n let left = 0; // inclusive\n let right = arr.length; // exclusive\n let found;\n while (left < right) {\n const middle = left + ((right - left) >>> 1);\n let compareResult;\n if (isEvaluator) {\n compareResult = compareFn.call(opt_selfObj, arr[middle], middle, arr);\n } else {\n // NOTE(dimvar): To avoid this cast, we'd have to use function overloading\n // for the type of binarySearch_, which the type system can't express yet.\n compareResult = /** @type {function(?, ?): number} */ (compareFn)(\n opt_target, arr[middle]);\n }\n if (compareResult > 0) {\n left = middle + 1;\n } else {\n right = middle;\n // We are looking for the lowest index so we can't return immediately.\n found = !compareResult;\n }\n }\n // left is the index if found, or the insertion point otherwise.\n // Avoiding bitwise not operator, as that causes a loss in precision for array\n // indexes outside the bounds of a 32-bit signed integer. Array indexes have\n // a maximum value of 2^32-2 https://tc39.es/ecma262/#array-index\n return found ? left : -left - 1;\n}\n\n\n/**\n * Sorts the specified array into ascending order. If no opt_compareFn is\n * specified, elements are compared using\n * <code>defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s), unlike the native sort,\n * but will give unpredictable results for heterogeneous lists of strings and\n * numbers with different numbers of digits.\n *\n * This sort is not guaranteed to be stable.\n *\n * Runtime: Same as `Array.prototype.sort`\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T,T):number=} opt_compareFn Optional comparison\n * function by which the\n * array is to be ordered. Should take 2 arguments to compare, and return a\n * negative number, zero, or a positive number depending on whether the\n * first argument is less than, equal to, or greater than the second.\n * @template T\n */\nfunction sort(arr, opt_compareFn) {\n // TODO(arv): Update type annotation since null is not accepted.\n arr.sort(opt_compareFn || defaultCompare);\n}\nexports.sort = sort;\n\n\n/**\n * Sorts the specified array into ascending order in a stable way. If no\n * opt_compareFn is specified, elements are compared using\n * <code>defaultCompare</code>, which compares the elements using\n * the built in < and > operators. This will produce the expected behavior\n * for homogeneous arrays of String(s) and Number(s).\n *\n * Runtime: Same as `Array.prototype.sort`, plus an additional\n * O(n) overhead of copying the array twice.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {?function(T, T): number=} opt_compareFn Optional comparison function\n * by which the array is to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T\n */\nfunction stableSort(arr, opt_compareFn) {\n const compArr = new Array(arr.length);\n for (let i = 0; i < arr.length; i++) {\n compArr[i] = {index: i, value: arr[i]};\n }\n const valueCompareFn = opt_compareFn || defaultCompare;\n function stableCompareFn(obj1, obj2) {\n return valueCompareFn(obj1.value, obj2.value) || obj1.index - obj2.index;\n }\n sort(compArr, stableCompareFn);\n for (let i = 0; i < arr.length; i++) {\n arr[i] = compArr[i].value;\n }\n}\nexports.stableSort = stableSort;\n\n\n/**\n * Sort the specified array into ascending order based on item keys\n * returned by the specified key function.\n * If no opt_compareFn is specified, the keys are compared in ascending order\n * using <code>defaultCompare</code>.\n *\n * Runtime: O(S(f(n)), where S is runtime of <code>sort</code>\n * and f(n) is runtime of the key function.\n *\n * @param {Array<T>} arr The array to be sorted.\n * @param {function(T): K} keyFn Function taking array element and returning\n * a key used for sorting this element.\n * @param {?function(K, K): number=} opt_compareFn Optional comparison function\n * by which the keys are to be ordered. Should take 2 arguments to compare,\n * and return a negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template T,K\n */\nfunction sortByKey(arr, keyFn, opt_compareFn) {\n const keyCompareFn = opt_compareFn || defaultCompare;\n sort(arr, function(a, b) {\n return keyCompareFn(keyFn(a), keyFn(b));\n });\n}\nexports.sortByKey = sortByKey;\n\n\n/**\n * Sorts an array of objects by the specified object key and compare\n * function. If no compare function is provided, the key values are\n * compared in ascending order using <code>defaultCompare</code>.\n * This won't work for keys that get renamed by the compiler. So use\n * {'foo': 1, 'bar': 2} rather than {foo: 1, bar: 2}.\n * @param {Array<Object>} arr An array of objects to sort.\n * @param {string} key The object key to sort by.\n * @param {Function=} opt_compareFn The function to use to compare key\n * values.\n */\nfunction sortObjectsByKey(arr, key, opt_compareFn) {\n sortByKey(arr, function(obj) {\n return obj[key];\n }, opt_compareFn);\n}\nexports.sortObjectsByKey = sortObjectsByKey;\n\n\n/**\n * Tells if the array is sorted.\n * @param {!IArrayLike<T>} arr The array.\n * @param {?function(T,T):number=} opt_compareFn Function to compare the\n * array elements.\n * Should take 2 arguments to compare, and return a negative number, zero,\n * or a positive number depending on whether the first argument is less\n * than, equal to, or greater than the second.\n * @param {boolean=} opt_strict If true no equal elements are allowed.\n * @return {boolean} Whether the array is sorted.\n * @template T\n */\nfunction isSorted(arr, opt_compareFn, opt_strict) {\n const compare = opt_compareFn || defaultCompare;\n for (let i = 1; i < arr.length; i++) {\n const compareResult = compare(arr[i - 1], arr[i]);\n if (compareResult > 0 || compareResult == 0 && opt_strict) {\n return false;\n }\n }\n return true;\n}\nexports.isSorted = isSorted;\n\n\n/**\n * Compares two arrays for equality. Two arrays are considered equal if they\n * have the same length and their corresponding elements are equal according to\n * the comparison function.\n *\n * @param {IArrayLike<A>} arr1 The first array to compare.\n * @param {IArrayLike<B>} arr2 The second array to compare.\n * @param {?function(A,B):boolean=} opt_equalsFn Optional comparison function.\n * Should take 2 arguments to compare, and return true if the arguments\n * are equal. Defaults to {@link goog.array.defaultCompareEquality} which\n * compares the elements using the built-in '===' operator.\n * @return {boolean} Whether the two arrays are equal.\n * @template A\n * @template B\n */\nfunction equals(arr1, arr2, opt_equalsFn) {\n if (!goog.isArrayLike(arr1) || !goog.isArrayLike(arr2) ||\n arr1.length != arr2.length) {\n return false;\n }\n const l = arr1.length;\n const equalsFn = opt_equalsFn || defaultCompareEquality;\n for (let i = 0; i < l; i++) {\n if (!equalsFn(arr1[i], arr2[i])) {\n return false;\n }\n }\n return true;\n}\nexports.equals = equals;\n\n\n/**\n * 3-way array compare function.\n * @param {!IArrayLike<VALUE>} arr1 The first array to\n * compare.\n * @param {!IArrayLike<VALUE>} arr2 The second array to\n * compare.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is to be ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {number} Negative number, zero, or a positive number depending on\n * whether the first argument is less than, equal to, or greater than the\n * second.\n * @template VALUE\n */\nfunction compare3(arr1, arr2, opt_compareFn) {\n const compare = opt_compareFn || defaultCompare;\n const l = Math.min(arr1.length, arr2.length);\n for (let i = 0; i < l; i++) {\n const result = compare(arr1[i], arr2[i]);\n if (result != 0) {\n return result;\n }\n }\n return defaultCompare(arr1.length, arr2.length);\n}\nexports.compare3 = compare3;\n\n\n/**\n * Compares its two arguments for order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is less than, equal to, or greater than the second,\n * respectively.\n * @template VALUE\n */\nfunction defaultCompare(a, b) {\n return a > b ? 1 : a < b ? -1 : 0;\n}\nexports.defaultCompare = defaultCompare;\n\n\n/**\n * Compares its two arguments for inverse order, using the built in < and >\n * operators.\n * @param {VALUE} a The first object to be compared.\n * @param {VALUE} b The second object to be compared.\n * @return {number} A negative number, zero, or a positive number as the first\n * argument is greater than, equal to, or less than the second,\n * respectively.\n * @template VALUE\n */\nfunction inverseDefaultCompare(a, b) {\n return -defaultCompare(a, b);\n}\nexports.inverseDefaultCompare = inverseDefaultCompare;\n\n\n/**\n * Compares its two arguments for equality, using the built in === operator.\n * @param {*} a The first object to compare.\n * @param {*} b The second object to compare.\n * @return {boolean} True if the two arguments are equal, false otherwise.\n */\nfunction defaultCompareEquality(a, b) {\n return a === b;\n}\nexports.defaultCompareEquality = defaultCompareEquality;\n\n\n/**\n * Inserts a value into a sorted array. The array is not modified if the\n * value is already present.\n * @param {IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to insert.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was inserted.\n * @template VALUE\n */\nfunction binaryInsert(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n if (index < 0) {\n insertAt(array, value, -(index + 1));\n return true;\n }\n return false;\n}\nexports.binaryInsert = binaryInsert;\n\n\n/**\n * Removes a value from a sorted array.\n * @param {!IArrayLike<VALUE>} array The array to modify.\n * @param {VALUE} value The object to remove.\n * @param {function(VALUE, VALUE): number=} opt_compareFn Optional comparison\n * function by which the array is ordered. Should take 2 arguments to\n * compare, and return a negative number, zero, or a positive number\n * depending on whether the first argument is less than, equal to, or\n * greater than the second.\n * @return {boolean} True if an element was removed.\n * @template VALUE\n */\nfunction binaryRemove(array, value, opt_compareFn) {\n const index = binarySearch(array, value, opt_compareFn);\n return (index >= 0) ? removeAt(array, index) : false;\n}\nexports.binaryRemove = binaryRemove;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {IArrayLike<T>} array The array.\n * @param {function(this:S, T, number, !IArrayLike<T>):?} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index\n * and the array) and must return a valid object key (a string, number,\n * etc), or undefined, if that object should not be placed in a bucket.\n * @param {S=} opt_obj The object to be used as the value of 'this' within\n * sorter.\n * @return {!Object<!Array<T>>} An object, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template T,S\n */\nfunction bucket(array, sorter, opt_obj) {\n const buckets = {};\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter.call(/** @type {?} */ (opt_obj), value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n const bucket = buckets[key] || (buckets[key] = []);\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucket = bucket;\n\n\n/**\n * Splits an array into disjoint buckets according to a splitting function.\n * @param {!IArrayLike<V>} array The array.\n * @param {function(V, number, !IArrayLike<V>):(K|undefined)} sorter Function to\n * call for every element. This takes 3 arguments (the element, the index,\n * and the array) and must return a value to use as a key, or undefined, if\n * that object should not be placed in a bucket.\n * @return {!Map<K, !Array<V>>} A map, with keys being all of the unique\n * return values of sorter, and values being arrays containing the items for\n * which the splitter returned that key.\n * @template K,V\n */\nfunction bucketToMap(array, sorter) {\n const /** !Map<K, !Array<V>> */ buckets = new Map();\n\n for (let i = 0; i < array.length; i++) {\n const value = array[i];\n const key = sorter(value, i, array);\n if (key !== undefined) {\n // Push the value to the right bucket, creating it if necessary.\n let bucket = buckets.get(key);\n if (!bucket) {\n bucket = [];\n buckets.set(key, bucket);\n }\n bucket.push(value);\n }\n }\n\n return buckets;\n}\nexports.bucketToMap = bucketToMap;\n\n\n/**\n * Creates a new object built from the provided array and the key-generation\n * function.\n * @param {IArrayLike<T>} arr Array or array like object over\n * which to iterate whose elements will be the values in the new object.\n * @param {?function(this:S, T, number, ?) : string} keyFunc The function to\n * call for every element. This function takes 3 arguments (the element, the\n * index and the array) and should return a string that will be used as the\n * key for the element in the new object. If the function returns the same\n * key for more than one element, the value for that key is\n * implementation-defined.\n * @param {S=} opt_obj The object to be used as the value of 'this'\n * within keyFunc.\n * @return {!Object<T>} The new object.\n * @template T,S\n */\nfunction toObject(arr, keyFunc, opt_obj) {\n const ret = {};\n forEach(arr, function(element, index) {\n ret[keyFunc.call(/** @type {?} */ (opt_obj), element, index, arr)] =\n element;\n });\n return ret;\n}\nexports.toObject = toObject;\n\n\n/**\n * Creates a new ES6 Map built from the provided array and the key-generation\n * function.\n * @param {!IArrayLike<V>} arr Array or array like object over which to iterate\n * whose elements will be the values in the new object.\n * @param {?function(V, number, ?) : K} keyFunc The function to call for every\n * element. This function takes 3 arguments (the element, the index, and the\n * array) and should return a value that will be used as the key for the\n * element in the new object. If the function returns the same key for more\n * than one element, the value for that key is implementation-defined.\n * @return {!Map<K, V>} The new map.\n * @template K,V\n */\nfunction toMap(arr, keyFunc) {\n const /** !Map<K, V> */ map = new Map();\n\n for (let i = 0; i < arr.length; i++) {\n const element = arr[i];\n map.set(keyFunc(element, i, arr), element);\n }\n\n return map;\n}\nexports.toMap = toMap;\n\n\n/**\n * Creates a range of numbers in an arithmetic progression.\n *\n * Range takes 1, 2, or 3 arguments:\n * <pre>\n * range(5) is the same as range(0, 5, 1) and produces [0, 1, 2, 3, 4]\n * range(2, 5) is the same as range(2, 5, 1) and produces [2, 3, 4]\n * range(-2, -5, -1) produces [-2, -3, -4]\n * range(-2, -5, 1) produces [], since stepping by 1 wouldn't ever reach -5.\n * </pre>\n *\n * @param {number} startOrEnd The starting value of the range if an end argument\n * is provided. Otherwise, the start value is 0, and this is the end value.\n * @param {number=} opt_end The optional end value of the range.\n * @param {number=} opt_step The step size between range values. Defaults to 1\n * if opt_step is undefined or 0.\n * @return {!Array<number>} An array of numbers for the requested range. May be\n * an empty array if adding the step would not converge toward the end\n * value.\n */\nfunction range(startOrEnd, opt_end, opt_step) {\n const array = [];\n let start = 0;\n let end = startOrEnd;\n const step = opt_step || 1;\n if (opt_end !== undefined) {\n start = startOrEnd;\n end = opt_end;\n }\n\n if (step * (end - start) < 0) {\n // Sign mismatch: start + step will never reach the end value.\n return [];\n }\n\n if (step > 0) {\n for (let i = start; i < end; i += step) {\n array.push(i);\n }\n } else {\n for (let i = start; i > end; i += step) {\n array.push(i);\n }\n }\n return array;\n}\nexports.range = range;\n\n\n/**\n * Returns an array consisting of the given value repeated N times.\n *\n * @param {VALUE} value The value to repeat.\n * @param {number} n The repeat count.\n * @return {!Array<VALUE>} An array with the repeated value.\n * @template VALUE\n */\nfunction repeat(value, n) {\n const array = [];\n for (let i = 0; i < n; i++) {\n array[i] = value;\n }\n return array;\n}\nexports.repeat = repeat;\n\n\n/**\n * Returns an array consisting of every argument with all arrays\n * expanded in-place recursively.\n *\n * @param {...*} var_args The values to flatten.\n * @return {!Array<?>} An array containing the flattened values.\n */\nfunction flatten(var_args) {\n const CHUNK_SIZE = 8192;\n\n const result = [];\n for (let i = 0; i < arguments.length; i++) {\n const element = arguments[i];\n if (Array.isArray(element)) {\n for (let c = 0; c < element.length; c += CHUNK_SIZE) {\n const chunk = slice(element, c, c + CHUNK_SIZE);\n const recurseResult = flatten.apply(null, chunk);\n for (let r = 0; r < recurseResult.length; r++) {\n result.push(recurseResult[r]);\n }\n }\n } else {\n result.push(element);\n }\n }\n return result;\n}\nexports.flatten = flatten;\n\n\n/**\n * Rotates an array in-place. After calling this method, the element at\n * index i will be the element previously at index (i - n) %\n * array.length, for all values of i between 0 and array.length - 1,\n * inclusive.\n *\n * For example, suppose list comprises [t, a, n, k, s]. After invoking\n * rotate(array, 1) (or rotate(array, -4)), array will comprise [s, t, a, n, k].\n *\n * @param {!Array<T>} array The array to rotate.\n * @param {number} n The amount to rotate.\n * @return {!Array<T>} The array.\n * @template T\n */\nfunction rotate(array, n) {\n asserts.assert(array.length != null);\n\n if (array.length) {\n n %= array.length;\n if (n > 0) {\n Array.prototype.unshift.apply(array, array.splice(-n, n));\n } else if (n < 0) {\n Array.prototype.push.apply(array, array.splice(0, -n));\n }\n }\n return array;\n}\nexports.rotate = rotate;\n\n\n/**\n * Moves one item of an array to a new position keeping the order of the rest\n * of the items. Example use case: keeping a list of JavaScript objects\n * synchronized with the corresponding list of DOM elements after one of the\n * elements has been dragged to a new position.\n * @param {!IArrayLike<?>} arr The array to modify.\n * @param {number} fromIndex Index of the item to move between 0 and\n * `arr.length - 1`.\n * @param {number} toIndex Target index between 0 and `arr.length - 1`.\n */\nfunction moveItem(arr, fromIndex, toIndex) {\n asserts.assert(fromIndex >= 0 && fromIndex < arr.length);\n asserts.assert(toIndex >= 0 && toIndex < arr.length);\n // Remove 1 item at fromIndex.\n const removedItems = Array.prototype.splice.call(arr, fromIndex, 1);\n // Insert the removed item at toIndex.\n Array.prototype.splice.call(arr, toIndex, 0, removedItems[0]);\n // We don't use goog.array.insertAt and goog.array.removeAt, because they're\n // significantly slower than splice.\n}\nexports.moveItem = moveItem;\n\n\n/**\n * Creates a new array for which the element at position i is an array of the\n * ith element of the provided arrays. The returned array will only be as long\n * as the shortest array provided; additional values are ignored. For example,\n * the result of zipping [1, 2] and [3, 4, 5] is [[1,3], [2, 4]].\n *\n * This is similar to the zip() function in Python. See {@link\n * http://docs.python.org/library/functions.html#zip}\n *\n * @param {...!IArrayLike<?>} var_args Arrays to be combined.\n * @return {!Array<!Array<?>>} A new array of arrays created from\n * provided arrays.\n */\nfunction zip(var_args) {\n if (!arguments.length) {\n return [];\n }\n const result = [];\n let minLen = arguments[0].length;\n for (let i = 1; i < arguments.length; i++) {\n if (arguments[i].length < minLen) {\n minLen = arguments[i].length;\n }\n }\n for (let i = 0; i < minLen; i++) {\n const value = [];\n for (let j = 0; j < arguments.length; j++) {\n value.push(arguments[j][i]);\n }\n result.push(value);\n }\n return result;\n}\nexports.zip = zip;\n\n\n/**\n * Shuffles the values in the specified array using the Fisher-Yates in-place\n * shuffle (also known as the Knuth Shuffle). By default, calls Math.random()\n * and so resets the state of that random number generator. Similarly, may reset\n * the state of any other specified random number generator.\n *\n * Runtime: O(n)\n *\n * @param {!Array<?>} arr The array to be shuffled.\n * @param {function():number=} opt_randFn Optional random function to use for\n * shuffling.\n * Takes no arguments, and returns a random number on the interval [0, 1).\n * Defaults to Math.random() using JavaScript's built-in Math library.\n */\nfunction shuffle(arr, opt_randFn) {\n const randFn = opt_randFn || Math.random;\n\n for (let i = arr.length - 1; i > 0; i--) {\n // Choose a random array index in [0, i] (inclusive with i).\n const j = Math.floor(randFn() * (i + 1));\n\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n }\n}\nexports.shuffle = shuffle;\n\n\n/**\n * Returns a new array of elements from arr, based on the indexes of elements\n * provided by index_arr. For example, the result of index copying\n * ['a', 'b', 'c'] with index_arr [1,0,0,2] is ['b', 'a', 'a', 'c'].\n *\n * @param {!IArrayLike<T>} arr The array to get a indexed copy from.\n * @param {!IArrayLike<number>} index_arr An array of indexes to get from arr.\n * @return {!Array<T>} A new array of elements from arr in index_arr order.\n * @template T\n */\nfunction copyByIndex(arr, index_arr) {\n const result = [];\n forEach(index_arr, function(index) {\n result.push(arr[index]);\n });\n return result;\n}\nexports.copyByIndex = copyByIndex;\n\n\n/**\n * Maps each element of the input array into zero or more elements of the output\n * array.\n *\n * @param {!IArrayLike<VALUE>|string} arr Array or array like object\n * over which to iterate.\n * @param {function(this:THIS, VALUE, number, ?): !Array<RESULT>} f The function\n * to call for every element. This function takes 3 arguments (the element,\n * the index and the array) and should return an array. The result will be\n * used to extend a new array.\n * @param {THIS=} opt_obj The object to be used as the value of 'this' within f.\n * @return {!Array<RESULT>} a new array with the concatenation of all arrays\n * returned from f.\n * @template THIS, VALUE, RESULT\n */\nfunction concatMap(arr, f, opt_obj) {\n return concat.apply([], map(arr, f, opt_obj));\n}\nexports.concatMap = concatMap;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A base class for event objects.\n */\n\n\ngoog.provide('goog.events.Event');\n\n/**\n * goog.events.Event no longer depends on goog.Disposable. Keep requiring\n * goog.Disposable here to not break projects which assume this dependency.\n * @suppress {extraRequire}\n */\ngoog.require('goog.Disposable');\ngoog.require('goog.events.EventId');\n\n\n/**\n * A base class for event objects, so that they can support preventDefault and\n * stopPropagation.\n *\n * @param {string|!goog.events.EventId} type Event Type.\n * @param {Object=} opt_target Reference to the object that is the target of\n * this event. It has to implement the `EventTarget` interface\n * declared at {@link http://developer.mozilla.org/en/DOM/EventTarget}.\n * @constructor\n */\ngoog.events.Event = function(type, opt_target) {\n 'use strict';\n /**\n * Event type.\n * @type {string}\n */\n this.type = type instanceof goog.events.EventId ? String(type) : type;\n\n /**\n * TODO(tbreisacher): The type should probably be\n * EventTarget|goog.events.EventTarget.\n *\n * Target of the event.\n * @type {Object|undefined}\n */\n this.target = opt_target;\n\n /**\n * Object that had the listener attached.\n * @type {Object|undefined}\n */\n this.currentTarget = this.target;\n\n /**\n * Whether to cancel the event in internal capture/bubble processing for IE.\n * @type {boolean}\n * @private\n */\n this.propagationStopped_ = false;\n\n /**\n * Whether the default action has been prevented.\n * This is a property to match the W3C specification at\n * {@link http://www.w3.org/TR/DOM-Level-3-Events/\n * #events-event-type-defaultPrevented}.\n * Must be treated as read-only outside the class.\n * @type {boolean}\n */\n this.defaultPrevented = false;\n};\n\n/**\n * @return {boolean} true iff internal propagation has been stopped.\n */\ngoog.events.Event.prototype.hasPropagationStopped = function() {\n 'use strict';\n return this.propagationStopped_;\n};\n\n/**\n * Stops event propagation.\n * @return {void}\n */\ngoog.events.Event.prototype.stopPropagation = function() {\n 'use strict';\n this.propagationStopped_ = true;\n};\n\n\n/**\n * Prevents the default action, for example a link redirecting to a url.\n * @return {void}\n */\ngoog.events.Event.prototype.preventDefault = function() {\n 'use strict';\n this.defaultPrevented = true;\n};\n\n\n/**\n * Stops the propagation of the event. It is equivalent to\n * `e.stopPropagation()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.stopPropagation = function(e) {\n 'use strict';\n e.stopPropagation();\n};\n\n\n/**\n * Prevents the default action. It is equivalent to\n * `e.preventDefault()`, but can be used as the callback argument of\n * {@link goog.events.listen} without declaring another function.\n * @param {!goog.events.Event} e An event.\n * @return {void}\n */\ngoog.events.Event.preventDefault = function(e) {\n 'use strict';\n e.preventDefault();\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Browser capability checks for the events package.\n */\n\ngoog.module('goog.events.BrowserFeature');\ngoog.module.declareLegacyNamespace();\n\n\n/**\n * Tricks Closure Compiler into believing that a function is pure. The compiler\n * assumes that any `valueOf` function is pure, without analyzing its contents.\n *\n * @param {function(): T} fn\n * @return {T}\n * @template T\n */\nconst purify = (fn) => {\n return ({valueOf: fn}).valueOf();\n};\n\n\n/**\n * Enum of browser capabilities.\n * @enum {boolean}\n */\nexports = {\n /**\n * Whether touch is enabled in the browser.\n */\n TOUCH_ENABLED:\n ('ontouchstart' in goog.global ||\n !!(goog.global['document'] && document.documentElement &&\n 'ontouchstart' in document.documentElement) ||\n // IE10 uses non-standard touch events, so it has a different check.\n !!(goog.global['navigator'] &&\n (goog.global['navigator']['maxTouchPoints'] ||\n goog.global['navigator']['msMaxTouchPoints']))),\n\n /**\n * Whether addEventListener supports W3C standard pointer events.\n * http://www.w3.org/TR/pointerevents/\n */\n POINTER_EVENTS: ('PointerEvent' in goog.global),\n\n /**\n * Whether addEventListener supports MSPointer events (only used in IE10).\n * http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n * http://msdn.microsoft.com/library/hh673557(v=vs.85).aspx\n */\n MSPOINTER_EVENTS:\n ('MSPointerEvent' in goog.global &&\n !!(goog.global['navigator'] &&\n goog.global['navigator']['msPointerEnabled'])),\n\n /**\n * Whether addEventListener supports {passive: true}.\n * https://developers.google.com/web/updates/2016/06/passive-event-listeners\n */\n PASSIVE_EVENTS: purify(function() {\n // If we're in a web worker or other custom environment, we can't tell.\n if (!goog.global.addEventListener || !Object.defineProperty) { // IE 8\n return false;\n }\n\n var passive = false;\n var options = Object.defineProperty({}, 'passive', {\n get: function() {\n passive = true;\n }\n });\n try {\n goog.global.addEventListener('test', goog.nullFunction, options);\n goog.global.removeEventListener('test', goog.nullFunction, options);\n } catch (e) {\n }\n\n return passive;\n })\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview String functions called from Closure packages that couldn't\n * depend on each other. Outside Closure, use goog.string function which\n * delegate to these.\n */\n\n\ngoog.provide('goog.string.internal');\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n * @see goog.string.startsWith\n */\ngoog.string.internal.startsWith = function(str, prefix) {\n 'use strict';\n return str.lastIndexOf(prefix, 0) == 0;\n};\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n * @see goog.string.endsWith\n */\ngoog.string.internal.endsWith = function(str, suffix) {\n 'use strict';\n const l = str.length - suffix.length;\n return l >= 0 && str.indexOf(suffix, l) == l;\n};\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveStartsWith\n */\ngoog.string.internal.caseInsensitiveStartsWith = function(str, prefix) {\n 'use strict';\n return goog.string.internal.caseInsensitiveCompare(\n prefix, str.substr(0, prefix.length)) == 0;\n};\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n * @see goog.string.caseInsensitiveEndsWith\n */\ngoog.string.internal.caseInsensitiveEndsWith = function(str, suffix) {\n 'use strict';\n return (\n goog.string.internal.caseInsensitiveCompare(\n suffix, str.substr(str.length - suffix.length, suffix.length)) == 0);\n};\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n * @see goog.string.caseInsensitiveEquals\n */\ngoog.string.internal.caseInsensitiveEquals = function(str1, str2) {\n 'use strict';\n return str1.toLowerCase() == str2.toLowerCase();\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @see goog.string.isEmptyOrWhitespace\n */\ngoog.string.internal.isEmptyOrWhitespace = function(str) {\n 'use strict';\n // testing length == 0 first is actually slower in all browsers (about the\n // same in Opera).\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return /^[\\s\\xa0]*$/.test(str);\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.internal.trim =\n (goog.TRUSTED_SITE && String.prototype.trim) ? function(str) {\n 'use strict';\n return str.trim();\n } : function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s\n // character class (as required by section 7.2 of the ECMAScript spec),\n // we explicitly include it in the regexp to enforce consistent\n // cross-browser behavior.\n // NOTE: We don't use String#replace because it might have side effects\n // causing this function to not compile to 0 bytes.\n return /^[\\s\\xa0]*([\\s\\S]*?)[\\s\\xa0]*$/.exec(str)[1];\n };\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n * @see goog.string.caseInsensitiveCompare\n */\ngoog.string.internal.caseInsensitiveCompare = function(str1, str2) {\n 'use strict';\n const test1 = String(str1).toLowerCase();\n const test2 = String(str2).toLowerCase();\n\n if (test1 < test2) {\n return -1;\n } else if (test1 == test2) {\n return 0;\n } else {\n return 1;\n }\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n * @see goog.string.newLineToBr\n */\ngoog.string.internal.newLineToBr = function(str, opt_xml) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)/g, opt_xml ? '<br />' : '<br>');\n};\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars\n * @return {string} An escaped copy of `str`.\n * @see goog.string.htmlEscape\n */\ngoog.string.internal.htmlEscape = function(\n str, opt_isLikelyToContainHtmlChars) {\n 'use strict';\n if (opt_isLikelyToContainHtmlChars) {\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;')\n .replace(goog.string.internal.LT_RE_, '&lt;')\n .replace(goog.string.internal.GT_RE_, '&gt;')\n .replace(goog.string.internal.QUOT_RE_, '&quot;')\n .replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;')\n .replace(goog.string.internal.NULL_RE_, '&#0;');\n return str;\n\n } else {\n // quick test helps in the case when there are no chars to replace, in\n // worst case this makes barely a difference to the time taken\n if (!goog.string.internal.ALL_RE_.test(str)) return str;\n\n // str.indexOf is faster than regex.test in this case\n if (str.indexOf('&') != -1) {\n str = str.replace(goog.string.internal.AMP_RE_, '&amp;');\n }\n if (str.indexOf('<') != -1) {\n str = str.replace(goog.string.internal.LT_RE_, '&lt;');\n }\n if (str.indexOf('>') != -1) {\n str = str.replace(goog.string.internal.GT_RE_, '&gt;');\n }\n if (str.indexOf('\"') != -1) {\n str = str.replace(goog.string.internal.QUOT_RE_, '&quot;');\n }\n if (str.indexOf('\\'') != -1) {\n str = str.replace(goog.string.internal.SINGLE_QUOTE_RE_, '&#39;');\n }\n if (str.indexOf('\\x00') != -1) {\n str = str.replace(goog.string.internal.NULL_RE_, '&#0;');\n }\n return str;\n }\n};\n\n\n/**\n * Regular expression that matches an ampersand, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.AMP_RE_ = /&/g;\n\n\n/**\n * Regular expression that matches a less than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.LT_RE_ = /</g;\n\n\n/**\n * Regular expression that matches a greater than sign, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.GT_RE_ = />/g;\n\n\n/**\n * Regular expression that matches a double quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.QUOT_RE_ = /\"/g;\n\n\n/**\n * Regular expression that matches a single quote, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.SINGLE_QUOTE_RE_ = /'/g;\n\n\n/**\n * Regular expression that matches null character, for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.NULL_RE_ = /\\x00/g;\n\n\n/**\n * Regular expression that matches any character that needs to be escaped.\n * @const {!RegExp}\n * @private\n */\ngoog.string.internal.ALL_RE_ = /[\\x00&<>\"']/;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n * @see goog.string.whitespaceEscape\n */\ngoog.string.internal.whitespaceEscape = function(str, opt_xml) {\n 'use strict';\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.internal.newLineToBr(\n str.replace(/ /g, ' &#160;'), opt_xml);\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.contains\n */\ngoog.string.internal.contains = function(str, subString) {\n 'use strict';\n return str.indexOf(subString) != -1;\n};\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n * @see goog.string.caseInsensitiveContains\n */\ngoog.string.internal.caseInsensitiveContains = function(str, subString) {\n 'use strict';\n return goog.string.internal.contains(\n str.toLowerCase(), subString.toLowerCase());\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n * @see goog.string.compareVersions\n */\ngoog.string.internal.compareVersions = function(version1, version2) {\n 'use strict';\n let order = 0;\n // Trim leading and trailing whitespace and split the versions into\n // subversions.\n const v1Subs = goog.string.internal.trim(String(version1)).split('.');\n const v2Subs = goog.string.internal.trim(String(version2)).split('.');\n const subCount = Math.max(v1Subs.length, v2Subs.length);\n\n // Iterate over the subversions, as long as they appear to be equivalent.\n for (let subIdx = 0; order == 0 && subIdx < subCount; subIdx++) {\n let v1Sub = v1Subs[subIdx] || '';\n let v2Sub = v2Subs[subIdx] || '';\n\n do {\n // Split the subversions into pairs of numbers and qualifiers (like 'b').\n // Two different RegExp objects are use to make it clear the code\n // is side-effect free\n const v1Comp = /(\\d*)(\\D*)(.*)/.exec(v1Sub) || ['', '', '', ''];\n const v2Comp = /(\\d*)(\\D*)(.*)/.exec(v2Sub) || ['', '', '', ''];\n // Break if there are no more matches.\n if (v1Comp[0].length == 0 && v2Comp[0].length == 0) {\n break;\n }\n\n // Parse the numeric part of the subversion. A missing number is\n // equivalent to 0.\n const v1CompNum = v1Comp[1].length == 0 ? 0 : parseInt(v1Comp[1], 10);\n const v2CompNum = v2Comp[1].length == 0 ? 0 : parseInt(v2Comp[1], 10);\n\n // Compare the subversion components. The number has the highest\n // precedence. Next, if the numbers are equal, a subversion without any\n // qualifier is always higher than a subversion with any qualifier. Next,\n // the qualifiers are compared as strings.\n order = goog.string.internal.compareElements_(v1CompNum, v2CompNum) ||\n goog.string.internal.compareElements_(\n v1Comp[2].length == 0, v2Comp[2].length == 0) ||\n goog.string.internal.compareElements_(v1Comp[2], v2Comp[2]);\n // Stop as soon as an inequality is discovered.\n\n v1Sub = v1Comp[3];\n v2Sub = v2Comp[3];\n } while (order == 0);\n }\n\n return order;\n};\n\n\n/**\n * Compares elements of a version number.\n *\n * @param {string|number|boolean} left An element from a version number.\n * @param {string|number|boolean} right An element from a version number.\n *\n * @return {number} 1 if `left` is higher.\n * 0 if arguments are equal.\n * -1 if `right` is higher.\n * @private\n */\ngoog.string.internal.compareElements_ = function(left, right) {\n 'use strict';\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n }\n return 0;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities used by goog.labs.userAgent tools. These functions\n * should not be used outside of goog.labs.userAgent.*.\n *\n */\n\ngoog.module('goog.labs.userAgent.util');\ngoog.module.declareLegacyNamespace();\n\nconst {USE_CLIENT_HINTS} = goog.require('goog.labs.userAgent');\nconst {caseInsensitiveContains, contains} = goog.require('goog.string.internal');\n\n/**\n * @const {boolean} If true, use navigator.userAgentData without check.\n * TODO(user): FEATURESET_YEAR >= 2023 if it supports mobile and all the\n * brands we need. See https://caniuse.com/mdn-api_navigator_useragentdata.\n */\nconst ASSUME_CLIENT_HINTS_SUPPORT = false;\n\n/**\n * Gets the native userAgent string from navigator if it exists.\n * If navigator or navigator.userAgent string is missing, returns an empty\n * string.\n * @return {string}\n */\nfunction getNativeUserAgentString() {\n const navigator = getNavigator();\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n}\n\n/**\n * Gets the native userAgentData object from navigator if it exists.\n * If navigator.userAgentData object is missing or USE_CLIENT_HINTS is set to\n * false, returns null.\n * @return {?NavigatorUAData}\n */\nfunction getNativeUserAgentData() {\n if (!USE_CLIENT_HINTS) {\n return null;\n }\n const navigator = getNavigator();\n // TODO(user): Use navigator?.userAgent ?? null once it's supported.\n if (navigator) {\n return navigator.userAgentData || null;\n }\n return null;\n}\n\n/**\n * Getter for the native navigator.\n * @return {!Navigator}\n */\nfunction getNavigator() {\n return goog.global.navigator;\n}\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgent but use a specified value for detection instead.\n * @type {?string}\n */\nlet userAgentInternal = null;\n\n/**\n * A possible override for applications which wish to not check\n * navigator.userAgentData but use a specified value for detection instead.\n * @type {?NavigatorUAData}\n */\nlet userAgentDataInternal = getNativeUserAgentData();\n\n/**\n * Override the user agent string with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to use the native browser object instead.\n * @param {?string=} userAgent The userAgent override.\n * @return {void}\n */\nfunction setUserAgent(userAgent = undefined) {\n userAgentInternal =\n typeof userAgent === 'string' ? userAgent : getNativeUserAgentString();\n}\n\n/** @return {string} The user agent string. */\nfunction getUserAgent() {\n return userAgentInternal == null ? getNativeUserAgentString() :\n userAgentInternal;\n}\n\n/**\n * Override the user agent data object with the given value.\n * This should only be used for testing within the goog.labs.userAgent\n * namespace.\n * Pass `null` to specify the absence of userAgentData. Note that this behavior\n * is different from setUserAgent.\n * @param {?NavigatorUAData} userAgentData The userAgentData override.\n */\nfunction setUserAgentData(userAgentData) {\n userAgentDataInternal = userAgentData;\n}\n\n/**\n * If the user agent data object was overridden using setUserAgentData,\n * reset it so that it uses the native browser object instead, if it exists.\n */\nfunction resetUserAgentData() {\n userAgentDataInternal = getNativeUserAgentData();\n}\n\n/** @return {?NavigatorUAData} Navigator.userAgentData if exist */\nfunction getUserAgentData() {\n return userAgentDataInternal;\n}\n\n/**\n * Checks if any string in userAgentData.brands matches str.\n * Returns false if userAgentData is not supported.\n * @param {string} str\n * @return {boolean} Whether any brand string from userAgentData contains the\n * given string.\n */\nfunction matchUserAgentDataBrand(str) {\n const data = getUserAgentData();\n if (!data) return false;\n return data.brands.some(({brand}) => brand && contains(brand, str));\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string.\n */\nfunction matchUserAgent(str) {\n const userAgent = getUserAgent();\n return contains(userAgent, str);\n}\n\n/**\n * @param {string} str\n * @return {boolean} Whether the user agent contains the given string, ignoring\n * case.\n */\nfunction matchUserAgentIgnoreCase(str) {\n const userAgent = getUserAgent();\n return caseInsensitiveContains(userAgent, str);\n}\n\n/**\n * Parses the user agent into tuples for each section.\n * @param {string} userAgent\n * @return {!Array<!Array<string>>} Tuples of key, version, and the contents of\n * the parenthetical.\n */\nfunction extractVersionTuples(userAgent) {\n // Matches each section of a user agent string.\n // Example UA:\n // Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us)\n // AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405\n // This has three version tuples: Mozilla, AppleWebKit, and Mobile.\n\n const versionRegExp = new RegExp(\n // Key. Note that a key may have a space.\n // (i.e. 'Mobile Safari' in 'Mobile Safari/5.0')\n '([A-Z][\\\\w ]+)' +\n\n '/' + // slash\n '([^\\\\s]+)' + // version (i.e. '5.0b')\n '\\\\s*' + // whitespace\n '(?:\\\\((.*?)\\\\))?', // parenthetical info. parentheses not matched.\n 'g');\n\n const data = [];\n let match;\n\n // Iterate and collect the version tuples. Each iteration will be the\n // next regex match.\n while (match = versionRegExp.exec(userAgent)) {\n data.push([\n match[1], // key\n match[2], // value\n // || undefined as this is not undefined in IE7 and IE8\n match[3] || undefined // info\n ]);\n }\n\n return data;\n}\n\nexports = {\n ASSUME_CLIENT_HINTS_SUPPORT,\n extractVersionTuples,\n getNativeUserAgentString,\n getUserAgent,\n getUserAgentData,\n matchUserAgent,\n matchUserAgentDataBrand,\n matchUserAgentIgnoreCase,\n resetUserAgentData,\n setUserAgent,\n setUserAgentData,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Useful compiler idioms.\n */\n\ngoog.provide('goog.reflect');\n\n\n/**\n * Syntax for object literal casts.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an object literal whose keys need to have the same names\n * as the properties of some class even after they are renamed by the compiler.\n *\n * @param {!Function} type Type to cast to.\n * @param {Object} object Object literal to cast.\n * @return {Object} The object literal.\n */\ngoog.reflect.object = function(type, object) {\n 'use strict';\n return object;\n};\n\n/**\n * Syntax for renaming property strings.\n * @see http://go/jscompiler-renaming\n * @see https://goo.gl/CRs09P\n *\n * Use this if you have an need to access a property as a string, but want\n * to also have the property renamed by the compiler. In contrast to\n * goog.reflect.object, this method takes an instance of an object.\n *\n * Properties must be simple names (not qualified names).\n *\n * @param {string} prop Name of the property\n * @param {!Object} object Instance of the object whose type will be used\n * for renaming\n * @return {string} The renamed property.\n */\ngoog.reflect.objectProperty = function(prop, object) {\n 'use strict';\n return prop;\n};\n\n/**\n * To assert to the compiler that an operation is needed when it would\n * otherwise be stripped. For example:\n * <code>\n * // Force a layout\n * goog.reflect.sinkValue(dialog.offsetHeight);\n * </code>\n * @param {T} x\n * @return {T}\n * @template T\n */\ngoog.reflect.sinkValue = function(x) {\n 'use strict';\n goog.reflect.sinkValue[' '](x);\n return x;\n};\n\n\n/**\n * The compiler should optimize this function away iff no one ever uses\n * goog.reflect.sinkValue.\n */\ngoog.reflect.sinkValue[' '] = goog.nullFunction;\n\n\n/**\n * Check if a property can be accessed without throwing an exception.\n * @param {Object} obj The owner of the property.\n * @param {string} prop The property name.\n * @return {boolean} Whether the property is accessible. Will also return true\n * if obj is null.\n */\ngoog.reflect.canAccessProperty = function(obj, prop) {\n 'use strict';\n try {\n goog.reflect.sinkValue(obj[prop]);\n return true;\n } catch (e) {\n }\n return false;\n};\n\n\n/**\n * Retrieves a value from a cache given a key. The compiler provides special\n * consideration for this call such that it is generally considered side-effect\n * free. However, if the `opt_keyFn` or `valueFn` have side-effects\n * then the entire call is considered to have side-effects.\n *\n * Conventionally storing the value on the cache would be considered a\n * side-effect and preclude unused calls from being pruned, ie. even if\n * the value was never used, it would still always be stored in the cache.\n *\n * Providing a side-effect free `valueFn` and `opt_keyFn`\n * allows unused calls to `goog.reflect.cache` to be pruned.\n *\n * @param {!Object<K, V>} cacheObj The object that contains the cached values.\n * @param {?} key The key to lookup in the cache. If it is not string or number\n * then a `opt_keyFn` should be provided. The key is also used as the\n * parameter to the `valueFn`.\n * @param {function(?):V} valueFn The value provider to use to calculate the\n * value to store in the cache. This function should be side-effect free\n * to take advantage of the optimization.\n * @param {function(?):K=} opt_keyFn The key provider to determine the cache\n * map key. This should be used if the given key is not a string or number.\n * If not provided then the given key is used. This function should be\n * side-effect free to take advantage of the optimization.\n * @return {V} The cached or calculated value.\n * @template K\n * @template V\n */\ngoog.reflect.cache = function(cacheObj, key, valueFn, opt_keyFn) {\n 'use strict';\n const storedKey = opt_keyFn ? opt_keyFn(key) : key;\n\n if (Object.prototype.hasOwnProperty.call(cacheObj, storedKey)) {\n return cacheObj[storedKey];\n }\n\n return (cacheObj[storedKey] = valueFn(key));\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Rendering engine detection.\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For information on the browser brand (such as Safari versus Chrome), see\n * goog.userAgent.product.\n * @see ../demos/useragent.html\n */\n\ngoog.provide('goog.userAgent');\n\ngoog.require('goog.labs.userAgent.browser');\ngoog.require('goog.labs.userAgent.engine');\ngoog.require('goog.labs.userAgent.platform');\ngoog.require('goog.labs.userAgent.util');\ngoog.require('goog.reflect');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is IE.\n */\ngoog.userAgent.ASSUME_IE = goog.define('goog.userAgent.ASSUME_IE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is EDGE,\n * referring to EdgeHTML based Edge.\n */\ngoog.userAgent.ASSUME_EDGE = goog.define('goog.userAgent.ASSUME_EDGE', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is GECKO.\n */\ngoog.userAgent.ASSUME_GECKO = goog.define('goog.userAgent.ASSUME_GECKO', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is WEBKIT.\n */\ngoog.userAgent.ASSUME_WEBKIT =\n goog.define('goog.userAgent.ASSUME_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is a\n * mobile device running WebKit e.g. iPhone or Android.\n */\ngoog.userAgent.ASSUME_MOBILE_WEBKIT =\n goog.define('goog.userAgent.ASSUME_MOBILE_WEBKIT', false);\n\n\n/**\n * @define {boolean} Whether we know at compile-time that the browser is OPERA,\n * referring to Presto-based Opera.\n */\ngoog.userAgent.ASSUME_OPERA = goog.define('goog.userAgent.ASSUME_OPERA', false);\n\n\n/**\n * @define {boolean} Whether the\n * `goog.userAgent.isVersionOrHigher`\n * function will return true for any version.\n */\ngoog.userAgent.ASSUME_ANY_VERSION =\n goog.define('goog.userAgent.ASSUME_ANY_VERSION', false);\n\n\n/**\n * Whether we know the browser engine at compile-time.\n * @type {boolean}\n * @private\n */\ngoog.userAgent.BROWSER_KNOWN_ = goog.userAgent.ASSUME_IE ||\n goog.userAgent.ASSUME_EDGE || goog.userAgent.ASSUME_GECKO ||\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.ASSUME_WEBKIT ||\n goog.userAgent.ASSUME_OPERA;\n\n\n/**\n * Returns the userAgent string for the current browser.\n *\n * @return {string} The userAgent string.\n */\ngoog.userAgent.getUserAgentString = function() {\n 'use strict';\n return goog.labs.userAgent.util.getUserAgent();\n};\n\n\n/**\n * @return {?Navigator} The native navigator object.\n */\ngoog.userAgent.getNavigatorTyped = function() {\n 'use strict';\n // Need a local navigator reference instead of using the global one,\n // to avoid the rare case where they reference different objects.\n // (in a WorkerPool, for example).\n return goog.global['navigator'] || null;\n};\n\n\n/**\n * TODO(nnaze): Change type to \"Navigator\" and update compilation targets.\n * @return {?Object} The native navigator object.\n */\ngoog.userAgent.getNavigator = function() {\n 'use strict';\n return goog.userAgent.getNavigatorTyped();\n};\n\n\n/**\n * Whether the user agent is Presto-based Opera.\n * @type {boolean}\n */\ngoog.userAgent.OPERA = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_OPERA :\n goog.labs.userAgent.browser.isOpera();\n\n\n/**\n * Whether the user agent is Internet Explorer.\n * @type {boolean}\n */\ngoog.userAgent.IE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_IE :\n goog.labs.userAgent.browser.isIE();\n\n\n/**\n * Whether the user agent is Microsoft Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_EDGE :\n goog.labs.userAgent.engine.isEdge();\n\n\n/**\n * Whether the user agent is MS Internet Explorer or MS Edge (EdgeHTML based).\n * @type {boolean}\n */\ngoog.userAgent.EDGE_OR_IE = goog.userAgent.EDGE || goog.userAgent.IE;\n\n\n/**\n * Whether the user agent is Gecko. Gecko is the rendering engine used by\n * Mozilla, Firefox, and others.\n * @type {boolean}\n */\ngoog.userAgent.GECKO = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_GECKO :\n goog.labs.userAgent.engine.isGecko();\n\n\n/**\n * Whether the user agent is WebKit. WebKit is the rendering engine that\n * Safari, Edge Chromium, Opera Chromium, Android and others use.\n * @type {boolean}\n */\ngoog.userAgent.WEBKIT = goog.userAgent.BROWSER_KNOWN_ ?\n goog.userAgent.ASSUME_WEBKIT || goog.userAgent.ASSUME_MOBILE_WEBKIT :\n goog.labs.userAgent.engine.isWebKit();\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * This is a separate function so that the logic can be tested.\n *\n * TODO(nnaze): Investigate swapping in goog.labs.userAgent.device.isMobile().\n *\n * @return {boolean} Whether the user agent is running on a mobile device.\n * @private\n */\ngoog.userAgent.isMobile_ = function() {\n 'use strict';\n return goog.userAgent.WEBKIT &&\n goog.labs.userAgent.util.matchUserAgent('Mobile');\n};\n\n\n/**\n * Whether the user agent is running on a mobile device.\n *\n * TODO(nnaze): Consider deprecating MOBILE when labs.userAgent\n * is promoted as the gecko/webkit logic is likely inaccurate.\n *\n * @type {boolean}\n */\ngoog.userAgent.MOBILE =\n goog.userAgent.ASSUME_MOBILE_WEBKIT || goog.userAgent.isMobile_();\n\n\n/**\n * Used while transitioning code to use WEBKIT instead.\n * @type {boolean}\n * @deprecated Use {@link goog.userAgent.product.SAFARI} instead.\n * TODO(nicksantos): Delete this from goog.userAgent.\n */\ngoog.userAgent.SAFARI = goog.userAgent.WEBKIT;\n\n\n/**\n * @return {string} the platform (operating system) the user agent is running\n * on. Default to empty string because navigator.platform may not be defined\n * (on Rhino, for example).\n * @private\n */\ngoog.userAgent.determinePlatform_ = function() {\n 'use strict';\n var navigator = goog.userAgent.getNavigatorTyped();\n return navigator && navigator.platform || '';\n};\n\n\n/**\n * The platform (operating system) the user agent is running on. Default to\n * empty string because navigator.platform may not be defined (on Rhino, for\n * example).\n * @type {string}\n */\ngoog.userAgent.PLATFORM = goog.userAgent.determinePlatform_();\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Macintosh operating\n * system.\n */\ngoog.userAgent.ASSUME_MAC = goog.define('goog.userAgent.ASSUME_MAC', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Windows operating\n * system.\n */\ngoog.userAgent.ASSUME_WINDOWS =\n goog.define('goog.userAgent.ASSUME_WINDOWS', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a Linux operating\n * system.\n */\ngoog.userAgent.ASSUME_LINUX = goog.define('goog.userAgent.ASSUME_LINUX', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on a X11 windowing\n * system.\n */\ngoog.userAgent.ASSUME_X11 = goog.define('goog.userAgent.ASSUME_X11', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on Android.\n */\ngoog.userAgent.ASSUME_ANDROID =\n goog.define('goog.userAgent.ASSUME_ANDROID', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPhone.\n */\ngoog.userAgent.ASSUME_IPHONE =\n goog.define('goog.userAgent.ASSUME_IPHONE', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPad.\n */\ngoog.userAgent.ASSUME_IPAD = goog.define('goog.userAgent.ASSUME_IPAD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on an iPod.\n */\ngoog.userAgent.ASSUME_IPOD = goog.define('goog.userAgent.ASSUME_IPOD', false);\n\n\n/**\n * @define {boolean} Whether the user agent is running on KaiOS.\n */\ngoog.userAgent.ASSUME_KAIOS = goog.define('goog.userAgent.ASSUME_KAIOS', false);\n\n\n/**\n * @type {boolean}\n * @private\n */\ngoog.userAgent.PLATFORM_KNOWN_ = goog.userAgent.ASSUME_MAC ||\n goog.userAgent.ASSUME_WINDOWS || goog.userAgent.ASSUME_LINUX ||\n goog.userAgent.ASSUME_X11 || goog.userAgent.ASSUME_ANDROID ||\n goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD;\n\n\n/**\n * Whether the user agent is running on a Macintosh operating system.\n * @type {boolean}\n */\ngoog.userAgent.MAC = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_MAC :\n goog.labs.userAgent.platform.isMacintosh();\n\n\n/**\n * Whether the user agent is running on a Windows operating system.\n * @type {boolean}\n */\ngoog.userAgent.WINDOWS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_WINDOWS :\n goog.labs.userAgent.platform.isWindows();\n\n\n/**\n * Whether the user agent is Linux per the legacy behavior of\n * goog.userAgent.LINUX, which considered ChromeOS to also be\n * Linux.\n * @return {boolean}\n * @private\n */\ngoog.userAgent.isLegacyLinux_ = function() {\n 'use strict';\n return goog.labs.userAgent.platform.isLinux() ||\n goog.labs.userAgent.platform.isChromeOS();\n};\n\n\n/**\n * Whether the user agent is running on a Linux operating system.\n *\n * Note that goog.userAgent.LINUX considers ChromeOS to be Linux,\n * while goog.labs.userAgent.platform considers ChromeOS and\n * Linux to be different OSes.\n *\n * @type {boolean}\n */\ngoog.userAgent.LINUX = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_LINUX :\n goog.userAgent.isLegacyLinux_();\n\n\n/**\n * @return {boolean} Whether the user agent is an X11 windowing system.\n * @private\n */\ngoog.userAgent.isX11_ = function() {\n 'use strict';\n var navigator = goog.userAgent.getNavigatorTyped();\n return !!navigator &&\n goog.string.internal.contains(navigator['appVersion'] || '', 'X11');\n};\n\n\n/**\n * Whether the user agent is running on a X11 windowing system.\n * @type {boolean}\n */\ngoog.userAgent.X11 = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_X11 :\n goog.userAgent.isX11_();\n\n\n/**\n * Whether the user agent is running on Android.\n * @type {boolean}\n */\ngoog.userAgent.ANDROID = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_ANDROID :\n goog.labs.userAgent.platform.isAndroid();\n\n\n/**\n * Whether the user agent is running on an iPhone.\n * @type {boolean}\n */\ngoog.userAgent.IPHONE = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPHONE :\n goog.labs.userAgent.platform.isIphone();\n\n\n/**\n * Whether the user agent is running on an iPad.\n * @type {boolean}\n */\ngoog.userAgent.IPAD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPAD :\n goog.labs.userAgent.platform.isIpad();\n\n\n/**\n * Whether the user agent is running on an iPod.\n * @type {boolean}\n */\ngoog.userAgent.IPOD = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_IPOD :\n goog.labs.userAgent.platform.isIpod();\n\n\n/**\n * Whether the user agent is running on iOS.\n * @type {boolean}\n */\ngoog.userAgent.IOS = goog.userAgent.PLATFORM_KNOWN_ ?\n (goog.userAgent.ASSUME_IPHONE || goog.userAgent.ASSUME_IPAD ||\n goog.userAgent.ASSUME_IPOD) :\n goog.labs.userAgent.platform.isIos();\n\n/**\n * Whether the user agent is running on KaiOS.\n * @type {boolean}\n */\ngoog.userAgent.KAIOS = goog.userAgent.PLATFORM_KNOWN_ ?\n goog.userAgent.ASSUME_KAIOS :\n goog.labs.userAgent.platform.isKaiOS();\n\n\n/**\n * @return {string} The string that describes the version number of the user\n * agent.\n * @private\n */\ngoog.userAgent.determineVersion_ = function() {\n 'use strict';\n // All browsers have different ways to detect the version and they all have\n // different naming schemes.\n // version is a string rather than a number because it may contain 'b', 'a',\n // and so on.\n var version = '';\n var arr = goog.userAgent.getVersionRegexResult_();\n if (arr) {\n version = arr ? arr[1] : '';\n }\n\n if (goog.userAgent.IE) {\n // IE9 can be in document mode 9 but be reporting an inconsistent user agent\n // version. If it is identifying as a version lower than 9 we take the\n // documentMode as the version instead. IE8 has similar behavior.\n // It is recommended to set the X-UA-Compatible header to ensure that IE9\n // uses documentMode 9.\n var docMode = goog.userAgent.getDocumentMode_();\n if (docMode != null && docMode > parseFloat(version)) {\n return String(docMode);\n }\n }\n\n return version;\n};\n\n\n/**\n * @return {?IArrayLike<string>|undefined} The version regex matches from\n * parsing the user\n * agent string. These regex statements must be executed inline so they can\n * be compiled out by the closure compiler with the rest of the useragent\n * detection logic when ASSUME_* is specified.\n * @private\n */\ngoog.userAgent.getVersionRegexResult_ = function() {\n 'use strict';\n var userAgent = goog.userAgent.getUserAgentString();\n if (goog.userAgent.GECKO) {\n return /rv\\:([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.EDGE) {\n return /Edge\\/([\\d\\.]+)/.exec(userAgent);\n }\n if (goog.userAgent.IE) {\n return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(userAgent);\n }\n if (goog.userAgent.WEBKIT) {\n // WebKit/125.4\n return /WebKit\\/(\\S+)/.exec(userAgent);\n }\n if (goog.userAgent.OPERA) {\n // If none of the above browsers were detected but the browser is Opera, the\n // only string that is of interest is 'Version/<number>'.\n return /(?:Version)[ \\/]?(\\S+)/.exec(userAgent);\n }\n return undefined;\n};\n\n\n/**\n * @return {number|undefined} Returns the document mode (for testing).\n * @private\n */\ngoog.userAgent.getDocumentMode_ = function() {\n 'use strict';\n // NOTE(user): goog.userAgent may be used in context where there is no DOM.\n var doc = goog.global['document'];\n return doc ? doc['documentMode'] : undefined;\n};\n\n\n/**\n * The version of the user agent. This is a string because it might contain\n * 'b' (as in beta) as well as multiple dots.\n * @type {string}\n */\ngoog.userAgent.VERSION = goog.userAgent.determineVersion_();\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string} v1 Version of first item.\n * @param {string} v2 Version of second item.\n *\n * @return {number} 1 if first argument is higher\n * 0 if arguments are equal\n * -1 if second argument is higher.\n * @deprecated Use goog.string.compareVersions.\n */\ngoog.userAgent.compare = function(v1, v2) {\n 'use strict';\n return goog.string.internal.compareVersions(v1, v2);\n};\n\n\n/**\n * Cache for {@link goog.userAgent.isVersionOrHigher}.\n * Calls to compareVersions are surprisingly expensive and, as a browser's\n * version number is unlikely to change during a session, we cache the results.\n * @const\n * @private\n */\ngoog.userAgent.isVersionOrHigherCache_ = {};\n\n\n/**\n * Whether the user agent version is higher or the same as the given version.\n * NOTE: When checking the version numbers for Firefox and Safari, be sure to\n * use the engine's version, not the browser's version number. For example,\n * Firefox 3.0 corresponds to Gecko 1.9 and Safari 3.0 to Webkit 522.11.\n * Opera and Internet Explorer versions match the product release number.<br>\n * @see <a href=\"http://en.wikipedia.org/wiki/Safari_version_history\">\n * Webkit</a>\n * @see <a href=\"http://en.wikipedia.org/wiki/Gecko_engine\">Gecko</a>\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the user agent version is higher or the same as\n * the given version.\n */\ngoog.userAgent.isVersionOrHigher = function(version) {\n 'use strict';\n return goog.userAgent.ASSUME_ANY_VERSION ||\n goog.reflect.cache(\n goog.userAgent.isVersionOrHigherCache_, version, function() {\n 'use strict';\n return goog.string.internal.compareVersions(\n goog.userAgent.VERSION, version) >= 0;\n });\n};\n\n\n/**\n * Whether the IE effective document mode is higher or the same as the given\n * document mode version.\n * NOTE: Only for IE, return false for another browser.\n *\n * @param {number} documentMode The document mode version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n */\ngoog.userAgent.isDocumentModeOrHigher = function(documentMode) {\n 'use strict';\n return Number(goog.userAgent.DOCUMENT_MODE) >= documentMode;\n};\n\n\n/**\n * Deprecated alias to `goog.userAgent.isDocumentModeOrHigher`.\n * @param {number} version The version to check.\n * @return {boolean} Whether the IE effective document mode is higher or the\n * same as the given version.\n * @deprecated Use goog.userAgent.isDocumentModeOrHigher().\n */\ngoog.userAgent.isDocumentMode = goog.userAgent.isDocumentModeOrHigher;\n\n\n/**\n * For IE version < 7, documentMode is undefined, so attempt to use the\n * CSS1Compat property to see if we are in standards mode. If we are in\n * standards mode, treat the browser version as the document mode. Otherwise,\n * IE is emulating version 5.\n *\n * NOTE(user): Support for IE < 7 is long gone, so this is now simplified.\n * It returns document.documentMode for IE and undefined for everything else.\n *\n * @type {number|undefined}\n * @const\n */\ngoog.userAgent.DOCUMENT_MODE = (function() {\n 'use strict';\n var doc = goog.global['document'];\n if (!doc || !goog.userAgent.IE) return undefined;\n // This must be an IE user agent.\n var documentMode = goog.userAgent.getDocumentMode_();\n if (documentMode) return documentMode;\n // The user agent version string begins with the major version.\n // Parse the major version and truncate anything following.\n var ieVersion = parseInt(goog.userAgent.VERSION, 10);\n return ieVersion || undefined;\n})();\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection (Browser).\n * @see <a href=\"http://www.useragentstring.com/\">User agent strings</a>\n * For more information on rendering engine, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent, goog.labs.userAgent.platform,\n * goog.labs.userAgent.device respectively.)\n */\n\ngoog.module('goog.labs.userAgent.browser');\ngoog.module.declareLegacyNamespace();\n\nconst googAsserts = goog.require('goog.asserts');\nconst util = goog.require('goog.labs.userAgent.util');\nconst {AsyncValue, Version} = goog.require('goog.labs.userAgent.highEntropy.highEntropyValue');\nconst {compareVersions} = goog.require('goog.string.internal');\nconst {fullVersionList, hasFullVersionList} = goog.require('goog.labs.userAgent.highEntropy.highEntropyData');\n\n// TODO(nnaze): Refactor to remove excessive exclusion logic in matching\n// functions.\n\n/**\n * A browser brand represents an opaque string that is used for making\n * brand-specific version checks in userAgentData.\n * @enum {string}\n */\nconst Brand = {\n /**\n * The browser brand for Android Browser.\n * Do not depend on the value of this string. Because Android Browser has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n ANDROID_BROWSER: 'Android Browser',\n /**\n * The browser brand for Chromium, including Chromium-based Edge and Opera.\n */\n CHROMIUM: 'Chromium',\n /**\n * The browser brand for Edge.\n * This brand can be used to get the version of both EdgeHTML and\n * Chromium-based Edge.\n */\n EDGE: 'Microsoft Edge',\n /**\n * The browser brand for Firefox.\n * Do not depend on the value of this string. Because Firefox has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n FIREFOX: 'Firefox',\n /**\n * The browser brand for Internet Explorer.\n * Do not depend on the value of this string. Because IE will never support\n * userAgentData, the value of this string should be treated as opaque (it's\n * used internally for legacy-userAgent fallback).\n */\n IE: 'Internet Explorer',\n /**\n * The browser brand for Opera.\n * This brand can be used to get the version of both Presto- and\n * Chromium-based Opera.\n */\n OPERA: 'Opera',\n /**\n * The browser brand for Safari.\n * Do not depend on the value of this string. Because Safari has not\n * implemented userAgentData yet, the value of this string is not guaranteed\n * to stay the same in future revisions.\n */\n SAFARI: 'Safari',\n /**\n * The browser brand for Silk.\n * See\n * https://docs.aws.amazon.com/silk/latest/developerguide/what-is-silk.html\n * Do not depend on the value of this string. Because Silk does not\n * identify itself in userAgentData yet, the value of this string is not\n * guaranteed to stay the same in future revisions.\n */\n SILK: 'Silk',\n};\nexports.Brand = Brand;\n\n/**\n * @return {boolean} Whether to use navigator.userAgentData to determine\n * browser's brand.\n */\nfunction useUserAgentDataBrand() {\n if (util.ASSUME_CLIENT_HINTS_SUPPORT) return true;\n const userAgentData = util.getUserAgentData();\n return !!userAgentData && userAgentData.brands.length > 0;\n}\n\n/**\n * @return {boolean} Whether the user's browser is Opera. Note: Chromium based\n * Opera (Opera 15+) is detected as Chrome to avoid unnecessary special\n * casing.\n */\nfunction matchOpera() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Opera');\n}\n\n/** @return {boolean} Whether the user's browser is IE. */\nfunction matchIE() {\n if (useUserAgentDataBrand()) {\n // IE doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the user's browser is Edge. This refers to\n * EdgeHTML based Edge.\n */\nfunction matchEdgeHtml() {\n if (useUserAgentDataBrand()) {\n // Pre-Chromium Edge doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Edge');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nfunction matchEdgeChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.EDGE);\n }\n return util.matchUserAgent('Edg/');\n}\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nfunction matchOperaChromium() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.OPERA);\n }\n return util.matchUserAgent('OPR');\n}\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nfunction matchFirefox() {\n // Firefox doesn't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Firefox') || util.matchUserAgent('FxiOS');\n}\n\n/** @return {boolean} Whether the user's browser is Safari. */\nfunction matchSafari() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n return util.matchUserAgent('Safari') &&\n !(matchChrome() || matchCoast() || matchOpera() || matchEdgeHtml() ||\n matchEdgeChromium() || matchOperaChromium() || matchFirefox() ||\n isSilk() || util.matchUserAgent('Android'));\n}\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nfunction matchCoast() {\n if (useUserAgentDataBrand()) {\n // Coast doesn't support navigator.userAgentData.\n return false;\n }\n return util.matchUserAgent('Coast');\n}\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nfunction matchIosWebview() {\n // Apple-based browsers don't support navigator.userAgentData yet, so use\n // navigator.userAgent.\n // iOS Webview does not show up as Chrome or Safari.\n return (util.matchUserAgent('iPad') || util.matchUserAgent('iPhone')) &&\n !matchSafari() && !matchChrome() && !matchCoast() && !matchFirefox() &&\n util.matchUserAgent('AppleWebKit');\n}\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium browser. This\n * returns true for Chrome, Opera 15+, and Edge Chromium.\n */\nfunction matchChrome() {\n if (useUserAgentDataBrand()) {\n return util.matchUserAgentDataBrand(Brand.CHROMIUM);\n }\n return ((util.matchUserAgent('Chrome') || util.matchUserAgent('CriOS')) &&\n !matchEdgeHtml()) ||\n isSilk();\n}\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nfunction matchAndroidBrowser() {\n // Android can appear in the user agent string for Chrome on Android.\n // This is not the Android standalone browser if it does.\n return util.matchUserAgent('Android') &&\n !(isChrome() || isFirefox() || isOpera() || isSilk());\n}\n\n/** @return {boolean} Whether the user's browser is Opera. */\nconst isOpera = matchOpera;\nexports.isOpera = isOpera;\n\n/** @return {boolean} Whether the user's browser is IE. */\nconst isIE = matchIE;\nexports.isIE = isIE;\n\n/** @return {boolean} Whether the user's browser is EdgeHTML based Edge. */\nconst isEdge = matchEdgeHtml;\nexports.isEdge = isEdge;\n\n/** @return {boolean} Whether the user's browser is Chromium based Edge. */\nconst isEdgeChromium = matchEdgeChromium;\nexports.isEdgeChromium = isEdgeChromium;\n\n/** @return {boolean} Whether the user's browser is Chromium based Opera. */\nconst isOperaChromium = matchOperaChromium;\nexports.isOperaChromium = isOperaChromium;\n\n/** @return {boolean} Whether the user's browser is Firefox. */\nconst isFirefox = matchFirefox;\nexports.isFirefox = isFirefox;\n\n/** @return {boolean} Whether the user's browser is Safari. */\nconst isSafari = matchSafari;\nexports.isSafari = isSafari;\n\n/**\n * @return {boolean} Whether the user's browser is Coast (Opera's Webkit-based\n * iOS browser).\n */\nconst isCoast = matchCoast;\nexports.isCoast = isCoast;\n\n/** @return {boolean} Whether the user's browser is iOS Webview. */\nconst isIosWebview = matchIosWebview;\nexports.isIosWebview = isIosWebview;\n\n/**\n * @return {boolean} Whether the user's browser is any Chromium based browser (\n * Chrome, Blink-based Opera (15+) and Edge Chromium).\n */\nconst isChrome = matchChrome;\nexports.isChrome = isChrome;\n\n/** @return {boolean} Whether the user's browser is the Android browser. */\nconst isAndroidBrowser = matchAndroidBrowser;\nexports.isAndroidBrowser = isAndroidBrowser;\n\n/**\n * For more information, see:\n * http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html\n * @return {boolean} Whether the user's browser is Silk.\n */\nfunction isSilk() {\n // As of Silk 93, Silk does not identify itself in userAgentData.brands.\n // When Silk changes this behavior, update this method to call\n // matchUserAgentDataBrand (akin to isChrome, etc.)\n return util.matchUserAgent('Silk');\n}\nexports.isSilk = isSilk;\n\n/**\n * A helper function that returns a function mapping a list of candidate\n * version tuple keys to the first version string present under a key.\n * Ex:\n * <code>\n * // Arg extracted from \"Foo/1.2.3 Bar/0.2021\"\n * const mapVersion = createVersionMap([[\"Foo\", \"1.2.3\"], [\"Bar\", \"0.2021\"]]);\n * mapVersion([\"Bar\", \"Foo\"]); // returns \"0.2021\"\n * mapVersion([\"Baz\", \"Foo\"]); // returns \"1.2.3\"\n * mapVersion([\"Baz\", \"???\"]); // returns \"\"\n * </code>\n * @param {!Array<!Array<string>>} versionTuples Version tuples pre-extracted\n * from a user agent string.\n * @return {function(!Array<string>): string} The version string, or empty\n * string if it doesn't exist under the given key.\n */\nfunction createVersionMap(versionTuples) {\n // Construct a map for easy lookup.\n const versionMap = {};\n versionTuples.forEach((tuple) => {\n // Note that the tuple is of length three, but we only care about the\n // first two.\n const key = tuple[0];\n const value = tuple[1];\n versionMap[key] = value;\n });\n\n // Gives the value with the first key it finds, otherwise empty string.\n return (keys) => versionMap[keys.find((key) => key in versionMap)] || '';\n}\n\n/**\n * Returns the browser version.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and returns the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use\n * getVersionStringForLogging() or fullVersionOf() instead.\n *\n * @return {string} The browser version or empty string if version cannot be\n * determined. Note that for Internet Explorer, this returns the version of\n * the browser, not the version of the rendering engine. (IE 8 in\n * compatibility mode will return 8.0 rather than 7.0. To determine the\n * rendering engine version, look at document.documentMode instead. See\n * http://msdn.microsoft.com/en-us/library/cc196988(v=vs.85).aspx for more\n * details.)\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (isIE()) {\n return getIEVersion(userAgentString);\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n\n // Check Opera before Chrome since Opera 15+ has \"Chrome\" in the string.\n // See\n // http://my.opera.com/ODIN/blog/2013/07/15/opera-user-agent-strings-opera-15-and-beyond\n if (isOpera()) {\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\" first.\n // Opera uses 'OPR' for more recent UAs.\n return lookUpValueWithKeys(['Version', 'Opera']);\n }\n\n // Check Edge before Chrome since it has Chrome in the string.\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n }\n\n // Check Chromium Edge before Chrome since it has Chrome in the string.\n if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n\n // Check Silk before Chrome since it may have Chrome in its string and be\n // treated as Chrome.\n if (isSilk()) {\n return lookUpValueWithKeys(['Silk']);\n }\n\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n\n // Usually products browser versions are in the third tuple after \"Mozilla\"\n // and the engine.\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n}\nexports.getVersion = getVersion;\n\n/**\n * Returns whether the current browser's version is at least as high as the\n * given one.\n *\n * Note that for browsers with multiple brands, this function assumes a primary\n * brand and checks the version for that brand.\n *\n * Additionally, this function is not userAgentData-aware and will return\n * incorrect values when the User Agent string is frozen. The current status of\n * User Agent string freezing is available here:\n * https://www.chromestatus.com/feature/5704553745874944\n *\n * To mitigate both of these potential issues, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n *\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the browser version is higher or the same as the\n * given version.\n * @deprecated Use isAtLeast()/isAtMost() instead.\n */\nfunction isVersionOrHigher(version) {\n return compareVersions(getVersion(), version) >= 0;\n}\nexports.isVersionOrHigher = isVersionOrHigher;\n\n/**\n * A helper function to determine IE version. More information:\n * http://msdn.microsoft.com/en-us/library/ie/bg182625(v=vs.85).aspx#uaString\n * http://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx\n * http://blogs.msdn.com/b/ie/archive/2010/03/23/introducing-ie9-s-user-agent-string.aspx\n * http://blogs.msdn.com/b/ie/archive/2009/01/09/the-internet-explorer-8-user-agent-string-updated-edition.aspx\n * @param {string} userAgent the User-Agent.\n * @return {string}\n */\nfunction getIEVersion(userAgent) {\n // IE11 may identify itself as MSIE 9.0 or MSIE 10.0 due to an IE 11 upgrade\n // bug. Example UA:\n // Mozilla/5.0 (MSIE 9.0; Windows NT 6.1; WOW64; Trident/7.0; rv:11.0)\n // like Gecko.\n // See http://www.whatismybrowser.com/developers/unknown-user-agent-fragments.\n const rv = /rv: *([\\d\\.]*)/.exec(userAgent);\n if (rv && rv[1]) {\n return rv[1];\n }\n\n let version = '';\n const msie = /MSIE +([\\d\\.]+)/.exec(userAgent);\n if (msie && msie[1]) {\n // IE in compatibility mode usually identifies itself as MSIE 7.0; in this\n // case, use the Trident version to determine the version of IE. For more\n // details, see the links above.\n const tridentVersion = /Trident\\/(\\d.\\d)/.exec(userAgent);\n if (msie[1] == '7.0') {\n if (tridentVersion && tridentVersion[1]) {\n switch (tridentVersion[1]) {\n case '4.0':\n version = '8.0';\n break;\n case '5.0':\n version = '9.0';\n break;\n case '6.0':\n version = '10.0';\n break;\n case '7.0':\n version = '11.0';\n break;\n }\n } else {\n version = '7.0';\n }\n } else {\n version = msie[1];\n }\n }\n return version;\n}\n\n/**\n * A helper function to return the navigator.userAgent-supplied full version\n * number of the current browser or an empty string, based on whether the\n * current browser is the one specified.\n * @param {string} browser The brand whose version should be returned.\n * @return {string}\n */\nfunction getFullVersionFromUserAgentString(browser) {\n const userAgentString = util.getUserAgent();\n // Special case IE since IE's version is inside the parenthesis and\n // without the '/'.\n if (browser === Brand.IE) {\n return isIE() ? getIEVersion(userAgentString) : '';\n }\n\n const versionTuples = util.extractVersionTuples(userAgentString);\n const lookUpValueWithKeys = createVersionMap(versionTuples);\n switch (browser) {\n case Brand.OPERA:\n // Opera 10 has Version/10.0 but Opera/9.8, so look for \"Version\"\n // first. Opera uses 'OPR' for more recent UAs.\n if (isOpera()) {\n return lookUpValueWithKeys(['Version', 'Opera']);\n } else if (isOperaChromium()) {\n return lookUpValueWithKeys(['OPR']);\n }\n break;\n case Brand.EDGE:\n if (isEdge()) {\n return lookUpValueWithKeys(['Edge']);\n } else if (isEdgeChromium()) {\n return lookUpValueWithKeys(['Edg']);\n }\n break;\n case Brand.CHROMIUM:\n if (isChrome()) {\n return lookUpValueWithKeys(['Chrome', 'CriOS', 'HeadlessChrome']);\n }\n break;\n }\n\n // For the following browsers, the browser version is in the third tuple after\n // \"Mozilla\" and the engine.\n if ((browser === Brand.FIREFOX && isFirefox()) ||\n (browser === Brand.SAFARI && isSafari()) ||\n (browser === Brand.ANDROID_BROWSER && isAndroidBrowser()) ||\n (browser === Brand.SILK && isSilk())) {\n const tuple = versionTuples[2];\n return tuple && tuple[1] || '';\n }\n\n return '';\n}\n\n/**\n * Returns the major version of the given browser brand, or NaN if the current\n * browser is not the given brand.\n * Note that the major version number may be different depending on which\n * browser is specified. The returned value can be used to make browser version\n * comparisons using comparison operators.\n * @deprecated Use isAtLeast or isAtMost instead.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {number} The major version number associated with the current\n * browser under the given brand, or NaN if the current browser doesn't match\n * the given brand.\n */\nfunction versionOf(browser) {\n let versionParts;\n // Silk currently does not identify itself in its userAgentData.brands array,\n // so if checking its version, always fall back to the user agent string.\n if (useUserAgentDataBrand() && browser !== Brand.SILK) {\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n if (!matchingBrand || !matchingBrand.version) {\n return NaN;\n }\n versionParts = matchingBrand.version.split('.');\n } else {\n const fullVersion = getFullVersionFromUserAgentString(browser);\n if (fullVersion === '') {\n return NaN;\n }\n versionParts = fullVersion.split('.');\n }\n if (versionParts.length === 0) {\n return NaN;\n }\n const majorVersion = versionParts[0];\n return Number(majorVersion); // Returns NaN if it is not parseable.\n}\nexports.versionOf = versionOf;\n\n/**\n * Returns true if the current browser matches the given brand and is at least\n * the given major version. The major version must be a whole number (i.e.\n * decimals should not be used to represent a minor version).\n * @param {!Brand} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at least the given version.\n */\nfunction isAtLeast(brand, majorVersion) {\n googAsserts.assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf(brand) >= majorVersion;\n}\nexports.isAtLeast = isAtLeast;\n\n/**\n * Returns true if the current browser matches the given brand and is at most\n * the given version. The major version must be a whole number (i.e. decimals\n * should not be used to represent a minor version).\n * @param {!Brand} brand The brand whose version should be returned.\n * @param {number} majorVersion The major version number to compare against.\n * This must be a whole number.\n * @return {boolean} Whether the current browser both matches the given brand\n * and is at most the given version.\n */\nfunction isAtMost(brand, majorVersion) {\n googAsserts.assert(\n Math.floor(majorVersion) === majorVersion,\n 'Major version must be an integer');\n return versionOf(brand) <= majorVersion;\n}\nexports.isAtMost = isAtMost;\n\n/**\n * Loads the high-entropy browser brand/version data and wraps the correct\n * version string in a Version object.\n * @implements {AsyncValue<!Version>}\n */\nclass HighEntropyBrandVersion {\n /**\n * @param {string} brand The brand whose version is retrieved in this\n * container.\n */\n constructor(brand) {\n /**\n * @const {string}\n * @private\n */\n this.brand_ = brand;\n }\n\n /**\n * @return {!Version|undefined}\n * @override\n */\n getIfLoaded() {\n const loadedVersionList = fullVersionList.getIfLoaded();\n if (loadedVersionList !== undefined) {\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n googAsserts.assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n return;\n }\n\n /**\n * @return {!Promise<!Version>}\n * @override\n */\n async load() {\n const loadedVersionList = await fullVersionList.load();\n const matchingBrand =\n loadedVersionList.find(({brand}) => this.brand_ === brand);\n googAsserts.assertExists(matchingBrand);\n return new Version(matchingBrand.version);\n }\n}\n\n/**\n * Wraps a version string in a Version object.\n * @implements {AsyncValue<!Version>}\n */\nclass UserAgentStringFallbackBrandVersion {\n /**\n * @param {string} versionString\n */\n constructor(versionString) {\n /**\n * @const {!Version}\n * @private\n */\n this.version_ = new Version(versionString);\n }\n\n /**\n * @return {!Version|undefined}\n * @override\n */\n getIfLoaded() {\n return this.version_;\n }\n\n /**\n * @return {!Promise<!Version>}\n * @override\n */\n async load() {\n return this.version_;\n }\n}\n\n/**\n * Requests all full browser versions to be cached. When the returned promise\n * resolves, subsequent calls to `fullVersionOf(...).getIfLoaded()` will return\n * a value.\n *\n * This method should be avoided in favor of directly awaiting\n * `fullVersionOf(...).load()` where it is used.\n *\n * @return {!Promise<void>}\n */\nasync function loadFullVersions() {\n if (useUserAgentDataBrand() && hasFullVersionList()) {\n await fullVersionList.load();\n }\n}\nexports.loadFullVersions = loadFullVersions;\n\n/**\n * Returns an object that provides access to the full version string of the\n * current browser -- or undefined, based on whether the current browser matches\n * the requested browser brand. Note that the full version string is a\n * high-entropy value, and must be asynchronously loaded before it can be\n * accessed synchronously.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {!AsyncValue<!Version>|undefined} An object that can be used\n * to get or load the full version string as a high-entropy value, or\n * undefined if the current browser doesn't match the given brand.\n */\nfunction fullVersionOf(browser) {\n // Silk currently does not identify itself in its userAgentData.brands array,\n // so if checking its version, always fall back to the user agent string.\n if (useUserAgentDataBrand() && hasFullVersionList()) {\n const data = util.getUserAgentData();\n // Operate under the assumption that the low-entropy and high-entropy lists\n // of brand/version pairs contain an identical set of brands. Therefore, if\n // the low-entropy list doesn't contain the given brand, return undefined.\n if (!data.brands.find(({brand}) => brand === browser)) {\n return undefined;\n }\n return new HighEntropyBrandVersion(browser);\n } else {\n const fullVersionFromUserAgentString =\n getFullVersionFromUserAgentString(browser);\n if (fullVersionFromUserAgentString === '') {\n return undefined;\n }\n return new UserAgentStringFallbackBrandVersion(\n fullVersionFromUserAgentString);\n }\n}\nexports.fullVersionOf = fullVersionOf;\n\n/**\n * Returns a version string for the current browser or undefined, based on\n * whether the current browser is the one specified.\n * This value should ONLY be used for logging/debugging purposes. Do not use it\n * to branch code paths. For comparing versions, use isAtLeast()/isAtMost() or\n * fullVersionOf() instead.\n * @param {!Brand} browser The brand whose version should be returned.\n * @return {string} The version as a string.\n */\nfunction getVersionStringForLogging(browser) {\n if (useUserAgentDataBrand()) {\n const fullVersionObj = fullVersionOf(browser);\n if (fullVersionObj) {\n const fullVersion = fullVersionObj.getIfLoaded();\n if (fullVersion) {\n return fullVersion.toVersionStringForLogging();\n }\n // No full version, return the major version instead.\n const data = util.getUserAgentData();\n const matchingBrand = data.brands.find(({brand}) => brand === browser);\n // Checking for the existence of matchingBrand is not necessary because\n // the existence of fullVersionObj implies that there is already a\n // matching brand.\n googAsserts.assertExists(matchingBrand);\n return matchingBrand.version;\n }\n // If fullVersionObj is undefined, this doesn't mean that the full version\n // is unavailable, but rather that the current browser doesn't match the\n // input `browser` argument.\n return '';\n } else {\n return getFullVersionFromUserAgentString(browser);\n }\n}\nexports.getVersionStringForLogging = getVersionStringForLogging;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Closure user agent detection.\n * @see http://en.wikipedia.org/wiki/User_agent\n * For more information on browser brand, platform, or device see the other\n * sub-namespaces in goog.labs.userAgent (browser, platform, and device).\n */\n\ngoog.module('goog.labs.userAgent.engine');\ngoog.module.declareLegacyNamespace();\n\nconst googArray = goog.require('goog.array');\nconst googString = goog.require('goog.string.internal');\nconst util = goog.require('goog.labs.userAgent.util');\n\n/**\n * @return {boolean} Whether the rendering engine is Presto.\n */\nfunction isPresto() {\n return util.matchUserAgent('Presto');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Trident.\n */\nfunction isTrident() {\n // IE only started including the Trident token in IE8.\n return util.matchUserAgent('Trident') || util.matchUserAgent('MSIE');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is EdgeHTML.\n */\nfunction isEdge() {\n return util.matchUserAgent('Edge');\n}\n\n/**\n * @return {boolean} Whether the rendering engine is WebKit. This will return\n * true for Chrome, Blink-based Opera (15+), Edge Chromium and Safari.\n */\nfunction isWebKit() {\n return util.matchUserAgentIgnoreCase('WebKit') && !isEdge();\n}\n\n/**\n * @return {boolean} Whether the rendering engine is Gecko.\n */\nfunction isGecko() {\n return util.matchUserAgent('Gecko') && !isWebKit() && !isTrident() &&\n !isEdge();\n}\n\n/**\n * @return {string} The rendering engine's version or empty string if version\n * can't be determined.\n */\nfunction getVersion() {\n const userAgentString = util.getUserAgent();\n if (userAgentString) {\n const tuples = util.extractVersionTuples(userAgentString);\n\n const engineTuple = getEngineTuple(tuples);\n if (engineTuple) {\n // In Gecko, the version string is either in the browser info or the\n // Firefox version. See Gecko user agent string reference:\n // http://goo.gl/mULqa\n if (engineTuple[0] == 'Gecko') {\n return getVersionForKey(tuples, 'Firefox');\n }\n\n return engineTuple[1];\n }\n\n // MSIE has only one version identifier, and the Trident version is\n // specified in the parenthetical. IE Edge is covered in the engine tuple\n // detection.\n const browserTuple = tuples[0];\n let info;\n if (browserTuple && (info = browserTuple[2])) {\n const match = /Trident\\/([^\\s;]+)/.exec(info);\n if (match) {\n return match[1];\n }\n }\n }\n return '';\n}\n\n/**\n * @param {!Array<!Array<string>>} tuples Extracted version tuples.\n * @return {!Array<string>|undefined} The engine tuple or undefined if not\n * found.\n */\nfunction getEngineTuple(tuples) {\n if (!isEdge()) {\n return tuples[1];\n }\n for (let i = 0; i < tuples.length; i++) {\n const tuple = tuples[i];\n if (tuple[0] == 'Edge') {\n return tuple;\n }\n }\n}\n\n/**\n * @param {string|number} version The version to check.\n * @return {boolean} Whether the rendering engine version is higher or the same\n * as the given version.\n */\nfunction isVersionOrHigher(version) {\n return googString.compareVersions(getVersion(), version) >= 0;\n}\n\n/**\n * @param {!Array<!Array<string>>} tuples Version tuples.\n * @param {string} key The key to look for.\n * @return {string} The version string of the given key, if present.\n * Otherwise, the empty string.\n */\nfunction getVersionForKey(tuples, key) {\n // TODO(nnaze): Move to util if useful elsewhere.\n\n const pair = googArray.find(tuples, function(pair) {\n return key == pair[0];\n });\n\n return pair && pair[1] || '';\n}\n\nexports = {\n getVersion,\n isEdge,\n isGecko,\n isPresto,\n isTrident,\n isVersionOrHigher,\n isWebKit,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Wrapper class for handling XmlHttpRequests.\n *\n * One off requests can be sent through goog.net.XhrIo.send() or an\n * instance can be created to send multiple requests. Each request uses its\n * own XmlHttpRequest object and handles clearing of the event callback to\n * ensure no leaks.\n *\n * XhrIo is event based, it dispatches events on success, failure, finishing,\n * ready-state change, or progress (download and upload).\n *\n * The ready-state or timeout event fires first, followed by\n * a generic completed event. Then the abort, error, or success event\n * is fired as appropriate. Progress events are fired as they are\n * received. Lastly, the ready event will fire to indicate that the\n * object may be used to make another request.\n *\n * The error event may also be called before completed and\n * ready-state-change if the XmlHttpRequest.open() or .send() methods throw.\n *\n * This class does not support multiple requests, queuing, or prioritization.\n *\n * When progress events are supported by the browser, and progress is\n * enabled via .setProgressEventsEnabled(true), the\n * goog.net.EventType.PROGRESS event will be the re-dispatched browser\n * progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event\n * will be fired for download and upload progress respectively.\n */\n\n\ngoog.provide('goog.net.XhrIo');\ngoog.provide('goog.net.XhrIo.ResponseType');\n\ngoog.require('goog.Timer');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json.hybrid');\ngoog.require('goog.log');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.HttpStatus');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.uri.utils');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.net.XhrLike');\ngoog.requireType('goog.net.XmlHttpFactory');\n\ngoog.scope(function() {\n\n'use strict';\n/**\n * Basic class for handling XMLHttpRequests.\n * @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when\n * creating XMLHttpRequest objects.\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.net.XhrIo = function(opt_xmlHttpFactory) {\n 'use strict';\n XhrIo.base(this, 'constructor');\n\n /**\n * Map of default headers to add to every request, use:\n * XhrIo.headers.set(name, value)\n * @type {!Map<string,string>}\n */\n this.headers = new Map();\n\n /**\n * Optional XmlHttpFactory\n * @private {goog.net.XmlHttpFactory}\n */\n this.xmlHttpFactory_ = opt_xmlHttpFactory || null;\n\n /**\n * Whether XMLHttpRequest is active. A request is active from the time send()\n * is called until onReadyStateChange() is complete, or error() or abort()\n * is called.\n * @private {boolean}\n */\n this.active_ = false;\n\n /**\n * The XMLHttpRequest object that is being used for the transfer.\n * @private {?goog.net.XhrLike.OrNative}\n */\n this.xhr_ = null;\n\n /**\n * The options to use with the current XMLHttpRequest object.\n * @private {?Object}\n */\n this.xhrOptions_ = null;\n\n /**\n * Last URL that was requested.\n * @private {string|goog.Uri}\n */\n this.lastUri_ = '';\n\n /**\n * Method for the last request.\n * @private {string}\n */\n this.lastMethod_ = '';\n\n /**\n * Last error code.\n * @private {!goog.net.ErrorCode}\n */\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n\n /**\n * Last error message.\n * @private {Error|string}\n */\n this.lastError_ = '';\n\n /**\n * Used to ensure that we don't dispatch an multiple ERROR events. This can\n * happen in IE when it does a synchronous load and one error is handled in\n * the ready state change and one is handled due to send() throwing an\n * exception.\n * @private {boolean}\n */\n this.errorDispatched_ = false;\n\n /**\n * Used to make sure we don't fire the complete event from inside a send call.\n * @private {boolean}\n */\n this.inSend_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.open.\n * @private {boolean}\n */\n this.inOpen_ = false;\n\n /**\n * Used in determining if a call to {@link #onReadyStateChange_} is from\n * within a call to this.xhr_.abort.\n * @private {boolean}\n */\n this.inAbort_ = false;\n\n /**\n * Number of milliseconds after which an incomplete request will be aborted\n * and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout\n * is set.\n * @private {number}\n */\n this.timeoutInterval_ = 0;\n\n /**\n * Timer to track request timeout.\n * @private {?number}\n */\n this.timeoutId_ = null;\n\n /**\n * The requested type for the response. The empty string means use the default\n * XHR behavior.\n * @private {goog.net.XhrIo.ResponseType}\n */\n this.responseType_ = ResponseType.DEFAULT;\n\n /**\n * Whether a \"credentialed\" request is to be sent (one that is aware of\n * cookies and authentication). This is applicable only for cross-domain\n * requests and more recent browsers that support this part of the HTTP Access\n * Control standard.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute\n *\n * @private {boolean}\n */\n this.withCredentials_ = false;\n\n /**\n * Whether progress events are enabled for this request. This is\n * disabled by default because setting a progress event handler\n * causes pre-flight OPTIONS requests to be sent for CORS requests,\n * even in cases where a pre-flight request would not otherwise be\n * sent.\n *\n * @see http://xhr.spec.whatwg.org/#security-considerations\n *\n * Note that this can cause problems for Firefox 22 and below, as an\n * older \"LSProgressEvent\" will be dispatched by the browser. That\n * progress event is no longer supported, and can lead to failures,\n * including throwing exceptions.\n *\n * @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631\n * @see b/23469793\n *\n * @private {boolean}\n */\n this.progressEventsEnabled_ = false;\n\n /**\n * True if we can use XMLHttpRequest's timeout directly.\n * @private {boolean}\n */\n this.useXhr2Timeout_ = false;\n\n /**\n * Specification for Trust Token operations (issuance, signing, and\n * redemption).\n * @private {?TrustTokenAttributeType}\n */\n this.trustToken_ = null;\n};\ngoog.inherits(goog.net.XhrIo, goog.events.EventTarget);\n\nconst XhrIo = goog.net.XhrIo;\n\n/**\n * Response types that may be requested for XMLHttpRequests.\n * @enum {string}\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute\n */\ngoog.net.XhrIo.ResponseType = {\n DEFAULT: '',\n TEXT: 'text',\n DOCUMENT: 'document',\n // Not supported as of Chrome 10.0.612.1 dev\n BLOB: 'blob',\n ARRAY_BUFFER: 'arraybuffer',\n};\n\nconst ResponseType = goog.net.XhrIo.ResponseType;\n\n\n/**\n * A reference to the XhrIo logger\n * @private {?goog.log.Logger}\n * @const\n */\ngoog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');\n\n\n/**\n * The Content-Type HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';\n\n\n/**\n * The Content-Transfer-Encoding HTTP header name\n * @type {string}\n */\ngoog.net.XhrIo.CONTENT_TRANSFER_ENCODING = 'Content-Transfer-Encoding';\n\n\n/**\n * The pattern matching the 'http' and 'https' URI schemes\n * @type {!RegExp}\n */\ngoog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;\n\nconst HTTP_SCHEME_PATTERN = goog.net.XhrIo.HTTP_SCHEME_PATTERN;\n\n\n/**\n * The methods that typically come along with form data. We set different\n * headers depending on whether the HTTP action is one of these.\n * @type {!Array<string>}\n */\ngoog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];\n\n\n/**\n * The Content-Type HTTP header value for a url-encoded form\n * @type {string}\n */\ngoog.net.XhrIo.FORM_CONTENT_TYPE =\n 'application/x-www-form-urlencoded;charset=utf-8';\n\n\n/**\n * The XMLHttpRequest Level two timeout delay ms property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';\n\n\n/**\n * The XMLHttpRequest Level two ontimeout handler property name.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n *\n * @private {string}\n * @const\n */\ngoog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';\n\n\n/**\n * All non-disposed instances of goog.net.XhrIo created\n * by {@link goog.net.XhrIo.send} are in this Array.\n * @see goog.net.XhrIo.cleanup\n * @private {!Array<!goog.net.XhrIo>}\n */\ngoog.net.XhrIo.sendInstances_ = [];\n\n\n/**\n * Static send that creates a short lived instance of XhrIo to send the\n * request.\n * @see goog.net.XhrIo.cleanup\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function\n * for when request is complete.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {(?Object|?goog.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @param {number=} opt_timeoutInterval Number of milliseconds after which an\n * incomplete request will be aborted; 0 means no timeout is set.\n * @param {boolean=} opt_withCredentials Whether to send credentials with the\n * request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.\n * @return {!goog.net.XhrIo} The sent XhrIo.\n */\ngoog.net.XhrIo.send = function(\n url, opt_callback, opt_method, opt_content, opt_headers,\n opt_timeoutInterval, opt_withCredentials) {\n 'use strict';\n const x = new goog.net.XhrIo();\n goog.net.XhrIo.sendInstances_.push(x);\n if (opt_callback) {\n x.listen(goog.net.EventType.COMPLETE, opt_callback);\n }\n x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);\n if (opt_timeoutInterval) {\n x.setTimeoutInterval(opt_timeoutInterval);\n }\n if (opt_withCredentials) {\n x.setWithCredentials(opt_withCredentials);\n }\n x.send(url, opt_method, opt_content, opt_headers);\n return x;\n};\n\n\n/**\n * Disposes all non-disposed instances of goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send}.\n * {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance\n * it creates when the request completes or fails. However, if\n * the request never completes, then the goog.net.XhrIo is not disposed.\n * This can occur if the window is unloaded before the request completes.\n * We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo\n * it creates and make the client of {@link goog.net.XhrIo.send} be\n * responsible for disposing it in this case. However, this makes things\n * significantly more complicated for the client, and the whole point\n * of {@link goog.net.XhrIo.send} is that it's simple and easy to use.\n * Clients of {@link goog.net.XhrIo.send} should call\n * {@link goog.net.XhrIo.cleanup} when doing final\n * cleanup on window unload.\n */\ngoog.net.XhrIo.cleanup = function() {\n 'use strict';\n const instances = goog.net.XhrIo.sendInstances_;\n while (instances.length) {\n instances.pop().dispose();\n }\n};\n\n\n/**\n * Installs exception protection for all entry point introduced by\n * goog.net.XhrIo instances which are not protected by\n * {@link goog.debug.ErrorHandler#protectWindowSetTimeout},\n * {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or\n * {@link goog.events.protectBrowserEventEntryPoint}.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point(s).\n */\ngoog.net.XhrIo.protectEntryPoints = function(errorHandler) {\n 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n errorHandler.protectEntryPoint(\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n};\n\n\n/**\n * Disposes of the specified goog.net.XhrIo created by\n * {@link goog.net.XhrIo.send} and removes it from\n * {@link goog.net.XhrIo.pendingStaticSendInstances_}.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanupSend_ = function() {\n 'use strict';\n this.dispose();\n goog.array.remove(goog.net.XhrIo.sendInstances_, this);\n};\n\n\n/**\n * Returns the number of milliseconds after which an incomplete request will be\n * aborted, or 0 if no timeout is set.\n * @return {number} Timeout interval in milliseconds.\n */\ngoog.net.XhrIo.prototype.getTimeoutInterval = function() {\n 'use strict';\n return this.timeoutInterval_;\n};\n\n\n/**\n * Sets the number of milliseconds after which an incomplete request will be\n * aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no\n * timeout is set.\n * @param {number} ms Timeout interval in milliseconds; 0 means none.\n */\ngoog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {\n 'use strict';\n this.timeoutInterval_ = Math.max(0, ms);\n};\n\n\n/**\n * Sets the desired type for the response. At time of writing, this is only\n * supported in very recent versions of WebKit (10.0.612.1 dev and later).\n *\n * If this is used, the response may only be accessed via {@link #getResponse}.\n *\n * @param {goog.net.XhrIo.ResponseType} type The desired type for the response.\n */\ngoog.net.XhrIo.prototype.setResponseType = function(type) {\n 'use strict';\n this.responseType_ = type;\n};\n\n\n/**\n * Gets the desired type for the response.\n * @return {goog.net.XhrIo.ResponseType} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getResponseType = function() {\n 'use strict';\n return this.responseType_;\n};\n\n\n/**\n * Sets whether a \"credentialed\" request that is aware of cookie and\n * authentication information should be made. This option is only supported by\n * browsers that support HTTP Access Control. As of this writing, this option\n * is not supported in IE.\n *\n * @param {boolean} withCredentials Whether this should be a \"credentialed\"\n * request.\n */\ngoog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {\n 'use strict';\n this.withCredentials_ = withCredentials;\n};\n\n\n/**\n * Gets whether a \"credentialed\" request is to be sent.\n * @return {boolean} The desired type for the response.\n */\ngoog.net.XhrIo.prototype.getWithCredentials = function() {\n 'use strict';\n return this.withCredentials_;\n};\n\n\n/**\n * Sets whether progress events are enabled for this request. Note\n * that progress events require pre-flight OPTIONS request handling\n * for CORS requests, and may cause trouble with older browsers. See\n * progressEventsEnabled_ for details.\n * @param {boolean} enabled Whether progress events should be enabled.\n */\ngoog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {\n 'use strict';\n this.progressEventsEnabled_ = enabled;\n};\n\n\n/**\n * Gets whether progress events are enabled.\n * @return {boolean} Whether progress events are enabled for this request.\n */\ngoog.net.XhrIo.prototype.getProgressEventsEnabled = function() {\n 'use strict';\n return this.progressEventsEnabled_;\n};\n\n/**\n * Specify a Trust Tokens operation to execute alongside the request.\n * @param {!TrustTokenAttributeType} trustToken a Trust Tokens operation to\n * execute.\n */\ngoog.net.XhrIo.prototype.setTrustToken = function(trustToken) {\n 'use strict';\n this.trustToken_ = trustToken;\n};\n\n/**\n * Instance send that actually uses XMLHttpRequest to make a server call.\n * @param {string|goog.Uri} url Uri to make request to.\n * @param {string=} opt_method Send method, default: GET.\n * @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}\n * opt_content Body data.\n * @param {(?Object|?goog.collections.maps.MapLike<string, string>)=}\n * opt_headers Map of headers to add to the request.\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters for opt_headers.\n */\ngoog.net.XhrIo.prototype.send = function(\n url, opt_method, opt_content, opt_headers) {\n 'use strict';\n if (this.xhr_) {\n throw new Error(\n '[goog.net.XhrIo] Object is active with another request=' +\n this.lastUri_ + '; newUri=' + url);\n }\n\n const method = opt_method ? opt_method.toUpperCase() : 'GET';\n\n this.lastUri_ = url;\n this.lastError_ = '';\n this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;\n this.lastMethod_ = method;\n this.errorDispatched_ = false;\n this.active_ = true;\n\n // Use the factory to create the XHR object and options\n this.xhr_ = this.createXhr();\n this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :\n goog.net.XmlHttp.getOptions();\n\n // Set up the onreadystatechange callback\n this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);\n\n // Set up upload/download progress events, if progress events are supported.\n if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {\n this.xhr_.onprogress = goog.bind(function(e) {\n 'use strict';\n this.onProgressHandler_(e, true);\n }, this);\n if (this.xhr_.upload) {\n this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);\n }\n }\n\n /**\n * Try to open the XMLHttpRequest (always async), if an error occurs here it\n * is generally permission denied\n */\n try {\n goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));\n this.inOpen_ = true;\n this.xhr_.open(method, String(url), true); // Always async!\n this.inOpen_ = false;\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n return;\n }\n\n // We can't use null since this won't allow requests with form data to have a\n // content length specified which will cause some proxies to return a 411\n // error.\n const content = opt_content || '';\n\n const headers = new Map(this.headers);\n\n // Add headers specific to this request\n if (opt_headers) {\n if (Object.getPrototypeOf(opt_headers) === Object.prototype) {\n for (let key in opt_headers) {\n headers.set(key, opt_headers[key]);\n }\n } else if (\n typeof opt_headers.keys === 'function' &&\n typeof opt_headers.get === 'function') {\n for (const key of opt_headers.keys()) {\n headers.set(key, opt_headers.get(key));\n }\n } else {\n throw new Error(\n 'Unknown input type for opt_headers: ' + String(opt_headers));\n }\n }\n\n // Find whether a content type header is set, ignoring case.\n // HTTP header names are case-insensitive. See:\n // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\n const contentTypeKey =\n Array.from(headers.keys())\n .find(\n header => goog.string.caseInsensitiveEquals(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, header));\n\n const contentIsFormData =\n (goog.global['FormData'] && (content instanceof goog.global['FormData']));\n if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&\n !contentTypeKey && !contentIsFormData) {\n // For requests typically with form data, default to the url-encoded form\n // content type unless this is a FormData request. For FormData,\n // the browser will automatically add a multipart/form-data content type\n // with an appropriate multipart boundary.\n headers.set(\n goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);\n }\n\n // Add the headers to the Xhr object\n for (const [key, value] of headers) {\n this.xhr_.setRequestHeader(key, value);\n }\n\n if (this.responseType_) {\n this.xhr_.responseType = this.responseType_;\n }\n // Set xhr_.withCredentials only when the value is different, or else in\n // synchronous XMLHtppRequest.open Firefox will throw an exception.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=736340\n if ('withCredentials' in this.xhr_ &&\n this.xhr_.withCredentials !== this.withCredentials_) {\n this.xhr_.withCredentials = this.withCredentials_;\n }\n\n if ('setTrustToken' in this.xhr_ && this.trustToken_) {\n try {\n this.xhr_.setTrustToken(this.trustToken_);\n } catch (err) {\n goog.log.fine(\n this.logger_, this.formatMsg_('Error SetTrustToken: ' + err.message));\n }\n }\n /**\n * Try to send the request, or other wise report an error (404 not found).\n */\n try {\n this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.\n if (this.timeoutInterval_ > 0) {\n this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);\n goog.log.fine(\n this.logger_,\n this.formatMsg_(\n 'Will abort after ' + this.timeoutInterval_ +\n 'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));\n if (this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =\n goog.bind(this.timeout_, this);\n } else {\n this.timeoutId_ =\n goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);\n }\n }\n goog.log.fine(this.logger_, this.formatMsg_('Sending request'));\n this.inSend_ = true;\n this.xhr_.send(content);\n this.inSend_ = false;\n\n } catch (err) {\n goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));\n this.error_(goog.net.ErrorCode.EXCEPTION, err);\n }\n};\n\n\n/**\n * Determines if the argument is an XMLHttpRequest that supports the level 2\n * timeout value and event.\n *\n * Currently, FF 21.0 OS X has the fields but won't actually call the timeout\n * handler. Perhaps the confusion in the bug referenced below hasn't\n * entirely been resolved.\n *\n * @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute\n * @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816\n *\n * @param {!goog.net.XhrLike.OrNative} xhr The request.\n * @return {boolean} True if the request supports level 2 timeout.\n * @private\n */\ngoog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {\n 'use strict';\n return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&\n typeof xhr[goog.net.XhrIo.XHR2_TIMEOUT_] === 'number' &&\n xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_] !== undefined;\n};\n\n\n/**\n * Creates a new XHR object.\n * @return {!goog.net.XhrLike.OrNative} The newly created XHR object.\n * @protected\n */\ngoog.net.XhrIo.prototype.createXhr = function() {\n 'use strict';\n return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :\n goog.net.XmlHttp();\n};\n\n\n/**\n * The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}\n * milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts\n * the request.\n * @private\n */\ngoog.net.XhrIo.prototype.timeout_ = function() {\n 'use strict';\n if (typeof goog == 'undefined') {\n // If goog is undefined then the callback has occurred as the application\n // is unloading and will error. Thus we let it silently fail.\n } else if (this.xhr_) {\n this.lastError_ =\n 'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';\n this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;\n goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));\n this.dispatchEvent(goog.net.EventType.TIMEOUT);\n this.abort(goog.net.ErrorCode.TIMEOUT);\n }\n};\n\n\n/**\n * Something errorred, so inactivate, fire error callback and clean up\n * @param {goog.net.ErrorCode} errorCode The error code.\n * @param {Error} err The error object.\n * @private\n */\ngoog.net.XhrIo.prototype.error_ = function(errorCode, err) {\n 'use strict';\n this.active_ = false;\n if (this.xhr_) {\n this.inAbort_ = true;\n this.xhr_.abort(); // Ensures XHR isn't hung (FF)\n this.inAbort_ = false;\n }\n this.lastError_ = err;\n this.lastErrorCode_ = errorCode;\n this.dispatchErrors_();\n this.cleanUpXhr_();\n};\n\n\n/**\n * Dispatches COMPLETE and ERROR in case of an error. This ensures that we do\n * not dispatch multiple error events.\n * @private\n */\ngoog.net.XhrIo.prototype.dispatchErrors_ = function() {\n 'use strict';\n if (!this.errorDispatched_) {\n this.errorDispatched_ = true;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ERROR);\n }\n};\n\n\n/**\n * Abort the current XMLHttpRequest\n * @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -\n * defaults to ABORT.\n */\ngoog.net.XhrIo.prototype.abort = function(opt_failureCode) {\n 'use strict';\n if (this.xhr_ && this.active_) {\n goog.log.fine(this.logger_, this.formatMsg_('Aborting'));\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.ABORT);\n this.cleanUpXhr_();\n }\n};\n\n\n/**\n * Nullifies all callbacks to reduce risks of leaks.\n * @override\n * @protected\n */\ngoog.net.XhrIo.prototype.disposeInternal = function() {\n 'use strict';\n if (this.xhr_) {\n // We explicitly do not call xhr_.abort() unless active_ is still true.\n // This is to avoid unnecessarily aborting a successful request when\n // dispose() is called in a callback triggered by a complete response, but\n // in which browser cleanup has not yet finished.\n // (See http://b/issue?id=1684217.)\n if (this.active_) {\n this.active_ = false;\n this.inAbort_ = true;\n this.xhr_.abort();\n this.inAbort_ = false;\n }\n this.cleanUpXhr_(true);\n }\n\n XhrIo.base(this, 'disposeInternal');\n};\n\n\n/**\n * Internal handler for the XHR object's readystatechange event. This method\n * checks the status and the readystate and fires the correct callbacks.\n * If the request has ended, the handlers are cleaned up and the XHR object is\n * nullified.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChange_ = function() {\n 'use strict';\n if (this.isDisposed()) {\n // This method is the target of an untracked goog.Timer.callOnce().\n return;\n }\n if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {\n // Were not being called from within a call to this.xhr_.send\n // this.xhr_.abort, or this.xhr_.open, so this is an entry point\n this.onReadyStateChangeEntryPoint_();\n } else {\n this.onReadyStateChangeHelper_();\n }\n};\n\n\n/**\n * Used to protect the onreadystatechange handler entry point. Necessary\n * as {#onReadyStateChange_} maybe called from within send or abort, this\n * method is only called when {#onReadyStateChange_} is called as an\n * entry point.\n * {@see #protectEntryPoints}\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {\n 'use strict';\n this.onReadyStateChangeHelper_();\n};\n\n\n/**\n * Helper for {@link #onReadyStateChange_}. This is used so that\n * entry point calls to {@link #onReadyStateChange_} can be routed through\n * {@link #onReadyStateChangeEntryPoint_}.\n * @private\n */\ngoog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {\n 'use strict';\n if (!this.active_) {\n // can get called inside abort call\n return;\n }\n\n if (typeof goog == 'undefined') {\n // NOTE(user): If goog is undefined then the callback has occurred as the\n // application is unloading and will error. Thus we let it silently fail.\n\n } else if (\n this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&\n this.getStatus() == 2) {\n // NOTE(user): In IE if send() errors on a *local* request the readystate\n // is still changed to COMPLETE. We need to ignore it and allow the\n // try/catch around send() to pick up the error.\n goog.log.fine(\n this.logger_,\n this.formatMsg_('Local request error detected and ignored'));\n\n } else {\n // In IE when the response has been cached we sometimes get the callback\n // from inside the send call and this usually breaks code that assumes that\n // XhrIo is asynchronous. If that is the case we delay the callback\n // using a timer.\n if (this.inSend_ &&\n this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {\n goog.Timer.callOnce(this.onReadyStateChange_, 0, this);\n return;\n }\n\n this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);\n\n // readyState indicates the transfer has finished\n if (this.isComplete()) {\n goog.log.fine(this.logger_, this.formatMsg_('Request complete'));\n\n this.active_ = false;\n\n try {\n // Call the specific callbacks for success or failure. Only call the\n // success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)\n if (this.isSuccess()) {\n this.dispatchEvent(goog.net.EventType.COMPLETE);\n this.dispatchEvent(goog.net.EventType.SUCCESS);\n } else {\n this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;\n this.lastError_ =\n this.getStatusText() + ' [' + this.getStatus() + ']';\n this.dispatchErrors_();\n }\n } finally {\n this.cleanUpXhr_();\n }\n }\n }\n};\n\n\n/**\n * Internal handler for the XHR object's onprogress event. Fires both a generic\n * PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to\n * allow specific binding for each XHR progress event.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {boolean=} opt_isDownload Whether the current progress event is from a\n * download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS\n * event should be dispatched.\n * @private\n */\ngoog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {\n 'use strict';\n goog.asserts.assert(\n e.type === goog.net.EventType.PROGRESS,\n 'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');\n this.dispatchEvent(\n goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));\n this.dispatchEvent(goog.net.XhrIo.buildProgressEvent_(\n e,\n opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :\n goog.net.EventType.UPLOAD_PROGRESS));\n};\n\n\n/**\n * Creates a representation of the native ProgressEvent. IE doesn't support\n * constructing ProgressEvent via \"new\", and the alternatives (e.g.,\n * ProgressEvent.initProgressEvent) are non-standard or deprecated.\n * @param {!ProgressEvent} e XHR progress event.\n * @param {!goog.net.EventType} eventType The type of the event.\n * @return {!ProgressEvent} The progress event.\n * @private\n */\ngoog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {\n 'use strict';\n return /** @type {!ProgressEvent} */ ({\n type: eventType,\n lengthComputable: e.lengthComputable,\n loaded: e.loaded,\n total: e.total,\n });\n};\n\n\n/**\n * Remove the listener to protect against leaks, and nullify the XMLHttpRequest\n * object.\n * @param {boolean=} opt_fromDispose If this is from the dispose (don't want to\n * fire any events).\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {\n 'use strict';\n if (this.xhr_) {\n // Cancel any pending timeout event handler.\n this.cleanUpTimeoutTimer_();\n\n // Save reference so we can mark it as closed after the READY event. The\n // READY event may trigger another request, thus we must nullify this.xhr_\n const xhr = this.xhr_;\n const clearedOnReadyStateChange =\n this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?\n goog.nullFunction :\n null;\n this.xhr_ = null;\n this.xhrOptions_ = null;\n\n if (!opt_fromDispose) {\n this.dispatchEvent(goog.net.EventType.READY);\n }\n\n try {\n // NOTE(user): Not nullifying in FireFox can still leak if the callbacks\n // are defined in the same scope as the instance of XhrIo. But, IE doesn't\n // allow you to set the onreadystatechange to NULL so nullFunction is\n // used.\n xhr.onreadystatechange = clearedOnReadyStateChange;\n } catch (e) {\n // This seems to occur with a Gears HTTP request. Delayed the setting of\n // this onreadystatechange until after READY is sent out and catching the\n // error to see if we can track down the problem.\n goog.log.error(\n this.logger_,\n 'Problem encountered resetting onreadystatechange: ' + e.message);\n }\n }\n};\n\n\n/**\n * Make sure the timeout timer isn't running.\n * @private\n */\ngoog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {\n 'use strict';\n if (this.xhr_ && this.useXhr2Timeout_) {\n this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;\n }\n if (this.timeoutId_) {\n goog.Timer.clear(this.timeoutId_);\n this.timeoutId_ = null;\n }\n};\n\n\n/**\n * @return {boolean} Whether there is an active request.\n */\ngoog.net.XhrIo.prototype.isActive = function() {\n 'use strict';\n return !!this.xhr_;\n};\n\n\n/**\n * @return {boolean} Whether the request has completed.\n */\ngoog.net.XhrIo.prototype.isComplete = function() {\n 'use strict';\n return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n};\n\n\n/**\n * @return {boolean} Whether the request completed with a success.\n */\ngoog.net.XhrIo.prototype.isSuccess = function() {\n 'use strict';\n const status = this.getStatus();\n // A zero status code is considered successful for local files.\n return goog.net.HttpStatus.isSuccess(status) ||\n status === 0 && !this.isLastUriEffectiveSchemeHttp_();\n};\n\n\n/**\n * @return {boolean} whether the effective scheme of the last URI that was\n * fetched was 'http' or 'https'.\n * @private\n */\ngoog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {\n 'use strict';\n const scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));\n return HTTP_SCHEME_PATTERN.test(scheme);\n};\n\n\n/**\n * Get the readystate from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.\n */\ngoog.net.XhrIo.prototype.getReadyState = function() {\n 'use strict';\n return this.xhr_ ?\n /** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :\n goog.net.XmlHttp.ReadyState.UNINITIALIZED;\n};\n\n\n/**\n * Get the status from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {number} Http status.\n */\ngoog.net.XhrIo.prototype.getStatus = function() {\n 'use strict';\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.status :\n -1;\n } catch (e) {\n return -1;\n }\n};\n\n\n/**\n * Get the status text from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @return {string} Status text.\n */\ngoog.net.XhrIo.prototype.getStatusText = function() {\n 'use strict';\n /**\n * IE doesn't like you checking status until the readystate is greater than 2\n * (i.e. it is receiving or complete). The try/catch is used for when the\n * page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.\n */\n try {\n return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?\n this.xhr_.statusText :\n '';\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get status: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the last Uri that was requested\n * @return {string} Last Uri.\n */\ngoog.net.XhrIo.prototype.getLastUri = function() {\n 'use strict';\n return String(this.lastUri_);\n};\n\n\n/**\n * Get the response text from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {string} Result from the server, or '' if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseText = function() {\n 'use strict';\n try {\n return this.xhr_ ? this.xhr_.responseText : '';\n } catch (e) {\n // http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute\n // states that responseText should return '' (and responseXML null)\n // when the state is not LOADING or DONE. Instead, IE can\n // throw unexpected exceptions, for example when a request is aborted\n // or no data is available yet.\n goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);\n return '';\n }\n};\n\n\n/**\n * Get the response body from the Xhr object. This property is only available\n * in IE since version 7 according to MSDN:\n * http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx\n * Will only return correct result when called from the context of a callback.\n *\n * One option is to construct a VBArray from the returned object and convert\n * it to a JavaScript array using the toArray method:\n * `(new window['VBArray'](xhrIo.getResponseBody())).toArray()`\n * This will result in an array of numbers in the range of [0..255]\n *\n * Another option is to use the VBScript CStr method to convert it into a\n * string as outlined in http://stackoverflow.com/questions/1919972\n *\n * @return {Object} Binary result from the server or null if not available.\n */\ngoog.net.XhrIo.prototype.getResponseBody = function() {\n 'use strict';\n try {\n if (this.xhr_ && 'responseBody' in this.xhr_) {\n return this.xhr_['responseBody'];\n }\n } catch (e) {\n // IE can throw unexpected exceptions, for example when a request is aborted\n // or no data is yet available.\n goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);\n }\n return null;\n};\n\n\n/**\n * Get the response XML from the Xhr object\n * Will only return correct result when called from the context of a callback.\n * @return {Document} The DOM Document representing the XML file, or null\n * if no result available.\n */\ngoog.net.XhrIo.prototype.getResponseXml = function() {\n 'use strict';\n try {\n return this.xhr_ ? this.xhr_.responseXML : null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the response and evaluates it as JSON from the Xhr object\n * Will only return correct result when called from the context of a callback\n * @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for\n * stripping of the response before parsing. This needs to be set only if\n * your backend server prepends the same prefix string to the JSON response.\n * @throws Error if the response text is invalid JSON.\n * @return {Object|undefined} JavaScript object.\n */\ngoog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {\n 'use strict';\n if (!this.xhr_) {\n return undefined;\n }\n\n let responseText = this.xhr_.responseText;\n if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {\n responseText = responseText.substring(opt_xssiPrefix.length);\n }\n\n return goog.json.hybrid.parse(responseText);\n};\n\n\n/**\n * Get the response as the type specificed by {@link #setResponseType}. At time\n * of writing, this is only directly supported in very recent versions of WebKit\n * (10.0.612.1 dev and later). If the field is not supported directly, we will\n * try to emulate it.\n *\n * Emulating the response means following the rules laid out at\n * http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute\n *\n * On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only\n * response types of DEFAULT or TEXT may be used, and the response returned will\n * be the text response.\n *\n * On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),\n * only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the\n * response returned will be either the text response or the Mozilla\n * implementation of the array buffer response.\n *\n * On browsers will full support, any valid response type supported by the\n * browser may be used, and the response provided by the browser will be\n * returned.\n *\n * @return {*} The response.\n */\ngoog.net.XhrIo.prototype.getResponse = function() {\n 'use strict';\n try {\n if (!this.xhr_) {\n return null;\n }\n if ('response' in this.xhr_) {\n return this.xhr_.response;\n }\n switch (this.responseType_) {\n case ResponseType.DEFAULT:\n case ResponseType.TEXT:\n return this.xhr_.responseText;\n // DOCUMENT and BLOB don't need to be handled here because they are\n // introduced in the same spec that adds the .response field, and would\n // have been caught above.\n // ARRAY_BUFFER needs an implementation for Firefox 4, where it was\n // implemented using a draft spec rather than the final spec.\n case ResponseType.ARRAY_BUFFER:\n if ('mozResponseArrayBuffer' in this.xhr_) {\n return this.xhr_.mozResponseArrayBuffer;\n }\n }\n // Fell through to a response type that is not supported on this browser.\n goog.log.error(\n this.logger_,\n 'Response type ' + this.responseType_ + ' is not ' +\n 'supported on this browser');\n return null;\n } catch (e) {\n goog.log.fine(this.logger_, 'Can not get response: ' + e.message);\n return null;\n }\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object\n * Will only return correct result when called from the context of a callback\n * and the request has completed\n * @param {string} key The name of the response-header to retrieve.\n * @return {string|undefined} The value of the response-header named key.\n */\ngoog.net.XhrIo.prototype.getResponseHeader = function(key) {\n 'use strict';\n if (!this.xhr_ || !this.isComplete()) {\n return undefined;\n }\n\n const value = this.xhr_.getResponseHeader(key);\n return value === null ? undefined : value;\n};\n\n\n/**\n * Gets the text of all the headers in the response.\n * Will only return correct result when called from the context of a callback\n * and the request has completed.\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllResponseHeaders = function() {\n 'use strict';\n // getAllResponseHeaders can return null if no response has been received,\n // ensure we always return an empty string.\n return this.xhr_ && this.isComplete() ?\n (this.xhr_.getAllResponseHeaders() || '') :\n '';\n};\n\n\n/**\n * Returns all response headers as a key-value map.\n * Multiple values for the same header key can be combined into one,\n * separated by a comma and a space.\n * Note that the native getResponseHeader method for retrieving a single header\n * does a case insensitive match on the header name. This method does not\n * include any case normalization logic, it will just return a key-value\n * representation of the headers.\n * See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method\n * @return {!Object<string, string>} An object with the header keys as keys\n * and header values as values.\n */\ngoog.net.XhrIo.prototype.getResponseHeaders = function() {\n 'use strict';\n // TODO(user): Make this function parse headers as per the spec\n // (https://tools.ietf.org/html/rfc2616#section-4.2).\n\n const headersObject = {};\n const headersArray = this.getAllResponseHeaders().split('\\r\\n');\n for (let i = 0; i < headersArray.length; i++) {\n if (goog.string.isEmptyOrWhitespace(headersArray[i])) {\n continue;\n }\n const keyValue =\n goog.string.splitLimit(headersArray[i], ':', /* maxSplitCount= */ 1);\n const key = keyValue[0];\n let value = keyValue[1];\n\n if (typeof value !== 'string') {\n // There must be a value but it can be the empty string.\n continue;\n }\n\n // Whitespace at the start and end of the value is meaningless.\n value = value.trim();\n // The key should not contain whitespace but we currently ignore that.\n\n const values = headersObject[key] || [];\n headersObject[key] = values;\n values.push(value);\n }\n\n return goog.object.map(headersObject, function(values) {\n 'use strict';\n return values.join(', ');\n });\n};\n\n\n/**\n * Get the value of the response-header with the given name from the Xhr object.\n * As opposed to {@link #getResponseHeader}, this method does not require that\n * the request has completed.\n * @param {string} key The name of the response-header to retrieve.\n * @return {?string} The value of the response-header, or null if it is\n * unavailable.\n */\ngoog.net.XhrIo.prototype.getStreamingResponseHeader = function(key) {\n 'use strict';\n return this.xhr_ ? this.xhr_.getResponseHeader(key) : null;\n};\n\n\n/**\n * Gets the text of all the headers in the response. As opposed to\n * {@link #getAllResponseHeaders}, this method does not require that the request\n * has completed.\n * @return {string} The value of the response headers or empty string.\n */\ngoog.net.XhrIo.prototype.getAllStreamingResponseHeaders = function() {\n 'use strict';\n return this.xhr_ ? this.xhr_.getAllResponseHeaders() : '';\n};\n\n\n/**\n * Get the last error message\n * @return {!goog.net.ErrorCode} Last error code.\n */\ngoog.net.XhrIo.prototype.getLastErrorCode = function() {\n 'use strict';\n return this.lastErrorCode_;\n};\n\n\n/**\n * Get the last error message\n * @return {string} Last error message.\n */\ngoog.net.XhrIo.prototype.getLastError = function() {\n 'use strict';\n return typeof this.lastError_ === 'string' ? this.lastError_ :\n String(this.lastError_);\n};\n\n\n/**\n * Adds the last method, status and URI to the message. This is used to add\n * this information to the logging calls.\n * @param {string} msg The message text that we want to add the extra text to.\n * @return {string} The message with the extra text appended.\n * @private\n */\ngoog.net.XhrIo.prototype.formatMsg_ = function(msg) {\n 'use strict';\n return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +\n this.getStatus() + ']';\n};\n\n\n// Register the xhr handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n 'use strict';\n goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =\n transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);\n });\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A patched, standardized event object for browser events.\n *\n * <pre>\n * The patched event object contains the following members:\n * - type {string} Event type, e.g. 'click'\n * - target {Object} The element that actually triggered the event\n * - currentTarget {Object} The element the listener is attached to\n * - relatedTarget {Object} For mouseover and mouseout, the previous object\n * - offsetX {number} X-coordinate relative to target\n * - offsetY {number} Y-coordinate relative to target\n * - clientX {number} X-coordinate relative to viewport\n * - clientY {number} Y-coordinate relative to viewport\n * - screenX {number} X-coordinate relative to the edge of the screen\n * - screenY {number} Y-coordinate relative to the edge of the screen\n * - button {number} Mouse button. Use isButton() to test.\n * - keyCode {number} Key-code\n * - ctrlKey {boolean} Was ctrl key depressed\n * - altKey {boolean} Was alt key depressed\n * - shiftKey {boolean} Was shift key depressed\n * - metaKey {boolean} Was meta key depressed\n * - pointerId {number} Pointer ID\n * - pointerType {string} Pointer type, e.g. 'mouse', 'pen', or 'touch'\n * - defaultPrevented {boolean} Whether the default action has been prevented\n * - state {Object} History state object\n *\n * NOTE: The keyCode member contains the raw browser keyCode. For normalized\n * key and character code use {@link goog.events.KeyHandler}.\n * </pre>\n */\n\ngoog.provide('goog.events.BrowserEvent');\ngoog.provide('goog.events.BrowserEvent.MouseButton');\ngoog.provide('goog.events.BrowserEvent.PointerType');\n\ngoog.require('goog.debug');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventType');\ngoog.require('goog.reflect');\ngoog.require('goog.userAgent');\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * The content of this object will not be initialized if no event object is\n * provided. If this is the case, init() needs to be invoked separately.\n * @param {Event=} opt_e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.events.BrowserEvent = function(opt_e, opt_currentTarget) {\n 'use strict';\n goog.events.BrowserEvent.base(this, 'constructor', opt_e ? opt_e.type : '');\n\n /**\n * Target that fired the event.\n * @override\n * @type {?Node}\n */\n this.target = null;\n\n /**\n * Node that had the listener attached.\n * @override\n * @type {?Node|undefined}\n */\n this.currentTarget = null;\n\n /**\n * For mouseover and mouseout events, the related object for the event.\n * @type {?Node}\n */\n this.relatedTarget = null;\n\n /**\n * X-coordinate relative to target.\n * @type {number}\n */\n this.offsetX = 0;\n\n /**\n * Y-coordinate relative to target.\n * @type {number}\n */\n this.offsetY = 0;\n\n /**\n * X-coordinate relative to the window.\n * @type {number}\n */\n this.clientX = 0;\n\n /**\n * Y-coordinate relative to the window.\n * @type {number}\n */\n this.clientY = 0;\n\n /**\n * X-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenX = 0;\n\n /**\n * Y-coordinate relative to the monitor.\n * @type {number}\n */\n this.screenY = 0;\n\n /**\n * Which mouse button was pressed.\n * @type {number}\n */\n this.button = 0;\n\n /**\n * Key of key press.\n * @type {string}\n */\n this.key = '';\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.keyCode = 0;\n\n /**\n * Keycode of key press.\n * @type {number}\n */\n this.charCode = 0;\n\n /**\n * Whether control was pressed at time of event.\n * @type {boolean}\n */\n this.ctrlKey = false;\n\n /**\n * Whether alt was pressed at time of event.\n * @type {boolean}\n */\n this.altKey = false;\n\n /**\n * Whether shift was pressed at time of event.\n * @type {boolean}\n */\n this.shiftKey = false;\n\n /**\n * Whether the meta key was pressed at time of event.\n * @type {boolean}\n */\n this.metaKey = false;\n\n /**\n * History state object, only set for PopState events where it's a copy of the\n * state object provided to pushState or replaceState.\n * @type {?Object}\n */\n this.state = null;\n\n /**\n * Whether the default platform modifier key was pressed at time of event.\n * (This is control for all platforms except Mac, where it's Meta.)\n * @type {boolean}\n */\n this.platformModifierKey = false;\n\n /**\n * @type {number}\n */\n this.pointerId = 0;\n\n /**\n * @type {string}\n */\n this.pointerType = '';\n\n /**\n * The browser event object.\n * @private {?Event}\n */\n this.event_ = null;\n\n if (opt_e) {\n this.init(opt_e, opt_currentTarget);\n }\n};\ngoog.inherits(goog.events.BrowserEvent, goog.events.Event);\n\n/**\n * @define {boolean} If true, use the layerX and layerY properties of a native\n * browser event over the offsetX and offsetY properties, which cause expensive\n * reflow. If layerX or layerY is not defined, offsetX and offsetY will be used\n * as usual.\n */\ngoog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY =\n goog.define('goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY', false);\n\n\n/**\n * Normalized button constants for the mouse.\n * @enum {number}\n */\ngoog.events.BrowserEvent.MouseButton = {\n LEFT: 0,\n MIDDLE: 1,\n RIGHT: 2\n};\n\n\n/**\n * Normalized pointer type constants for pointer events.\n * @enum {string}\n */\ngoog.events.BrowserEvent.PointerType = {\n MOUSE: 'mouse',\n PEN: 'pen',\n TOUCH: 'touch'\n};\n\n\n/**\n * Static data for mapping mouse buttons.\n * @type {!Array<number>}\n * @deprecated Use `goog.events.BrowserEvent.IE_BUTTON_MAP` instead.\n */\ngoog.events.BrowserEvent.IEButtonMap = goog.debug.freeze([\n 1, // LEFT\n 4, // MIDDLE\n 2 // RIGHT\n]);\n\n\n/**\n * Static data for mapping mouse buttons.\n * @const {!Array<number>}\n */\ngoog.events.BrowserEvent.IE_BUTTON_MAP = goog.events.BrowserEvent.IEButtonMap;\n\n\n/**\n * Static data for mapping MSPointerEvent types to PointerEvent types.\n * @const {!Object<number, goog.events.BrowserEvent.PointerType>}\n */\ngoog.events.BrowserEvent.IE_POINTER_TYPE_MAP = goog.debug.freeze({\n 2: goog.events.BrowserEvent.PointerType.TOUCH,\n 3: goog.events.BrowserEvent.PointerType.PEN,\n 4: goog.events.BrowserEvent.PointerType.MOUSE\n});\n\n\n/**\n * Accepts a browser event object and creates a patched, cross browser event\n * object.\n * @param {Event} e Browser event object.\n * @param {EventTarget=} opt_currentTarget Current target for event.\n */\ngoog.events.BrowserEvent.prototype.init = function(e, opt_currentTarget) {\n 'use strict';\n var type = this.type = e.type;\n\n /**\n * On touch devices use the first \"changed touch\" as the relevant touch.\n * @type {?Touch}\n */\n var relevantTouch =\n e.changedTouches && e.changedTouches.length ? e.changedTouches[0] : null;\n\n // TODO(nicksantos): Change this.target to type EventTarget.\n this.target = /** @type {Node} */ (e.target) || e.srcElement;\n\n // TODO(nicksantos): Change this.currentTarget to type EventTarget.\n this.currentTarget = /** @type {Node} */ (opt_currentTarget);\n\n var relatedTarget = /** @type {Node} */ (e.relatedTarget);\n if (relatedTarget) {\n // There's a bug in FireFox where sometimes, relatedTarget will be a\n // chrome element, and accessing any property of it will get a permission\n // denied exception. See:\n // https://bugzilla.mozilla.org/show_bug.cgi?id=497780\n if (goog.userAgent.GECKO) {\n if (!goog.reflect.canAccessProperty(relatedTarget, 'nodeName')) {\n relatedTarget = null;\n }\n }\n } else if (type == goog.events.EventType.MOUSEOVER) {\n relatedTarget = e.fromElement;\n } else if (type == goog.events.EventType.MOUSEOUT) {\n relatedTarget = e.toElement;\n }\n\n this.relatedTarget = relatedTarget;\n\n if (relevantTouch) {\n this.clientX = relevantTouch.clientX !== undefined ? relevantTouch.clientX :\n relevantTouch.pageX;\n this.clientY = relevantTouch.clientY !== undefined ? relevantTouch.clientY :\n relevantTouch.pageY;\n this.screenX = relevantTouch.screenX || 0;\n this.screenY = relevantTouch.screenY || 0;\n } else {\n if (goog.events.BrowserEvent.USE_LAYER_XY_AS_OFFSET_XY) {\n this.offsetX = (e.layerX !== undefined) ? e.layerX : e.offsetX;\n this.offsetY = (e.layerY !== undefined) ? e.layerY : e.offsetY;\n } else {\n // Webkit emits a lame warning whenever layerX/layerY is accessed.\n // http://code.google.com/p/chromium/issues/detail?id=101733\n this.offsetX = (goog.userAgent.WEBKIT || e.offsetX !== undefined) ?\n e.offsetX :\n e.layerX;\n this.offsetY = (goog.userAgent.WEBKIT || e.offsetY !== undefined) ?\n e.offsetY :\n e.layerY;\n }\n this.clientX = e.clientX !== undefined ? e.clientX : e.pageX;\n this.clientY = e.clientY !== undefined ? e.clientY : e.pageY;\n this.screenX = e.screenX || 0;\n this.screenY = e.screenY || 0;\n }\n\n this.button = e.button;\n\n this.keyCode = e.keyCode || 0;\n this.key = e.key || '';\n this.charCode = e.charCode || (type == 'keypress' ? e.keyCode : 0);\n this.ctrlKey = e.ctrlKey;\n this.altKey = e.altKey;\n this.shiftKey = e.shiftKey;\n this.metaKey = e.metaKey;\n this.platformModifierKey = goog.userAgent.MAC ? e.metaKey : e.ctrlKey;\n this.pointerId = e.pointerId || 0;\n this.pointerType = goog.events.BrowserEvent.getPointerType_(e);\n this.state = e.state;\n this.event_ = e;\n if (e.defaultPrevented) {\n // Sync native event state to internal state via super class, where default\n // prevention is implemented and managed.\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n }\n};\n\n\n/**\n * Tests to see which button was pressed during the event. This is really only\n * useful in IE and Gecko browsers. And in IE, it's only useful for\n * mousedown/mouseup events, because click only fires for the left mouse button.\n *\n * Safari 2 only reports the left button being clicked, and uses the value '1'\n * instead of 0. Opera only reports a mousedown event for the middle button, and\n * no mouse events for the right button. Opera has default behavior for left and\n * middle click that can only be overridden via a configuration setting.\n *\n * There's a nice table of this mess at http://www.unixpapa.com/js/mouse.html.\n *\n * @param {goog.events.BrowserEvent.MouseButton} button The button\n * to test for.\n * @return {boolean} True if button was pressed.\n */\ngoog.events.BrowserEvent.prototype.isButton = function(button) {\n 'use strict';\n return this.event_.button == button;\n};\n\n\n/**\n * Whether this has an \"action\"-producing mouse button.\n *\n * By definition, this includes left-click on windows/linux, and left-click\n * without the ctrl key on Macs.\n *\n * @return {boolean} The result.\n */\ngoog.events.BrowserEvent.prototype.isMouseActionButton = function() {\n 'use strict';\n // Ctrl+click should never behave like a left-click on mac, regardless of\n // whether or not the browser will actually ever emit such an event. If\n // we see it, treat it like right-click always.\n return this.isButton(goog.events.BrowserEvent.MouseButton.LEFT) &&\n !(goog.userAgent.MAC && this.ctrlKey);\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.stopPropagation = function() {\n 'use strict';\n goog.events.BrowserEvent.superClass_.stopPropagation.call(this);\n if (this.event_.stopPropagation) {\n this.event_.stopPropagation();\n } else {\n this.event_.cancelBubble = true;\n }\n};\n\n\n/**\n * @override\n */\ngoog.events.BrowserEvent.prototype.preventDefault = function() {\n 'use strict';\n goog.events.BrowserEvent.superClass_.preventDefault.call(this);\n var be = this.event_;\n if (!be.preventDefault) {\n be.returnValue = false;\n } else {\n be.preventDefault();\n }\n};\n\n\n/**\n * @return {Event} The underlying browser event object.\n */\ngoog.events.BrowserEvent.prototype.getBrowserEvent = function() {\n 'use strict';\n return this.event_;\n};\n\n\n/**\n * Extracts the pointer type from the given event.\n * @param {!Event} e\n * @return {string} The pointer type, e.g. 'mouse', 'pen', or 'touch'.\n * @private\n */\ngoog.events.BrowserEvent.getPointerType_ = function(e) {\n 'use strict';\n if (typeof (e.pointerType) === 'string') {\n return e.pointerType;\n }\n // IE10 uses integer codes for pointer type.\n // https://msdn.microsoft.com/en-us/library/hh772359(v=vs.85).aspx\n return goog.events.BrowserEvent.IE_POINTER_TYPE_MAP[e.pointerType] || '';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Event Types.\n */\n\n\ngoog.provide('goog.events.EventType');\ngoog.provide('goog.events.EventTypeHelpers');\ngoog.provide('goog.events.MouseAsMouseEventType');\ngoog.provide('goog.events.MouseEvents');\ngoog.provide('goog.events.PointerAsMouseEventType');\ngoog.provide('goog.events.PointerAsTouchEventType');\ngoog.provide('goog.events.PointerFallbackEventType');\ngoog.provide('goog.events.PointerTouchFallbackEventType');\n\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.userAgent');\n\n\n/**\n * Returns a prefixed event name for the current browser.\n * @param {string} eventName The name of the event.\n * @return {string} The prefixed event name.\n * @private\n */\ngoog.events.EventTypeHelpers.getVendorPrefixedName_ = function(eventName) {\n 'use strict';\n return goog.userAgent.WEBKIT ? 'webkit' + eventName : eventName.toLowerCase();\n};\n\n\n/**\n * Constants for event names.\n * @enum {string}\n */\ngoog.events.EventType = {\n // Mouse events\n CLICK: 'click',\n RIGHTCLICK: 'rightclick',\n DBLCLICK: 'dblclick',\n AUXCLICK: 'auxclick',\n MOUSEDOWN: 'mousedown',\n MOUSEUP: 'mouseup',\n MOUSEOVER: 'mouseover',\n MOUSEOUT: 'mouseout',\n MOUSEMOVE: 'mousemove',\n MOUSEENTER: 'mouseenter',\n MOUSELEAVE: 'mouseleave',\n\n // Non-existent event; will never fire. This exists as a mouse counterpart to\n // POINTERCANCEL.\n MOUSECANCEL: 'mousecancel',\n\n // Selection events.\n // https://www.w3.org/TR/selection-api/\n SELECTIONCHANGE: 'selectionchange',\n SELECTSTART: 'selectstart', // IE, Safari, Chrome\n\n // Wheel events\n // http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents\n WHEEL: 'wheel',\n\n // Key events\n KEYPRESS: 'keypress',\n KEYDOWN: 'keydown',\n KEYUP: 'keyup',\n\n // Focus\n BLUR: 'blur',\n FOCUS: 'focus',\n DEACTIVATE: 'deactivate', // IE only\n FOCUSIN: 'focusin',\n FOCUSOUT: 'focusout',\n\n // Forms\n CHANGE: 'change',\n RESET: 'reset',\n SELECT: 'select',\n SUBMIT: 'submit',\n INPUT: 'input',\n PROPERTYCHANGE: 'propertychange', // IE only\n\n // Drag and drop\n DRAGSTART: 'dragstart',\n DRAG: 'drag',\n DRAGENTER: 'dragenter',\n DRAGOVER: 'dragover',\n DRAGLEAVE: 'dragleave',\n DROP: 'drop',\n DRAGEND: 'dragend',\n\n // Touch events\n // Note that other touch events exist, but we should follow the W3C list here.\n // http://www.w3.org/TR/touch-events/#list-of-touchevent-types\n TOUCHSTART: 'touchstart',\n TOUCHMOVE: 'touchmove',\n TOUCHEND: 'touchend',\n TOUCHCANCEL: 'touchcancel',\n\n // Misc\n BEFOREUNLOAD: 'beforeunload',\n CONSOLEMESSAGE: 'consolemessage',\n CONTEXTMENU: 'contextmenu',\n DEVICECHANGE: 'devicechange',\n DEVICEMOTION: 'devicemotion',\n DEVICEORIENTATION: 'deviceorientation',\n DOMCONTENTLOADED: 'DOMContentLoaded',\n ERROR: 'error',\n HELP: 'help',\n LOAD: 'load',\n LOSECAPTURE: 'losecapture',\n ORIENTATIONCHANGE: 'orientationchange',\n READYSTATECHANGE: 'readystatechange',\n RESIZE: 'resize',\n SCROLL: 'scroll',\n UNLOAD: 'unload',\n\n // Media events\n CANPLAY: 'canplay',\n CANPLAYTHROUGH: 'canplaythrough',\n DURATIONCHANGE: 'durationchange',\n EMPTIED: 'emptied',\n ENDED: 'ended',\n LOADEDDATA: 'loadeddata',\n LOADEDMETADATA: 'loadedmetadata',\n PAUSE: 'pause',\n PLAY: 'play',\n PLAYING: 'playing',\n PROGRESS: 'progress',\n RATECHANGE: 'ratechange',\n SEEKED: 'seeked',\n SEEKING: 'seeking',\n STALLED: 'stalled',\n SUSPEND: 'suspend',\n TIMEUPDATE: 'timeupdate',\n VOLUMECHANGE: 'volumechange',\n WAITING: 'waiting',\n\n // Media Source Extensions events\n // https://www.w3.org/TR/media-source/#mediasource-events\n SOURCEOPEN: 'sourceopen',\n SOURCEENDED: 'sourceended',\n SOURCECLOSED: 'sourceclosed',\n // https://www.w3.org/TR/media-source/#sourcebuffer-events\n ABORT: 'abort',\n UPDATE: 'update',\n UPDATESTART: 'updatestart',\n UPDATEEND: 'updateend',\n\n // HTML 5 History events\n // See http://www.w3.org/TR/html5/browsers.html#event-definitions-0\n HASHCHANGE: 'hashchange',\n PAGEHIDE: 'pagehide',\n PAGESHOW: 'pageshow',\n POPSTATE: 'popstate',\n\n // Copy and Paste\n // Support is limited. Make sure it works on your favorite browser\n // before using.\n // http://www.quirksmode.org/dom/events/cutcopypaste.html\n COPY: 'copy',\n PASTE: 'paste',\n CUT: 'cut',\n BEFORECOPY: 'beforecopy',\n BEFORECUT: 'beforecut',\n BEFOREPASTE: 'beforepaste',\n\n // HTML5 online/offline events.\n // http://www.w3.org/TR/offline-webapps/#related\n ONLINE: 'online',\n OFFLINE: 'offline',\n\n // HTML 5 worker events\n MESSAGE: 'message',\n CONNECT: 'connect',\n\n // Service Worker Events - ServiceWorkerGlobalScope context\n // See https://w3c.github.io/ServiceWorker/#execution-context-events\n // Note: message event defined in worker events section\n INSTALL: 'install',\n ACTIVATE: 'activate',\n FETCH: 'fetch',\n FOREIGNFETCH: 'foreignfetch',\n MESSAGEERROR: 'messageerror',\n\n // Service Worker Events - Document context\n // See https://w3c.github.io/ServiceWorker/#document-context-events\n STATECHANGE: 'statechange',\n UPDATEFOUND: 'updatefound',\n CONTROLLERCHANGE: 'controllerchange',\n\n // CSS animation events.\n ANIMATIONSTART:\n goog.events.EventTypeHelpers.getVendorPrefixedName_('AnimationStart'),\n ANIMATIONEND:\n goog.events.EventTypeHelpers.getVendorPrefixedName_('AnimationEnd'),\n ANIMATIONITERATION:\n goog.events.EventTypeHelpers.getVendorPrefixedName_('AnimationIteration'),\n\n // CSS transition events. Based on the browser support described at:\n // https://developer.mozilla.org/en/css/css_transitions#Browser_compatibility\n TRANSITIONEND:\n goog.events.EventTypeHelpers.getVendorPrefixedName_('TransitionEnd'),\n\n // W3C Pointer Events\n // http://www.w3.org/TR/pointerevents/\n POINTERDOWN: 'pointerdown',\n POINTERUP: 'pointerup',\n POINTERCANCEL: 'pointercancel',\n POINTERMOVE: 'pointermove',\n POINTEROVER: 'pointerover',\n POINTEROUT: 'pointerout',\n POINTERENTER: 'pointerenter',\n POINTERLEAVE: 'pointerleave',\n GOTPOINTERCAPTURE: 'gotpointercapture',\n LOSTPOINTERCAPTURE: 'lostpointercapture',\n\n // IE specific events.\n // See http://msdn.microsoft.com/en-us/library/ie/hh772103(v=vs.85).aspx\n // Note: these events will be supplanted in IE11.\n MSGESTURECHANGE: 'MSGestureChange',\n MSGESTUREEND: 'MSGestureEnd',\n MSGESTUREHOLD: 'MSGestureHold',\n MSGESTURESTART: 'MSGestureStart',\n MSGESTURETAP: 'MSGestureTap',\n MSGOTPOINTERCAPTURE: 'MSGotPointerCapture',\n MSINERTIASTART: 'MSInertiaStart',\n MSLOSTPOINTERCAPTURE: 'MSLostPointerCapture',\n MSPOINTERCANCEL: 'MSPointerCancel',\n MSPOINTERDOWN: 'MSPointerDown',\n MSPOINTERENTER: 'MSPointerEnter',\n MSPOINTERHOVER: 'MSPointerHover',\n MSPOINTERLEAVE: 'MSPointerLeave',\n MSPOINTERMOVE: 'MSPointerMove',\n MSPOINTEROUT: 'MSPointerOut',\n MSPOINTEROVER: 'MSPointerOver',\n MSPOINTERUP: 'MSPointerUp',\n\n // Native IMEs/input tools events.\n TEXT: 'text',\n // The textInput event is supported in IE9+, but only in lower case. All other\n // browsers use the camel-case event name.\n TEXTINPUT: goog.userAgent.IE ? 'textinput' : 'textInput',\n COMPOSITIONSTART: 'compositionstart',\n COMPOSITIONUPDATE: 'compositionupdate',\n COMPOSITIONEND: 'compositionend',\n\n // The beforeinput event is initially only supported in Safari. See\n // https://bugs.chromium.org/p/chromium/issues/detail?id=342670 for Chrome\n // implementation tracking.\n BEFOREINPUT: 'beforeinput',\n\n // Webview tag events\n // See https://developer.chrome.com/apps/tags/webview\n EXIT: 'exit',\n LOADABORT: 'loadabort',\n LOADCOMMIT: 'loadcommit',\n LOADREDIRECT: 'loadredirect',\n LOADSTART: 'loadstart',\n LOADSTOP: 'loadstop',\n RESPONSIVE: 'responsive',\n SIZECHANGED: 'sizechanged',\n UNRESPONSIVE: 'unresponsive',\n\n // HTML5 Page Visibility API. See details at\n // `goog.labs.dom.PageVisibilityMonitor`.\n VISIBILITYCHANGE: 'visibilitychange',\n\n // LocalStorage event.\n STORAGE: 'storage',\n\n // DOM Level 2 mutation events (deprecated).\n DOMSUBTREEMODIFIED: 'DOMSubtreeModified',\n DOMNODEINSERTED: 'DOMNodeInserted',\n DOMNODEREMOVED: 'DOMNodeRemoved',\n DOMNODEREMOVEDFROMDOCUMENT: 'DOMNodeRemovedFromDocument',\n DOMNODEINSERTEDINTODOCUMENT: 'DOMNodeInsertedIntoDocument',\n DOMATTRMODIFIED: 'DOMAttrModified',\n DOMCHARACTERDATAMODIFIED: 'DOMCharacterDataModified',\n\n // Print events.\n BEFOREPRINT: 'beforeprint',\n AFTERPRINT: 'afterprint',\n\n // Web app manifest events.\n BEFOREINSTALLPROMPT: 'beforeinstallprompt',\n APPINSTALLED: 'appinstalled'\n};\n\n\n/**\n * Returns one of the given pointer fallback event names in order of preference:\n * 1. pointerEventName\n * 2. msPointerEventName\n * 3. fallbackEventName\n * @param {string} pointerEventName\n * @param {string} msPointerEventName\n * @param {string} fallbackEventName\n * @return {string} The supported pointer or fallback (mouse or touch) event\n * name.\n * @private\n */\ngoog.events.EventTypeHelpers.getPointerFallbackEventName_ = function(\n pointerEventName, msPointerEventName, fallbackEventName) {\n 'use strict';\n if (goog.events.BrowserFeature.POINTER_EVENTS) {\n return pointerEventName;\n }\n if (goog.events.BrowserFeature.MSPOINTER_EVENTS) {\n return msPointerEventName;\n }\n return fallbackEventName;\n};\n\n\n/**\n * Constants for pointer event names that fall back to corresponding mouse event\n * names on unsupported platforms. These are intended to be drop-in replacements\n * for corresponding values in `goog.events.EventType`.\n * @enum {string}\n */\ngoog.events.PointerFallbackEventType = {\n POINTERDOWN: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\n goog.events.EventType.MOUSEDOWN),\n POINTERUP: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\n goog.events.EventType.MOUSEUP),\n POINTERCANCEL: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERCANCEL,\n goog.events.EventType.MSPOINTERCANCEL,\n // When falling back to mouse events, there is no MOUSECANCEL equivalent\n // of POINTERCANCEL. In this case POINTERUP already falls back to MOUSEUP\n // which represents both UP and CANCEL. POINTERCANCEL does not fall back\n // to MOUSEUP to prevent listening twice on the same event.\n goog.events.EventType.MOUSECANCEL),\n POINTERMOVE: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\n goog.events.EventType.MOUSEMOVE),\n POINTEROVER: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTEROVER, goog.events.EventType.MSPOINTEROVER,\n goog.events.EventType.MOUSEOVER),\n POINTEROUT: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTEROUT, goog.events.EventType.MSPOINTEROUT,\n goog.events.EventType.MOUSEOUT),\n POINTERENTER: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERENTER, goog.events.EventType.MSPOINTERENTER,\n goog.events.EventType.MOUSEENTER),\n POINTERLEAVE: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERLEAVE, goog.events.EventType.MSPOINTERLEAVE,\n goog.events.EventType.MOUSELEAVE)\n};\n\n\n/**\n * Constants for pointer event names that fall back to corresponding touch event\n * names on unsupported platforms. These are intended to be drop-in replacements\n * for corresponding values in `goog.events.EventType`.\n * @enum {string}\n */\ngoog.events.PointerTouchFallbackEventType = {\n POINTERDOWN: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERDOWN, goog.events.EventType.MSPOINTERDOWN,\n goog.events.EventType.TOUCHSTART),\n POINTERUP: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERUP, goog.events.EventType.MSPOINTERUP,\n goog.events.EventType.TOUCHEND),\n POINTERCANCEL: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERCANCEL,\n goog.events.EventType.MSPOINTERCANCEL, goog.events.EventType.TOUCHCANCEL),\n POINTERMOVE: goog.events.EventTypeHelpers.getPointerFallbackEventName_(\n goog.events.EventType.POINTERMOVE, goog.events.EventType.MSPOINTERMOVE,\n goog.events.EventType.TOUCHMOVE)\n};\n\n\n/**\n * Mapping of mouse event names to underlying browser event names.\n * @typedef {{\n * MOUSEDOWN: string,\n * MOUSEUP: string,\n * MOUSECANCEL:string,\n * MOUSEMOVE:string,\n * MOUSEOVER:string,\n * MOUSEOUT:string,\n * MOUSEENTER:string,\n * MOUSELEAVE: string,\n * }}\n */\ngoog.events.MouseEvents;\n\n\n/**\n * An alias for `goog.events.EventType.MOUSE*` event types that is overridden by\n * corresponding `POINTER*` event types.\n * @const {!goog.events.MouseEvents}\n */\ngoog.events.PointerAsMouseEventType = {\n MOUSEDOWN: goog.events.PointerFallbackEventType.POINTERDOWN,\n MOUSEUP: goog.events.PointerFallbackEventType.POINTERUP,\n MOUSECANCEL: goog.events.PointerFallbackEventType.POINTERCANCEL,\n MOUSEMOVE: goog.events.PointerFallbackEventType.POINTERMOVE,\n MOUSEOVER: goog.events.PointerFallbackEventType.POINTEROVER,\n MOUSEOUT: goog.events.PointerFallbackEventType.POINTEROUT,\n MOUSEENTER: goog.events.PointerFallbackEventType.POINTERENTER,\n MOUSELEAVE: goog.events.PointerFallbackEventType.POINTERLEAVE\n};\n\n\n/**\n * An alias for `goog.events.EventType.MOUSE*` event types that continue to use\n * mouse events.\n * @const {!goog.events.MouseEvents}\n */\ngoog.events.MouseAsMouseEventType = {\n MOUSEDOWN: goog.events.EventType.MOUSEDOWN,\n MOUSEUP: goog.events.EventType.MOUSEUP,\n MOUSECANCEL: goog.events.EventType.MOUSECANCEL,\n MOUSEMOVE: goog.events.EventType.MOUSEMOVE,\n MOUSEOVER: goog.events.EventType.MOUSEOVER,\n MOUSEOUT: goog.events.EventType.MOUSEOUT,\n MOUSEENTER: goog.events.EventType.MOUSEENTER,\n MOUSELEAVE: goog.events.EventType.MOUSELEAVE\n};\n\n\n/**\n * An alias for `goog.events.EventType.TOUCH*` event types that is overridden by\n * corresponding `POINTER*` event types.\n * @enum {string}\n */\ngoog.events.PointerAsTouchEventType = {\n TOUCHCANCEL: goog.events.PointerTouchFallbackEventType.POINTERCANCEL,\n TOUCHEND: goog.events.PointerTouchFallbackEventType.POINTERUP,\n TOUCHMOVE: goog.events.PointerTouchFallbackEventType.POINTERMOVE,\n TOUCHSTART: goog.events.PointerTouchFallbackEventType.POINTERDOWN\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface for a listenable JavaScript object.\n */\n\ngoog.provide('goog.events.Listenable');\n\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\n\n\n/**\n * A listenable interface. A listenable is an object with the ability\n * to dispatch/broadcast events to \"event listeners\" registered via\n * listen/listenOnce.\n *\n * The interface allows for an event propagation mechanism similar\n * to one offered by native browser event targets, such as\n * capture/bubble mechanism, stopping propagation, and preventing\n * default actions. Capture/bubble mechanism depends on the ancestor\n * tree constructed via `#getParentEventTarget`; this tree\n * must be directed acyclic graph. The meaning of default action(s)\n * in preventDefault is specific to a particular use case.\n *\n * Implementations that do not support capture/bubble or can not have\n * a parent listenable can simply not implement any ability to set the\n * parent listenable (and have `#getParentEventTarget` return\n * null).\n *\n * Implementation of this class can be used with or independently from\n * goog.events.\n *\n * Implementation must call `#addImplementation(implClass)`.\n *\n * @interface\n * @see goog.events\n * @see http://www.w3.org/TR/DOM-Level-2-Events/events.html\n */\ngoog.events.Listenable = function() {};\n\n\n/**\n * An expando property to indicate that an object implements\n * goog.events.Listenable.\n *\n * See addImplementation/isImplementedBy.\n *\n * @type {string}\n * @const\n */\ngoog.events.Listenable.IMPLEMENTED_BY_PROP =\n 'closure_listenable_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * Marks a given class (constructor) as an implementation of\n * Listenable, so that we can query that fact at runtime. The class\n * must have already implemented the interface.\n * @param {function(new:goog.events.Listenable,...)} cls The class constructor.\n * The corresponding class must have already implemented the interface.\n */\ngoog.events.Listenable.addImplementation = function(cls) {\n 'use strict';\n cls.prototype[goog.events.Listenable.IMPLEMENTED_BY_PROP] = true;\n};\n\n\n/**\n * @param {?Object} obj The object to check.\n * @return {boolean} Whether a given instance implements Listenable. The\n * class/superclass of the instance must call addImplementation.\n */\ngoog.events.Listenable.isImplementedBy = function(obj) {\n 'use strict';\n return !!(obj && obj[goog.events.Listenable.IMPLEMENTED_BY_PROP]);\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Adds an event listener that is removed automatically after the\n * listener fired once.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Removes an event listener which was added with listen() or listenOnce().\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.Listenable.prototype.unlistenByKey = function(key) {};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {?goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n */\ngoog.events.Listenable.prototype.dispatchEvent = function(e) {};\n\n\n/**\n * Removes all listeners from this listenable. If type is specified,\n * it will only remove listeners of the particular type. otherwise all\n * registered listeners will be removed.\n *\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.Listenable.prototype.removeAllListeners = function(opt_type) {};\n\n\n/**\n * Returns the parent of this event target to use for capture/bubble\n * mechanism.\n *\n * NOTE(chrishenry): The name reflects the original implementation of\n * custom event target (`goog.events.EventTarget`). We decided\n * that changing the name is not worth it.\n *\n * @return {?goog.events.Listenable} The parent EventTarget or null if\n * there is no parent.\n */\ngoog.events.Listenable.prototype.getParentEventTarget = function() {};\n\n\n/**\n * Fires all registered listeners in this listenable for the given\n * type and capture mode, passing them the given eventObject. This\n * does not perform actual capture/bubble. Only implementors of the\n * interface should be using this.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.fireListeners = function(\n type, capture, eventObject) {};\n\n\n/**\n * Gets all listeners in this listenable for the given type and\n * capture mode.\n *\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListeners = function(type, capture) {};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {?goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n */\ngoog.events.Listenable.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {};\n\n\n/**\n * Whether there is any active listeners matching the specified\n * signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n */\ngoog.events.Listenable.prototype.hasListener = function(\n opt_type, opt_capture) {};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An interface that describes a single registered listener.\n */\ngoog.provide('goog.events.ListenableKey');\n\ngoog.requireType('goog.events.Listenable');\n\n\n/**\n * An interface that describes a single registered listener.\n * @interface\n */\ngoog.events.ListenableKey = function() {};\n\n\n/**\n * Counter used to create a unique key\n * @type {number}\n * @private\n */\ngoog.events.ListenableKey.counter_ = 0;\n\n\n/**\n * Reserves a key to be used for ListenableKey#key field.\n * @return {number} A number to be used to fill ListenableKey#key\n * field.\n */\ngoog.events.ListenableKey.reserveKey = function() {\n 'use strict';\n return ++goog.events.ListenableKey.counter_;\n};\n\n\n/**\n * The source event target.\n * @type {?Object|?goog.events.Listenable}\n */\ngoog.events.ListenableKey.prototype.src;\n\n\n/**\n * The event type the listener is listening to.\n * @type {string}\n */\ngoog.events.ListenableKey.prototype.type;\n\n\n/**\n * The listener function.\n * @type {function(?):?|{handleEvent:function(?):?}|null}\n */\ngoog.events.ListenableKey.prototype.listener;\n\n\n/**\n * Whether the listener works on capture phase.\n * @type {boolean}\n */\ngoog.events.ListenableKey.prototype.capture;\n\n\n/**\n * The 'this' object for the listener function's scope.\n * @type {?Object|undefined}\n */\ngoog.events.ListenableKey.prototype.handler;\n\n\n/**\n * A globally unique number to identify the key.\n * @type {number}\n */\ngoog.events.ListenableKey.prototype.key;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Listener object.\n * @see ../demos/events.html\n */\n\ngoog.provide('goog.events.Listener');\n\ngoog.require('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listenable');\n\n\n\n/**\n * Simple class that stores information about a listener\n * @param {function(?):?} listener Callback function.\n * @param {Function} proxy Wrapper for the listener that patches the event.\n * @param {EventTarget|goog.events.Listenable} src Source object for\n * the event.\n * @param {string} type Event type.\n * @param {boolean} capture Whether in capture or bubble phase.\n * @param {Object=} opt_handler Object in whose context to execute the callback.\n * @implements {goog.events.ListenableKey}\n * @constructor\n */\ngoog.events.Listener = function(\n listener, proxy, src, type, capture, opt_handler) {\n 'use strict';\n if (goog.events.Listener.ENABLE_MONITORING) {\n this.creationStack = new Error().stack;\n }\n\n /** @override */\n this.listener = listener;\n\n /**\n * A wrapper over the original listener. This is used solely to\n * handle native browser events (it is used to simulate the capture\n * phase and to patch the event object).\n * @type {Function}\n */\n this.proxy = proxy;\n\n /**\n * Object or node that callback is listening to\n * @type {EventTarget|goog.events.Listenable}\n */\n this.src = src;\n\n /**\n * The event type.\n * @const {string}\n */\n this.type = type;\n\n /**\n * Whether the listener is being called in the capture or bubble phase\n * @const {boolean}\n */\n this.capture = !!capture;\n\n /**\n * Optional object whose context to execute the listener in\n * @type {Object|undefined}\n */\n this.handler = opt_handler;\n\n /**\n * The key of the listener.\n * @const {number}\n * @override\n */\n this.key = goog.events.ListenableKey.reserveKey();\n\n /**\n * Whether to remove the listener after it has been called.\n * @type {boolean}\n */\n this.callOnce = false;\n\n /**\n * Whether the listener has been removed.\n * @type {boolean}\n */\n this.removed = false;\n};\n\n\n/**\n * @define {boolean} Whether to enable the monitoring of the\n * goog.events.Listener instances. Switching on the monitoring is only\n * recommended for debugging because it has a significant impact on\n * performance and memory usage. If switched off, the monitoring code\n * compiles down to 0 bytes.\n */\ngoog.events.Listener.ENABLE_MONITORING =\n goog.define('goog.events.Listener.ENABLE_MONITORING', false);\n\n\n/**\n * If monitoring the goog.events.Listener instances is enabled, stores the\n * creation stack trace of the Disposable instance.\n * @type {string}\n */\ngoog.events.Listener.prototype.creationStack;\n\n\n/**\n * Marks this listener as removed. This also remove references held by\n * this listener object (such as listener and event source).\n */\ngoog.events.Listener.prototype.markAsRemoved = function() {\n 'use strict';\n this.removed = true;\n this.listener = null;\n this.proxy = null;\n this.src = null;\n this.handler = null;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A map of listeners that provides utility functions to\n * deal with listeners on an event target. Used by\n * `goog.events.EventTarget`.\n *\n * WARNING: Do not use this class from outside goog.events package.\n *\n */\n\ngoog.provide('goog.events.ListenerMap');\n\ngoog.require('goog.array');\ngoog.require('goog.events.Listener');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.Listenable');\ngoog.requireType('goog.events.ListenableKey');\n\n\n\n/**\n * Creates a new listener map.\n * @param {EventTarget|goog.events.Listenable} src The src object.\n * @constructor\n * @final\n */\ngoog.events.ListenerMap = function(src) {\n 'use strict';\n /** @type {EventTarget|goog.events.Listenable} */\n this.src = src;\n\n /**\n * Maps of event type to an array of listeners.\n * @type {!Object<string, !Array<!goog.events.Listener>>}\n */\n this.listeners = {};\n\n /**\n * The count of types in this map that have registered listeners.\n * @private {number}\n */\n this.typeCount_ = 0;\n};\n\n\n/**\n * @return {number} The count of event types in this map that actually\n * have registered listeners.\n */\ngoog.events.ListenerMap.prototype.getTypeCount = function() {\n 'use strict';\n return this.typeCount_;\n};\n\n\n/**\n * @return {number} Total number of registered listeners.\n */\ngoog.events.ListenerMap.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var type in this.listeners) {\n count += this.listeners[type].length;\n }\n return count;\n};\n\n\n/**\n * Adds an event listener. A listener can only be added once to an\n * object and if it is added again the key for the listener is\n * returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n */\ngoog.events.ListenerMap.prototype.add = function(\n type, listener, callOnce, opt_useCapture, opt_listenerScope) {\n 'use strict';\n var typeStr = type.toString();\n var listenerArray = this.listeners[typeStr];\n if (!listenerArray) {\n listenerArray = this.listeners[typeStr] = [];\n this.typeCount_++;\n }\n\n var listenerObj;\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n listenerObj = listenerArray[index];\n if (!callOnce) {\n // Ensure that, if there is an existing callOnce listener, it is no\n // longer a callOnce listener.\n listenerObj.callOnce = false;\n }\n } else {\n listenerObj = new goog.events.Listener(\n listener, null, this.src, typeStr, !!opt_useCapture, opt_listenerScope);\n listenerObj.callOnce = callOnce;\n listenerArray.push(listenerObj);\n }\n return listenerObj;\n};\n\n\n/**\n * Removes a matching listener.\n * @param {string|!goog.events.EventId} type The listener event type.\n * @param {!Function} listener This listener callback method.\n * @param {boolean=} opt_useCapture The capture mode of the listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {boolean} Whether any listener was removed.\n */\ngoog.events.ListenerMap.prototype.remove = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n var typeStr = type.toString();\n if (!(typeStr in this.listeners)) {\n return false;\n }\n\n var listenerArray = this.listeners[typeStr];\n var index = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, opt_useCapture, opt_listenerScope);\n if (index > -1) {\n var listenerObj = listenerArray[index];\n listenerObj.markAsRemoved();\n goog.array.removeAt(listenerArray, index);\n if (listenerArray.length == 0) {\n delete this.listeners[typeStr];\n this.typeCount_--;\n }\n return true;\n }\n return false;\n};\n\n\n/**\n * Removes the given listener object.\n * @param {!goog.events.ListenableKey} listener The listener to remove.\n * @return {boolean} Whether the listener is removed.\n */\ngoog.events.ListenerMap.prototype.removeByKey = function(listener) {\n 'use strict';\n var type = listener.type;\n if (!(type in this.listeners)) {\n return false;\n }\n\n var removed = goog.array.remove(this.listeners[type], listener);\n if (removed) {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n if (this.listeners[type].length == 0) {\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return removed;\n};\n\n\n/**\n * Removes all listeners from this map. If opt_type is provided, only\n * listeners that match the given type are removed.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * @return {number} Number of listeners removed.\n */\ngoog.events.ListenerMap.prototype.removeAll = function(opt_type) {\n 'use strict';\n var typeStr = opt_type && opt_type.toString();\n var count = 0;\n for (var type in this.listeners) {\n if (!typeStr || type == typeStr) {\n var listenerArray = this.listeners[type];\n for (var i = 0; i < listenerArray.length; i++) {\n ++count;\n listenerArray[i].markAsRemoved();\n }\n delete this.listeners[type];\n this.typeCount_--;\n }\n }\n return count;\n};\n\n\n/**\n * Gets all listeners that match the given type and capture mode. The\n * returned array is a copy (but the listener objects are not).\n * @param {string|!goog.events.EventId} type The type of the listeners\n * to retrieve.\n * @param {boolean} capture The capture mode of the listeners to retrieve.\n * @return {!Array<!goog.events.ListenableKey>} An array of matching\n * listeners.\n */\ngoog.events.ListenerMap.prototype.getListeners = function(type, capture) {\n 'use strict';\n var listenerArray = this.listeners[type.toString()];\n var rv = [];\n if (listenerArray) {\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (listenerObj.capture == capture) {\n rv.push(listenerObj);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Gets the goog.events.ListenableKey for the event or null if no such\n * listener is in use.\n *\n * @param {string|!goog.events.EventId} type The type of the listener\n * to retrieve.\n * @param {!Function} listener The listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {Object=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n */\ngoog.events.ListenerMap.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n var listenerArray = this.listeners[type.toString()];\n var i = -1;\n if (listenerArray) {\n i = goog.events.ListenerMap.findListenerIndex_(\n listenerArray, listener, capture, opt_listenerScope);\n }\n return i > -1 ? listenerArray[i] : null;\n};\n\n\n/**\n * Whether there is a matching listener. If either the type or capture\n * parameters are unspecified, the function will match on the\n * remaining criteria.\n *\n * @param {string|!goog.events.EventId=} opt_type The type of the listener.\n * @param {boolean=} opt_capture The capture mode of the listener.\n * @return {boolean} Whether there is an active listener matching\n * the requested type and/or capture phase.\n */\ngoog.events.ListenerMap.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var hasType = (opt_type !== undefined);\n var typeStr = hasType ? opt_type.toString() : '';\n var hasCapture = (opt_capture !== undefined);\n\n return goog.object.some(this.listeners, function(listenerArray, type) {\n 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n if ((!hasType || listenerArray[i].type == typeStr) &&\n (!hasCapture || listenerArray[i].capture == opt_capture)) {\n return true;\n }\n }\n\n return false;\n });\n};\n\n\n/**\n * Finds the index of a matching goog.events.Listener in the given\n * listenerArray.\n * @param {!Array<!goog.events.Listener>} listenerArray Array of listener.\n * @param {!Function} listener The listener function.\n * @param {boolean=} opt_useCapture The capture flag for the listener.\n * @param {Object=} opt_listenerScope The listener scope.\n * @return {number} The index of the matching listener within the\n * listenerArray.\n * @private\n */\ngoog.events.ListenerMap.findListenerIndex_ = function(\n listenerArray, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n for (var i = 0; i < listenerArray.length; ++i) {\n var listenerObj = listenerArray[i];\n if (!listenerObj.removed && listenerObj.listener == listener &&\n listenerObj.capture == !!opt_useCapture &&\n listenerObj.handler == opt_listenerScope) {\n return i;\n }\n }\n return -1;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for manipulating objects/maps/hashes.\n */\ngoog.module('goog.object');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls a function for each element in an object/map/hash.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):?} f The function to call for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and the return value is ignored.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {void}\n * @template T,K,V\n */\nfunction forEach(obj, f, opt_obj) {\n for (const key in obj) {\n f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If that call returns\n * true, adds the element to a new object.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should return a boolean. If the return value is true the\n * element is added to the result object. If it is false the element is not\n * included.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,V>} a new object in which only elements that passed the\n * test are present.\n * @template T,K,V\n */\nfunction filter(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n res[key] = obj[key];\n }\n }\n return res;\n}\n\n/**\n * For every element in an object/map/hash calls a function and inserts the\n * result into a new object.\n * @param {?Object<K,V>} obj The object over which to iterate.\n * @param {function(this:T,V,?,?Object<K,V>):R} f The function to call for every\n * element. This function takes 3 arguments (the value, the key and the\n * object) and should return something. The result will be inserted into a\n * new object.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {!Object<K,R>} a new object with the results from f.\n * @template T,K,V,R\n */\nfunction map(obj, f, opt_obj) {\n const res = {};\n for (const key in obj) {\n res[key] = f.call(/** @type {?} */ (opt_obj), obj[key], key, obj);\n }\n return res;\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If any\n * call returns true, returns true (without checking the rest). If\n * all calls return false, returns false.\n * @param {?Object<K,V>} obj The object to check.\n * @param {function(this:T,V,?,?Object<K,V>):boolean} f The function to call for\n * every element. This function takes 3 arguments (the value, the key and\n * the object) and should return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} true if any element passes the test.\n * @template T,K,V\n */\nfunction some(obj, f, opt_obj) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Calls a function for each element in an object/map/hash. If\n * all calls return true, returns true. If any call returns false, returns\n * false at this point and does not continue to check the remaining elements.\n * @param {?Object<K,V>} obj The object to check.\n * @param {?function(this:T,V,?,?Object<K,V>):boolean} f The function to call\n * for every element. This function takes 3 arguments (the value, the key\n * and the object) and should return a boolean.\n * @param {T=} opt_obj This is used as the 'this' object within f.\n * @return {boolean} false if any element fails the test.\n * @template T,K,V\n */\nfunction every(obj, f, opt_obj) {\n for (const key in obj) {\n if (!f.call(/** @type {?} */ (opt_obj), obj[key], key, obj)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns the number of key-value pairs in the object map.\n * @param {?Object} obj The object for which to get the number of key-value\n * pairs.\n * @return {number} The number of key-value pairs in the object map.\n */\nfunction getCount(obj) {\n let rv = 0;\n for (const key in obj) {\n rv++;\n }\n return rv;\n}\n\n/**\n * Returns one key from the object map, if any exists.\n * For map literals the returned key will be the first one in most of the\n * browsers (a know exception is Konqueror).\n * @param {?Object} obj The object to pick a key from.\n * @return {string|undefined} The key or undefined if the object is empty.\n */\nfunction getAnyKey(obj) {\n for (const key in obj) {\n return key;\n }\n}\n\n/**\n * Returns one value from the object map, if any exists.\n * For map literals the returned value will be the first one in most of the\n * browsers (a know exception is Konqueror).\n * @param {?Object<K,V>} obj The object to pick a value from.\n * @return {V|undefined} The value or undefined if the object is empty.\n * @template K,V\n */\nfunction getAnyValue(obj) {\n for (const key in obj) {\n return obj[key];\n }\n}\n\n/**\n * Whether the object/hash/map contains the given object as a value.\n * An alias for containsValue(obj, val).\n * @param {?Object<K,V>} obj The object in which to look for val.\n * @param {V} val The object for which to check.\n * @return {boolean} true if val is present.\n * @template K,V\n */\nfunction contains(obj, val) {\n return containsValue(obj, val);\n}\n\n/**\n * Returns the values of the object/map/hash.\n * @param {?Object<K,V>} obj The object from which to get the values.\n * @return {!Array<V>} The values in the object/map/hash.\n * @template K,V\n */\nfunction getValues(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = obj[key];\n }\n return res;\n}\n\n/**\n * Returns the keys of the object/map/hash.\n * @param {?Object} obj The object from which to get the keys.\n * @return {!Array<string>} Array of property keys.\n */\nfunction getKeys(obj) {\n const res = [];\n let i = 0;\n for (const key in obj) {\n res[i++] = key;\n }\n return res;\n}\n\n/**\n * Get a value from an object multiple levels deep. This is useful for\n * pulling values from deeply nested objects, such as JSON responses.\n * Example usage: getValueByKeys(jsonObj, 'foo', 'entries', 3)\n * @param {?Object} obj An object to get the value from. Can be array-like.\n * @param {...(string|number|!IArrayLike<number|string>)} var_args A number of\n * keys (as strings, or numbers, for array-like objects). Can also be\n * specified as a single array of keys.\n * @return {*} The resulting value. If, at any point, the value for a key in the\n * current object is null or undefined, returns undefined.\n */\nfunction getValueByKeys(obj, var_args) {\n const isArrayLike = goog.isArrayLike(var_args);\n const keys = isArrayLike ?\n /** @type {!IArrayLike<number|string>} */ (var_args) :\n arguments;\n\n // Start with the 2nd parameter for the variable parameters syntax.\n for (let i = isArrayLike ? 0 : 1; i < keys.length; i++) {\n if (obj == null) return undefined;\n obj = obj[keys[i]];\n }\n\n return obj;\n}\n\n/**\n * Whether the object/map/hash contains the given key.\n * @param {?Object} obj The object in which to look for key.\n * @param {?} key The key for which to check.\n * @return {boolean} true If the map contains the key.\n */\nfunction containsKey(obj, key) {\n return obj !== null && key in obj;\n}\n\n/**\n * Whether the object/map/hash contains the given value. This is O(n).\n * @param {?Object<K,V>} obj The object in which to look for val.\n * @param {V} val The value for which to check.\n * @return {boolean} true If the map contains the value.\n * @template K,V\n */\nfunction containsValue(obj, val) {\n for (const key in obj) {\n if (obj[key] == val) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its key.\n * @param {?Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,?Object<K,V>):boolean} f The function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj An optional \"this\" context for the function.\n * @return {string|undefined} The key of an element for which the function\n * returns true or undefined if no such element is found.\n * @template T,K,V\n */\nfunction findKey(obj, f, thisObj = undefined) {\n for (const key in obj) {\n if (f.call(/** @type {?} */ (thisObj), obj[key], key, obj)) {\n return key;\n }\n }\n return undefined;\n}\n\n/**\n * Searches an object for an element that satisfies the given condition and\n * returns its value.\n * @param {?Object<K,V>} obj The object to search in.\n * @param {function(this:T,V,string,?Object<K,V>):boolean} f The function to\n * call for every element. Takes 3 arguments (the value, the key and the\n * object) and should return a boolean.\n * @param {T=} thisObj An optional \"this\" context for the function.\n * @return {V} The value of an element for which the function returns true or\n * undefined if no such element is found.\n * @template T,K,V\n */\nfunction findValue(obj, f, thisObj = undefined) {\n const key = findKey(obj, f, thisObj);\n return key && obj[key];\n}\n\n/**\n * Whether the object/map/hash is empty.\n * @param {?Object} obj The object to test.\n * @return {boolean} true if obj is empty.\n */\nfunction isEmpty(obj) {\n for (const key in obj) {\n return false;\n }\n return true;\n}\n\n/**\n * Removes all key value pairs from the object/map/hash.\n * @param {?Object} obj The object to clear.\n * @return {void}\n */\nfunction clear(obj) {\n for (const i in obj) {\n delete obj[i];\n }\n}\n\n/**\n * Removes a key-value pair based on the key.\n * @param {?Object} obj The object from which to remove the key.\n * @param {?} key The key to remove.\n * @return {boolean} Whether an element was removed.\n */\nfunction remove(obj, key) {\n let rv;\n if (rv = key in /** @type {!Object} */ (obj)) {\n delete obj[key];\n }\n return rv;\n}\n\n/**\n * Adds a key-value pair to the object. Throws an exception if the key is\n * already in use. Use set if you want to change an existing pair.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} val The value to add.\n * @return {void}\n * @template K,V\n */\nfunction add(obj, key, val) {\n if (obj !== null && key in obj) {\n throw new Error(`The object already contains the key \"${key}\"`);\n }\n set(obj, key, val);\n}\n\n/**\n * Returns the value for the given key.\n * @param {?Object<K,V>} obj The object from which to get the value.\n * @param {string} key The key for which to get the value.\n * @param {R=} val The value to return if no item is found for the given key\n * (default is undefined).\n * @return {V|R|undefined} The value for the given key.\n * @template K,V,R\n */\nfunction get(obj, key, val = undefined) {\n if (obj !== null && key in obj) {\n return obj[key];\n }\n return val;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add.\n * @template K,V\n * @return {void}\n */\nfunction set(obj, key, value) {\n obj[key] = value;\n}\n\n/**\n * Adds a key-value pair to the object/map/hash if it doesn't exist yet.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {V} value The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\nfunction setIfUndefined(obj, key, value) {\n return key in /** @type {!Object} */ (obj) ? obj[key] : (obj[key] = value);\n}\n\n/**\n * Sets a key and value to an object if the key is not set. The value will be\n * the return value of the given function. If the key already exists, the\n * object will not be changed and the function will not be called (the function\n * will be lazily evaluated -- only called if necessary).\n * This function is particularly useful when used with an `Object` which is\n * acting as a cache.\n * @param {?Object<K,V>} obj The object to which to add the key-value pair.\n * @param {string} key The key to add.\n * @param {function():V} f The value to add if the key wasn't present.\n * @return {V} The value of the entry at the end of the function.\n * @template K,V\n */\nfunction setWithReturnValueIfNotSet(obj, key, f) {\n if (key in obj) {\n return obj[key];\n }\n\n const val = f();\n obj[key] = val;\n return val;\n}\n\n/**\n * Compares two objects for equality using === on the values.\n * @param {!Object<K,V>} a\n * @param {!Object<K,V>} b\n * @return {boolean}\n * @template K,V\n */\nfunction equals(a, b) {\n for (const k in a) {\n if (!(k in b) || a[k] !== b[k]) {\n return false;\n }\n }\n for (const k in b) {\n if (!(k in a)) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Returns a shallow clone of the object.\n * @param {?Object<K,V>} obj Object to clone.\n * @return {!Object<K,V>} Clone of the input object.\n * @template K,V\n */\nfunction clone(obj) {\n const res = {};\n for (const key in obj) {\n res[key] = obj[key];\n }\n return res;\n}\n\n/**\n * Clones a value. The input may be an Object, Array, or basic type. Objects and\n * arrays will be cloned recursively.\n * WARNINGS:\n * <code>unsafeClone</code> does not detect reference loops. Objects\n * that refer to themselves will cause infinite recursion.\n * <code>unsafeClone</code> is unaware of unique identifiers, and\n * copies UIDs created by <code>getUid</code> into cloned results.\n * @param {T} obj The value to clone.\n * @return {T} A clone of the input value.\n * @template T\n */\nfunction unsafeClone(obj) {\n if (!obj || typeof obj !== 'object') return obj;\n if (typeof obj.clone === 'function') return obj.clone();\n if (typeof Map !== 'undefined' && obj instanceof Map) {\n return new Map(obj);\n } else if (typeof Set !== 'undefined' && obj instanceof Set) {\n return new Set(obj);\n }\n const clone = Array.isArray(obj) ? [] :\n typeof ArrayBuffer === 'function' &&\n typeof ArrayBuffer.isView === 'function' && ArrayBuffer.isView(obj) &&\n !(obj instanceof DataView) ?\n new obj.constructor(obj.length) :\n {};\n for (const key in obj) {\n clone[key] = unsafeClone(obj[key]);\n }\n return clone;\n}\n\n/**\n * Returns a new object in which all the keys and values are interchanged\n * (keys become values and values become keys). If multiple keys map to the\n * same value, the chosen transposed value is implementation-dependent.\n * @param {?Object} obj The object to transpose.\n * @return {!Object} The transposed object.\n */\nfunction transpose(obj) {\n const transposed = {};\n for (const key in obj) {\n transposed[obj[key]] = key;\n }\n return transposed;\n}\n\n/**\n * The names of the fields that are defined on Object.prototype.\n * @type {!Array<string>}\n */\nconst PROTOTYPE_FIELDS = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf',\n];\n\n/**\n * Extends an object with another object.\n * This operates 'in-place'; it does not create a new Object.\n * Example:\n * var o = {};\n * extend(o, {a: 0, b: 1});\n * o; // {a: 0, b: 1}\n * extend(o, {b: 2, c: 3});\n * o; // {a: 0, b: 2, c: 3}\n * @param {?Object} target The object to modify. Existing properties will be\n * overwritten if they are also present in one of the objects in `var_args`.\n * @param {...(?Object|undefined)} var_args The objects from which values\n * will be copied.\n * @return {void}\n * @deprecated Prefer Object.assign\n */\nfunction extend(target, var_args) {\n let key;\n let source;\n for (let i = 1; i < arguments.length; i++) {\n source = arguments[i];\n for (key in source) {\n target[key] = source[key];\n }\n\n // For IE the for-in-loop does not contain any properties that are not\n // enumerable on the prototype object (for example isPrototypeOf from\n // Object.prototype) and it will also not include 'replace' on objects that\n // extend String and change 'replace' (not that it is common for anyone to\n // extend anything except Object).\n\n for (let j = 0; j < PROTOTYPE_FIELDS.length; j++) {\n key = PROTOTYPE_FIELDS[j];\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n}\n\n/**\n * Creates a new object built from the key-value pairs provided as arguments.\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise even arguments are used as\n * the property names and odd arguments are used as the property values.\n * @return {!Object} The new object.\n * @throws {!Error} If there are uneven number of arguments or there is only one\n * non array argument.\n */\nfunction create(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return create.apply(null, arguments[0]);\n }\n\n if (argLength % 2) {\n throw new Error('Uneven number of arguments');\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i += 2) {\n rv[arguments[i]] = arguments[i + 1];\n }\n return rv;\n}\n\n/**\n * Creates a new object where the property names come from the arguments but\n * the value is always set to true\n * @param {...*} var_args If only one argument is provided and it is an array\n * then this is used as the arguments, otherwise the arguments are used as\n * the property names.\n * @return {!Object} The new object.\n */\nfunction createSet(var_args) {\n const argLength = arguments.length;\n if (argLength == 1 && Array.isArray(arguments[0])) {\n return createSet.apply(null, arguments[0]);\n }\n\n const rv = {};\n for (let i = 0; i < argLength; i++) {\n rv[arguments[i]] = true;\n }\n return rv;\n}\n\n/**\n * Creates an immutable view of the underlying object, if the browser\n * supports immutable objects.\n * In default mode, writes to this view will fail silently. In strict mode,\n * they will throw an error.\n * @param {!Object<K,V>} obj An object.\n * @return {!Object<K,V>} An immutable view of that object, or the original\n * object if this browser does not support immutables.\n * @template K,V\n */\nfunction createImmutableView(obj) {\n let result = obj;\n if (Object.isFrozen && !Object.isFrozen(obj)) {\n result = Object.create(obj);\n Object.freeze(result);\n }\n return result;\n}\n\n/**\n * @param {!Object} obj An object.\n * @return {boolean} Whether this is an immutable view of the object.\n */\nfunction isImmutableView(obj) {\n return !!Object.isFrozen && Object.isFrozen(obj);\n}\n\n/**\n * Get all properties names on a given Object regardless of enumerability.\n * <p> If the browser does not support `Object.getOwnPropertyNames` nor\n * `Object.getPrototypeOf` then this is equivalent to using\n * `getKeys`\n * @param {?Object} obj The object to get the properties of.\n * @param {boolean=} includeObjectPrototype Whether properties defined on\n * `Object.prototype` should be included in the result.\n * @param {boolean=} includeFunctionPrototype Whether properties defined on\n * `Function.prototype` should be included in the result.\n * @return {!Array<string>}\n * @public\n */\nfunction getAllPropertyNames(\n obj, includeObjectPrototype = undefined,\n includeFunctionPrototype = undefined) {\n if (!obj) {\n return [];\n }\n\n // Naively use a for..in loop to get the property names if the browser doesn't\n // support any other APIs for getting it.\n if (!Object.getOwnPropertyNames || !Object.getPrototypeOf) {\n return getKeys(obj);\n }\n\n const visitedSet = {};\n\n // Traverse the prototype chain and add all properties to the visited set.\n let proto = obj;\n while (proto && (proto !== Object.prototype || !!includeObjectPrototype) &&\n (proto !== Function.prototype || !!includeFunctionPrototype)) {\n const names = Object.getOwnPropertyNames(proto);\n for (let i = 0; i < names.length; i++) {\n visitedSet[names[i]] = true;\n }\n proto = Object.getPrototypeOf(proto);\n }\n\n return getKeys(visitedSet);\n}\n\n/**\n * Given a ES5 or ES6 class reference, return its super class / super\n * constructor.\n * This should be used in rare cases where you need to walk up the inheritance\n * tree (this is generally a bad idea). But this work with ES5 and ES6 classes,\n * unlike relying on the superClass_ property.\n * Note: To start walking up the hierarchy from an instance call this with its\n * `constructor` property; e.g. `getSuperClass(instance.constructor)`.\n * @param {function(new: ?)} constructor\n * @return {?Object}\n */\nfunction getSuperClass(constructor) {\n const proto = Object.getPrototypeOf(constructor.prototype);\n return proto && proto.constructor;\n}\n\nexports = {\n add,\n clear,\n clone,\n contains,\n containsKey,\n containsValue,\n create,\n createImmutableView,\n createSet,\n equals,\n every,\n extend,\n filter,\n findKey,\n findValue,\n forEach,\n get,\n getAllPropertyNames,\n getAnyKey,\n getAnyValue,\n getCount,\n getKeys,\n getSuperClass,\n getValueByKeys,\n getValues,\n isEmpty,\n isImmutableView,\n map,\n remove,\n set,\n setIfUndefined,\n setWithReturnValueIfNotSet,\n some,\n transpose,\n unsafeClone,\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview An event manager for both native browser event\n * targets and custom JavaScript event targets\n * (`goog.events.Listenable`). This provides an abstraction\n * over browsers' event systems.\n *\n * It also provides a simulation of W3C event model's capture phase in\n * Internet Explorer (IE 8 and below). Caveat: the simulation does not\n * interact well with listeners registered directly on the elements\n * (bypassing goog.events) or even with listeners registered via\n * goog.events in a separate JS binary. In these cases, we provide\n * no ordering guarantees.\n *\n * The listeners will receive a \"patched\" event object. Such event object\n * contains normalized values for certain event properties that differs in\n * different browsers.\n *\n * Example usage:\n * <pre>\n * goog.events.listen(myNode, 'click', function(e) { alert('woo') });\n * goog.events.listen(myNode, 'mouseover', mouseHandler, true);\n * goog.events.unlisten(myNode, 'mouseover', mouseHandler, true);\n * goog.events.removeAll(myNode);\n * </pre>\n *\n * in IE and event object patching]\n *\n * @see ../demos/events.html\n * @see ../demos/event-propagation.html\n * @see ../demos/stopevent.html\n */\n\n// IMPLEMENTATION NOTES:\n// goog.events stores an auxiliary data structure on each EventTarget\n// source being listened on. This allows us to take advantage of GC,\n// having the data structure GC'd when the EventTarget is GC'd. This\n// GC behavior is equivalent to using W3C DOM Events directly.\n\ngoog.provide('goog.events');\ngoog.provide('goog.events.CaptureSimulationMode');\ngoog.provide('goog.events.Key');\ngoog.provide('goog.events.ListenableType');\n\ngoog.require('goog.asserts');\ngoog.require('goog.debug.entryPointRegistry');\ngoog.require('goog.events.BrowserEvent');\ngoog.require('goog.events.BrowserFeature');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.requireType('goog.debug.ErrorHandler');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.EventWrapper');\ngoog.requireType('goog.events.ListenableKey');\ngoog.requireType('goog.events.Listener');\n\n\n/**\n * @typedef {number|goog.events.ListenableKey}\n */\ngoog.events.Key;\n\n\n/**\n * @typedef {EventTarget|goog.events.Listenable}\n */\ngoog.events.ListenableType;\n\n\n/**\n * Property name on a native event target for the listener map\n * associated with the event target.\n * @private @const {string}\n */\ngoog.events.LISTENER_MAP_PROP_ = 'closure_lm_' + ((Math.random() * 1e6) | 0);\n\n\n/**\n * String used to prepend to IE event types.\n * @const\n * @private\n */\ngoog.events.onString_ = 'on';\n\n\n/**\n * Map of computed \"on<eventname>\" strings for IE event types. Caching\n * this removes an extra object allocation in goog.events.listen which\n * improves IE6 performance.\n * @const\n * @dict\n * @private\n */\ngoog.events.onStringMap_ = {};\n\n\n/**\n * @enum {number} Different capture simulation mode for IE8-.\n */\ngoog.events.CaptureSimulationMode = {\n /**\n * Does not perform capture simulation. Will asserts in IE8- when you\n * add capture listeners.\n */\n OFF_AND_FAIL: 0,\n\n /**\n * Does not perform capture simulation, silently ignore capture\n * listeners.\n */\n OFF_AND_SILENT: 1,\n\n /**\n * Performs capture simulation.\n */\n ON: 2\n};\n\n\n/**\n * @define {number} The capture simulation mode for IE8-. By default,\n * this is ON.\n */\ngoog.events.CAPTURE_SIMULATION_MODE =\n goog.define('goog.events.CAPTURE_SIMULATION_MODE', 2);\n\n\n/**\n * Estimated count of total native listeners.\n * @private {number}\n */\ngoog.events.listenerCountEstimate_ = 0;\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. A listener can only be added once\n * to an object and if it is added again the key for the listener is\n * returned. Note that if the existing listener is a one-off listener\n * (registered via listenOnce), it will no longer be a one-off\n * listener after a call to listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method, or an object with a handleEvent function.\n * WARNING: passing an Object is now softly deprecated.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n */\ngoog.events.listen = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (opt_options && opt_options.once) {\n return goog.events.listenOnce(\n src, type, listener, opt_options, opt_handler);\n }\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listen(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listen(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ false, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target. A listener can only be added once to an object and if it\n * is added again the key for the listener is returned.\n *\n * Note that a one-off listener will not change an existing listener,\n * if any. On the other hand a normal listener will change existing\n * one-off listener to become a normal listener.\n *\n * @param {EventTarget} src The node to listen to events on.\n * @param {string|?goog.events.EventId<EVENTOBJ>} type Event type.\n * @param {!Function} listener Callback function.\n * @param {boolean} callOnce Whether the listener is a one-off\n * listener or otherwise.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} Unique key for the listener.\n * @template EVENTOBJ\n * @private\n */\ngoog.events.listen_ = function(\n src, type, listener, callOnce, opt_options, opt_handler) {\n 'use strict';\n if (!type) {\n throw new Error('Invalid event type');\n }\n\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n var listenerMap = goog.events.getListenerMap_(src);\n if (!listenerMap) {\n src[goog.events.LISTENER_MAP_PROP_] = listenerMap =\n new goog.events.ListenerMap(src);\n }\n\n var listenerObj = /** @type {goog.events.Listener} */ (\n listenerMap.add(type, listener, callOnce, capture, opt_handler));\n\n // If the listenerObj already has a proxy, it has been set up\n // previously. We simply return.\n if (listenerObj.proxy) {\n return listenerObj;\n }\n\n var proxy = goog.events.getProxy();\n listenerObj.proxy = proxy;\n\n proxy.src = src;\n proxy.listener = listenerObj;\n\n // Attach the proxy through the browser's API\n if (src.addEventListener) {\n // Don't pass an object as `capture` if the browser doesn't support that.\n if (!goog.events.BrowserFeature.PASSIVE_EVENTS) {\n opt_options = capture;\n }\n // Don't break tests that expect a boolean.\n if (opt_options === undefined) opt_options = false;\n src.addEventListener(type.toString(), proxy, opt_options);\n } else if (src.attachEvent) {\n // The else if above used to be an unconditional else. It would call\n // attachEvent come gws or high water. This would sometimes throw an\n // exception on IE11, spoiling the day of some callers. The previous\n // incarnation of this code, from 2007, indicates that it replaced an\n // earlier still version that caused excess allocations on IE6.\n src.attachEvent(goog.events.getOnString_(type.toString()), proxy);\n } else if (src.addListener && src.removeListener) {\n // In IE, MediaQueryList uses addListener() insteadd of addEventListener. In\n // Safari, there is no global for the MediaQueryList constructor, so we just\n // check whether the object \"looks like\" MediaQueryList.\n goog.asserts.assert(\n type === 'change', 'MediaQueryList only has a change event');\n src.addListener(proxy);\n } else {\n throw new Error('addEventListener and attachEvent are unavailable.');\n }\n\n goog.events.listenerCountEstimate_++;\n return listenerObj;\n};\n\n\n/**\n * Helper function for returning a proxy function.\n * @return {!Function} A new or reused function object.\n */\ngoog.events.getProxy = function() {\n 'use strict';\n const proxyCallbackFunction = goog.events.handleBrowserEvent_;\n const f = function(eventObject) {\n return proxyCallbackFunction.call(f.src, f.listener, eventObject);\n };\n return f;\n};\n\n\n/**\n * Adds an event listener for a specific event on a native event\n * target (such as a DOM element) or an object that has implemented\n * {@link goog.events.Listenable}. After the event has fired the event\n * listener is removed from the target.\n *\n * If an existing listener already exists, listenOnce will do\n * nothing. In particular, if the listener was previously registered\n * via listen(), listenOnce() will not turn the listener into a\n * one-off listener. Similarly, if there is already an existing\n * one-off listener, listenOnce does not modify the listeners (it is\n * still a once listener).\n *\n * @param {EventTarget|goog.events.Listenable} src The node to listen\n * to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(?):?}|null}\n * listener Callback method.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.Key} Unique key for the listener.\n * @template T,EVENTOBJ\n */\ngoog.events.listenOnce = function(\n src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.listenOnce(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n return src.listenOnce(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n } else {\n return goog.events.listen_(\n /** @type {!EventTarget} */ (src), type, listener,\n /* callOnce */ true, opt_options, opt_handler);\n }\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.Listenable}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.Listenable} src The target to\n * listen to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {T=} opt_handler Element in whose scope to call the listener.\n * @template T\n */\ngoog.events.listenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\n wrapper.listen(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes an event listener which was added with listen().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {?boolean} indicating whether the listener was there to remove.\n * @template EVENTOBJ\n */\ngoog.events.unlisten = function(src, type, listener, opt_options, opt_handler) {\n 'use strict';\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n goog.events.unlisten(src, type[i], listener, opt_options, opt_handler);\n }\n return null;\n }\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n\n listener = goog.events.wrapListener(listener);\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.unlisten(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return false;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n var listenerObj = listenerMap.getListener(\n /** @type {string|!goog.events.EventId} */ (type), listener, capture,\n opt_handler);\n if (listenerObj) {\n return goog.events.unlistenByKey(listenerObj);\n }\n }\n\n return false;\n};\n\n\n/**\n * Removes an event listener which was added with listen() by the key\n * returned by listen().\n *\n * @param {goog.events.Key} key The key returned by listen() for this\n * event listener.\n * @return {boolean} indicating whether the listener was there to remove.\n */\ngoog.events.unlistenByKey = function(key) {\n 'use strict';\n // TODO(chrishenry): Remove this check when tests that rely on this\n // are fixed.\n if (typeof key === 'number') {\n return false;\n }\n\n var listener = key;\n if (!listener || listener.removed) {\n return false;\n }\n\n var src = listener.src;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return /** @type {!goog.events.Listenable} */ (src).unlistenByKey(listener);\n }\n\n var type = listener.type;\n var proxy = listener.proxy;\n if (src.removeEventListener) {\n src.removeEventListener(type, proxy, listener.capture);\n } else if (src.detachEvent) {\n src.detachEvent(goog.events.getOnString_(type), proxy);\n } else if (src.addListener && src.removeListener) {\n src.removeListener(proxy);\n }\n goog.events.listenerCountEstimate_--;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n // TODO(chrishenry): Try to remove this conditional and execute the\n // first branch always. This should be safe.\n if (listenerMap) {\n listenerMap.removeByKey(listener);\n if (listenerMap.getTypeCount() == 0) {\n // Null the src, just because this is simple to do (and useful\n // for IE <= 7).\n listenerMap.src = null;\n // We don't use delete here because IE does not allow delete\n // on a window object.\n src[goog.events.LISTENER_MAP_PROP_] = null;\n }\n } else {\n /** @type {!goog.events.Listener} */ (listener).markAsRemoved();\n }\n\n return true;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.Listenable} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n */\ngoog.events.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_handler) {\n 'use strict';\n wrapper.unlisten(src, listener, opt_capt, opt_handler);\n};\n\n\n/**\n * Removes all listeners from an object. You can also optionally\n * remove listeners of a particular type.\n *\n * @param {Object|undefined} obj Object to remove listeners from. Must be an\n * EventTarget or a goog.events.Listenable.\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove.\n * Default is all types.\n * @return {number} Number of listeners removed.\n */\ngoog.events.removeAll = function(obj, opt_type) {\n 'use strict';\n // TODO(chrishenry): Change the type of obj to\n // (!EventTarget|!goog.events.Listenable).\n\n if (!obj) {\n return 0;\n }\n\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {?} */ (obj).removeAllListeners(opt_type);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n if (!listenerMap) {\n return 0;\n }\n\n var count = 0;\n var typeStr = opt_type && opt_type.toString();\n for (var type in listenerMap.listeners) {\n if (!typeStr || type == typeStr) {\n // Clone so that we don't need to worry about unlistenByKey\n // changing the content of the ListenerMap.\n var listeners = listenerMap.listeners[type].concat();\n for (var i = 0; i < listeners.length; ++i) {\n if (goog.events.unlistenByKey(listeners[i])) {\n ++count;\n }\n }\n }\n }\n return count;\n};\n\n\n/**\n * Gets the listeners for a given object, type and capture phase.\n *\n * @param {Object} obj Object to get listeners for.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Capture phase?.\n * @return {!Array<!goog.events.Listener>} Array of listener objects.\n */\ngoog.events.getListeners = function(obj, type, capture) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).getListeners(\n type, capture);\n } else {\n if (!obj) {\n // TODO(chrishenry): We should tighten the API to accept\n // !EventTarget|goog.events.Listenable, and add an assertion here.\n return [];\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return listenerMap ? listenerMap.getListeners(type, capture) : [];\n }\n};\n\n\n/**\n * Gets the goog.events.Listener for the event or null if no such listener is\n * in use.\n *\n * @param {EventTarget|goog.events.Listenable} src The target from\n * which to get listeners.\n * @param {?string|!goog.events.EventId<EVENTOBJ>} type The type of the event.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null} listener The\n * listener function to get.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the\n * capture or bubble phase of the event.\n * @param {Object=} opt_handler Element in whose scope to call the listener.\n * @return {goog.events.ListenableKey} the found listener or null if not found.\n * @template EVENTOBJ\n */\ngoog.events.getListener = function(src, type, listener, opt_capt, opt_handler) {\n 'use strict';\n // TODO(chrishenry): Change type from ?string to string, or add assertion.\n type = /** @type {string} */ (type);\n listener = goog.events.wrapListener(listener);\n var capture = !!opt_capt;\n if (goog.events.Listenable.isImplementedBy(src)) {\n return src.getListener(type, listener, capture, opt_handler);\n }\n\n if (!src) {\n // TODO(chrishenry): We should tighten the API to only accept\n // non-null objects, or add an assertion here.\n return null;\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (src));\n if (listenerMap) {\n return listenerMap.getListener(type, listener, capture, opt_handler);\n }\n return null;\n};\n\n\n/**\n * Returns whether an event target has any active listeners matching the\n * specified signature. If either the type or capture parameters are\n * unspecified, the function will match on the remaining criteria.\n *\n * @param {EventTarget|goog.events.Listenable} obj Target to get\n * listeners for.\n * @param {string|!goog.events.EventId=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble-phase\n * listeners.\n * @return {boolean} Whether an event target has one or more listeners matching\n * the requested type and/or capture phase.\n */\ngoog.events.hasListener = function(obj, opt_type, opt_capture) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return obj.hasListener(opt_type, opt_capture);\n }\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {!EventTarget} */ (obj));\n return !!listenerMap && listenerMap.hasListener(opt_type, opt_capture);\n};\n\n\n/**\n * Provides a nice string showing the normalized event objects public members\n * @param {Object} e Event Object.\n * @return {string} String of the public members of the normalized event object.\n */\ngoog.events.expose = function(e) {\n 'use strict';\n var str = [];\n for (var key in e) {\n if (e[key] && e[key].id) {\n str.push(key + ' = ' + e[key] + ' (' + e[key].id + ')');\n } else {\n str.push(key + ' = ' + e[key]);\n }\n }\n return str.join('\\n');\n};\n\n\n/**\n * Returns a string with on prepended to the specified type. This is used for IE\n * which expects \"on\" to be prepended. This function caches the string in order\n * to avoid extra allocations in steady state.\n * @param {string} type Event type.\n * @return {string} The type string with 'on' prepended.\n * @private\n */\ngoog.events.getOnString_ = function(type) {\n 'use strict';\n if (type in goog.events.onStringMap_) {\n return goog.events.onStringMap_[type];\n }\n return goog.events.onStringMap_[type] = goog.events.onString_ + type;\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase\n *\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n */\ngoog.events.fireListeners = function(obj, type, capture, eventObject) {\n 'use strict';\n if (goog.events.Listenable.isImplementedBy(obj)) {\n return /** @type {!goog.events.Listenable} */ (obj).fireListeners(\n type, capture, eventObject);\n }\n\n return goog.events.fireListeners_(obj, type, capture, eventObject);\n};\n\n\n/**\n * Fires an object's listeners of a particular type and phase.\n * @param {Object} obj Object whose listeners to call.\n * @param {string|!goog.events.EventId} type Event type.\n * @param {boolean} capture Which event phase.\n * @param {Object} eventObject Event object to be passed to listener.\n * @return {boolean} True if all listeners returned true else false.\n * @private\n */\ngoog.events.fireListeners_ = function(obj, type, capture, eventObject) {\n 'use strict';\n /** @type {boolean} */\n var retval = true;\n\n var listenerMap = goog.events.getListenerMap_(\n /** @type {EventTarget} */ (obj));\n if (listenerMap) {\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // listenerMap.getListeners(type, capture) instead, which is simpler.\n var listenerArray = listenerMap.listeners[type.toString()];\n if (listenerArray) {\n listenerArray = listenerArray.concat();\n for (var i = 0; i < listenerArray.length; i++) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && listener.capture == capture && !listener.removed) {\n var result = goog.events.fireListener(listener, eventObject);\n retval = retval && (result !== false);\n }\n }\n }\n }\n return retval;\n};\n\n\n/**\n * Fires a listener with a set of arguments\n *\n * @param {goog.events.Listener} listener The listener object to call.\n * @param {Object} eventObject The event object to pass to the listener.\n * @return {*} Result of listener.\n */\ngoog.events.fireListener = function(listener, eventObject) {\n 'use strict';\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n goog.events.unlistenByKey(listener);\n }\n return listenerFn.call(listenerHandler, eventObject);\n};\n\n\n/**\n * Gets the total number of listeners currently in the system.\n * @return {number} Number of listeners.\n * @deprecated This returns estimated count, now that Closure no longer\n * stores a central listener registry. We still return an estimation\n * to keep existing listener-related tests passing. In the near future,\n * this function will be removed.\n */\ngoog.events.getTotalListenerCount = function() {\n 'use strict';\n return goog.events.listenerCountEstimate_;\n};\n\n\n/**\n * Dispatches an event (or event like object) and calls all listeners\n * listening for events of this type. The type of the event is decided by the\n * type property on the event object.\n *\n * If any of the listeners returns false OR calls preventDefault then this\n * function will return false. If one of the capture listeners calls\n * stopPropagation, then the bubble listeners won't fire.\n *\n * @param {goog.events.Listenable} src The event target.\n * @param {goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the handlers returns false) this will also return false.\n * If there are no handlers, or if all handlers return true, this returns\n * true.\n */\ngoog.events.dispatchEvent = function(src, e) {\n 'use strict';\n goog.asserts.assert(\n goog.events.Listenable.isImplementedBy(src),\n 'Can not use goog.events.dispatchEvent with ' +\n 'non-goog.events.Listenable instance.');\n return src.dispatchEvent(e);\n};\n\n\n/**\n * Installs exception protection for the browser event entry point using the\n * given error handler.\n *\n * @param {goog.debug.ErrorHandler} errorHandler Error handler with which to\n * protect the entry point.\n */\ngoog.events.protectBrowserEventEntryPoint = function(errorHandler) {\n 'use strict';\n goog.events.handleBrowserEvent_ =\n errorHandler.protectEntryPoint(goog.events.handleBrowserEvent_);\n};\n\n\n/**\n * Handles an event and dispatches it to the correct listeners. This\n * function is a proxy for the real listener the user specified.\n *\n * @param {goog.events.Listener} listener The listener object.\n * @param {Event=} opt_evt Optional event object that gets passed in via the\n * native event handlers.\n * @return {*} Result of the event handler.\n * @this {EventTarget} The object or Element that fired the event.\n * @private\n */\ngoog.events.handleBrowserEvent_ = function(listener, opt_evt) {\n 'use strict';\n if (listener.removed) {\n return true;\n }\n\n // Otherwise, simply fire the listener.\n return goog.events.fireListener(\n listener, new goog.events.BrowserEvent(opt_evt, this));\n};\n\n\n/**\n * This is used to mark the IE event object so we do not do the Closure pass\n * twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @private\n */\ngoog.events.markIeEvent_ = function(e) {\n 'use strict';\n // Only the keyCode and the returnValue can be changed. We use keyCode for\n // non keyboard events.\n // event.returnValue is a bit more tricky. It is undefined by default. A\n // boolean false prevents the default action. In a window.onbeforeunload and\n // the returnValue is non undefined it will be alerted. However, we will only\n // modify the returnValue for keyboard events. We can get a problem if non\n // closure events sets the keyCode or the returnValue\n\n var useReturnValue = false;\n\n if (e.keyCode == 0) {\n // We cannot change the keyCode in case that srcElement is input[type=file].\n // We could test that that is the case but that would allocate 3 objects.\n // If we use try/catch we will only allocate extra objects in the case of a\n // failure.\n\n try {\n e.keyCode = -1;\n return;\n } catch (ex) {\n useReturnValue = true;\n }\n }\n\n if (useReturnValue ||\n /** @type {boolean|undefined} */ (e.returnValue) == undefined) {\n e.returnValue = true;\n }\n};\n\n\n/**\n * This is used to check if an IE event has already been handled by the Closure\n * system so we do not do the Closure pass twice for a bubbling event.\n * @param {Event} e The IE browser event.\n * @return {boolean} True if the event object has been marked.\n * @private\n */\ngoog.events.isMarkedIeEvent_ = function(e) {\n 'use strict';\n return e.keyCode < 0 || e.returnValue != undefined;\n};\n\n\n/**\n * Counter to create unique event ids.\n * @private {number}\n */\ngoog.events.uniqueIdCounter_ = 0;\n\n\n/**\n * Creates a unique event id.\n *\n * @param {string} identifier The identifier.\n * @return {string} A unique identifier.\n * @idGenerator {unique}\n */\ngoog.events.getUniqueId = function(identifier) {\n 'use strict';\n return identifier + '_' + goog.events.uniqueIdCounter_++;\n};\n\n\n/**\n * @param {EventTarget} src The source object.\n * @return {goog.events.ListenerMap} A listener map for the given\n * source object, or null if none exists.\n * @private\n */\ngoog.events.getListenerMap_ = function(src) {\n 'use strict';\n var listenerMap = src[goog.events.LISTENER_MAP_PROP_];\n // IE serializes the property as well (e.g. when serializing outer\n // HTML). So we must check that the value is of the correct type.\n return listenerMap instanceof goog.events.ListenerMap ? listenerMap : null;\n};\n\n\n/**\n * Expando property for listener function wrapper for Object with\n * handleEvent.\n * @private @const {string}\n */\ngoog.events.LISTENER_WRAPPER_PROP_ =\n '__closure_events_fn_' + ((Math.random() * 1e9) >>> 0);\n\n\n/**\n * @param {Object|Function} listener The listener function or an\n * object that contains handleEvent method.\n * @return {!Function} Either the original function or a function that\n * calls obj.handleEvent. If the same listener is passed to this\n * function more than once, the same function is guaranteed to be\n * returned.\n */\ngoog.events.wrapListener = function(listener) {\n 'use strict';\n goog.asserts.assert(listener, 'Listener can not be null.');\n\n if (typeof listener === 'function') {\n return listener;\n }\n\n goog.asserts.assert(\n listener.handleEvent, 'An object listener must have handleEvent method.');\n if (!listener[goog.events.LISTENER_WRAPPER_PROP_]) {\n listener[goog.events.LISTENER_WRAPPER_PROP_] = function(e) {\n 'use strict';\n return /** @type {?} */ (listener).handleEvent(e);\n };\n }\n return listener[goog.events.LISTENER_WRAPPER_PROP_];\n};\n\n\n// Register the browser event handler as an entry point, so that\n// it can be monitored for exception handling, etc.\ngoog.debug.entryPointRegistry.register(\n /**\n * @param {function(!Function): !Function} transformer The transforming\n * function.\n */\n function(transformer) {\n 'use strict';\n goog.events.handleBrowserEvent_ =\n transformer(goog.events.handleBrowserEvent_);\n });\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A disposable implementation of a custom\n * listenable/event target. See also: documentation for\n * `goog.events.Listenable`.\n *\n * @see ../demos/eventtarget.html\n * @see goog.events.Listenable\n */\n\ngoog.provide('goog.events.EventTarget');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.asserts');\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.events.ListenerMap');\ngoog.require('goog.object');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventLike');\ngoog.requireType('goog.events.ListenableKey');\n\n\n\n/**\n * An implementation of `goog.events.Listenable` with full W3C\n * EventTarget-like support (capture/bubble mechanism, stopping event\n * propagation, preventing default actions).\n *\n * You may subclass this class to turn your class into a Listenable.\n *\n * Unless propagation is stopped, an event dispatched by an\n * EventTarget will bubble to the parent returned by\n * `getParentEventTarget`. To set the parent, call\n * `setParentEventTarget`. Subclasses that don't support\n * changing the parent can override the setter to throw an error.\n *\n * Example usage:\n * <pre>\n * var source = new goog.events.EventTarget();\n * function handleEvent(e) {\n * alert('Type: ' + e.type + '; Target: ' + e.target);\n * }\n * source.listen('foo', handleEvent);\n * // Or: goog.events.listen(source, 'foo', handleEvent);\n * ...\n * source.dispatchEvent('foo'); // will call handleEvent\n * ...\n * source.unlisten('foo', handleEvent);\n * // Or: goog.events.unlisten(source, 'foo', handleEvent);\n * </pre>\n *\n * @constructor\n * @extends {goog.Disposable}\n * @implements {goog.events.Listenable}\n */\ngoog.events.EventTarget = function() {\n 'use strict';\n goog.Disposable.call(this);\n\n /**\n * Maps of event type to an array of listeners.\n * @private {!goog.events.ListenerMap}\n */\n this.eventTargetListeners_ = new goog.events.ListenerMap(this);\n\n /**\n * The object to use for event.target. Useful when mixing in an\n * EventTarget to another object.\n * @private {!Object}\n */\n this.actualEventTarget_ = this;\n\n /**\n * Parent event target, used during event bubbling.\n *\n * TODO(chrishenry): Change this to goog.events.Listenable. This\n * currently breaks people who expect getParentEventTarget to return\n * goog.events.EventTarget.\n *\n * @private {?goog.events.EventTarget}\n */\n this.parentEventTarget_ = null;\n};\ngoog.inherits(goog.events.EventTarget, goog.Disposable);\ngoog.events.Listenable.addImplementation(goog.events.EventTarget);\n\n\n/**\n * An artificial cap on the number of ancestors you can have. This is mainly\n * for loop detection.\n * @const {number}\n * @private\n */\ngoog.events.EventTarget.MAX_ANCESTORS_ = 1000;\n\n\n/**\n * Returns the parent of this event target to use for bubbling.\n *\n * @return {goog.events.EventTarget} The parent EventTarget or null if\n * there is no parent.\n * @override\n */\ngoog.events.EventTarget.prototype.getParentEventTarget = function() {\n 'use strict';\n return this.parentEventTarget_;\n};\n\n\n/**\n * Sets the parent of this event target to use for capture/bubble\n * mechanism.\n * @param {goog.events.EventTarget} parent Parent listenable (null if none).\n */\ngoog.events.EventTarget.prototype.setParentEventTarget = function(parent) {\n 'use strict';\n this.parentEventTarget_ = parent;\n};\n\n\n/**\n * Adds an event listener to the event target. The same handler can only be\n * added once per the type. Even if you add the same handler multiple times\n * using the same type then it will only be called once when the event is\n * dispatched.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#listen` instead, when possible. Otherwise, use\n * `goog.events.listen` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.addEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n 'use strict';\n goog.events.listen(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * Removes an event listener from the event target. The handler must be the\n * same object as the one added. If the handler has not been added then\n * nothing is done.\n *\n * @param {string|!goog.events.EventId} type The type of the event to listen for\n * @param {function(?):?|{handleEvent:function(?):?}|null} handler The function\n * to handle the event. The handler can also be an object that implements\n * the handleEvent method which takes the event object as argument.\n * @param {boolean=} opt_capture In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase\n * of the event.\n * @param {Object=} opt_handlerScope Object in whose scope to call\n * the listener.\n * @deprecated Use `#unlisten` instead, when possible. Otherwise, use\n * `goog.events.unlisten` if you are passing Object\n * (instead of Function) as handler.\n */\ngoog.events.EventTarget.prototype.removeEventListener = function(\n type, handler, opt_capture, opt_handlerScope) {\n 'use strict';\n goog.events.unlisten(this, type, handler, opt_capture, opt_handlerScope);\n};\n\n\n/**\n * @param {?goog.events.EventLike} e Event object.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @override\n */\ngoog.events.EventTarget.prototype.dispatchEvent = function(e) {\n 'use strict';\n this.assertInitialized_();\n\n var ancestorsTree, ancestor = this.getParentEventTarget();\n if (ancestor) {\n ancestorsTree = [];\n var ancestorCount = 1;\n for (; ancestor; ancestor = ancestor.getParentEventTarget()) {\n ancestorsTree.push(ancestor);\n goog.asserts.assert(\n (++ancestorCount < goog.events.EventTarget.MAX_ANCESTORS_),\n 'infinite loop');\n }\n }\n\n return goog.events.EventTarget.dispatchEventInternal_(\n this.actualEventTarget_, e, ancestorsTree);\n};\n\n\n/**\n * Removes listeners from this object. Classes that extend EventTarget may\n * need to override this method in order to remove references to DOM Elements\n * and additional listeners.\n * @override\n * @protected\n */\ngoog.events.EventTarget.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventTarget.superClass_.disposeInternal.call(this);\n\n this.removeAllListeners();\n this.parentEventTarget_ = null;\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.listen = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n this.assertInitialized_();\n return this.eventTargetListeners_.add(\n String(type), listener, false /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {!goog.events.ListenableKey} Unique key for the listener.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.listenOnce = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.add(\n String(type), listener, true /* callOnce */, opt_useCapture,\n opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The event type id.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener Callback\n * method.\n * @param {boolean=} opt_useCapture Whether to fire in capture phase\n * (defaults to false).\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call\n * the listener.\n * @return {boolean} Whether any listener was removed.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.unlisten = function(\n type, listener, opt_useCapture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.remove(\n String(type), listener, opt_useCapture, opt_listenerScope);\n};\n\n\n/**\n * @param {!goog.events.ListenableKey} key The key returned by\n * listen() or listenOnce().\n * @return {boolean} Whether any listener was removed.\n * @override\n */\ngoog.events.EventTarget.prototype.unlistenByKey = function(key) {\n 'use strict';\n return this.eventTargetListeners_.removeByKey(key);\n};\n\n\n/**\n * @param {string|!goog.events.EventId=} opt_type Type of event to remove,\n * default is to remove all types.\n * @return {number} Number of listeners removed.\n * @override\n */\ngoog.events.EventTarget.prototype.removeAllListeners = function(opt_type) {\n 'use strict';\n // TODO(chrishenry): Previously, removeAllListeners can be called on\n // uninitialized EventTarget, so we preserve that behavior. We\n // should remove this when usages that rely on that fact are purged.\n if (!this.eventTargetListeners_) {\n return 0;\n }\n return this.eventTargetListeners_.removeAll(opt_type);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The type of the\n * listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @param {EVENTOBJ} eventObject The event object to fire.\n * @return {boolean} Whether all listeners succeeded without\n * attempting to prevent default behavior. If any listener returns\n * false or called goog.events.Event#preventDefault, this returns\n * false.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.fireListeners = function(\n type, capture, eventObject) {\n 'use strict';\n // TODO(chrishenry): Original code avoids array creation when there\n // is no listener, so we do the same. If this optimization turns\n // out to be not required, we can replace this with\n // getListeners(type, capture) instead, which is simpler.\n var listenerArray = this.eventTargetListeners_.listeners[String(type)];\n if (!listenerArray) {\n return true;\n }\n listenerArray = listenerArray.concat();\n\n var rv = true;\n for (var i = 0; i < listenerArray.length; ++i) {\n var listener = listenerArray[i];\n // We might not have a listener if the listener was removed.\n if (listener && !listener.removed && listener.capture == capture) {\n var listenerFn = listener.listener;\n var listenerHandler = listener.handler || listener.src;\n\n if (listener.callOnce) {\n this.unlistenByKey(listener);\n }\n rv = listenerFn.call(listenerHandler, eventObject) !== false && rv;\n }\n }\n\n return rv && !eventObject.defaultPrevented;\n};\n\n\n/**\n * @param {string|!goog.events.EventId} type The type of the listeners to fire.\n * @param {boolean} capture The capture mode of the listeners to fire.\n * @return {!Array<!goog.events.ListenableKey>} An array of registered\n * listeners.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.getListeners = function(type, capture) {\n 'use strict';\n return this.eventTargetListeners_.getListeners(String(type), capture);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>} type The name of the event\n * without the 'on' prefix.\n * @param {function(this:SCOPE, EVENTOBJ):(boolean|undefined)} listener The\n * listener function to get.\n * @param {boolean} capture Whether the listener is a capturing listener.\n * @param {SCOPE=} opt_listenerScope Object in whose scope to call the\n * listener.\n * @return {?goog.events.ListenableKey} the found listener or null if not found.\n * @template SCOPE,EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.getListener = function(\n type, listener, capture, opt_listenerScope) {\n 'use strict';\n return this.eventTargetListeners_.getListener(\n String(type), listener, capture, opt_listenerScope);\n};\n\n\n/**\n * @param {string|!goog.events.EventId<EVENTOBJ>=} opt_type Event type.\n * @param {boolean=} opt_capture Whether to check for capture or bubble\n * listeners.\n * @return {boolean} Whether there is any active listeners matching\n * the requested type and/or capture phase.\n * @template EVENTOBJ\n * @override\n */\ngoog.events.EventTarget.prototype.hasListener = function(\n opt_type, opt_capture) {\n 'use strict';\n var id = (opt_type !== undefined) ? String(opt_type) : undefined;\n return this.eventTargetListeners_.hasListener(id, opt_capture);\n};\n\n\n/**\n * Sets the target to be used for `event.target` when firing\n * event. Mainly used for testing. For example, see\n * `goog.testing.events.mixinListenable`.\n * @param {!Object} target The target.\n */\ngoog.events.EventTarget.prototype.setTargetForTesting = function(target) {\n 'use strict';\n this.actualEventTarget_ = target;\n};\n\n\n/**\n * Asserts that the event target instance is initialized properly.\n * @private\n */\ngoog.events.EventTarget.prototype.assertInitialized_ = function() {\n 'use strict';\n goog.asserts.assert(\n this.eventTargetListeners_,\n 'Event target is not initialized. Did you call the superclass ' +\n '(goog.events.EventTarget) constructor?');\n};\n\n\n/**\n * Dispatches the given event on the ancestorsTree.\n *\n * @param {!Object} target The target to dispatch on.\n * @param {goog.events.Event|Object|string} e The event object.\n * @param {Array<goog.events.Listenable>=} opt_ancestorsTree The ancestors\n * tree of the target, in reverse order from the closest ancestor\n * to the root event target. May be null if the target has no ancestor.\n * @return {boolean} If anyone called preventDefault on the event object (or\n * if any of the listeners returns false) this will also return false.\n * @private\n */\ngoog.events.EventTarget.dispatchEventInternal_ = function(\n target, e, opt_ancestorsTree) {\n 'use strict';\n /** @suppress {missingProperties} */\n var type = e.type || /** @type {string} */ (e);\n\n // If accepting a string or object, create a custom event object so that\n // preventDefault and stopPropagation work with the event.\n if (typeof e === 'string') {\n e = new goog.events.Event(e, target);\n } else if (!(e instanceof goog.events.Event)) {\n var oldEvent = e;\n e = new goog.events.Event(type, target);\n goog.object.extend(e, oldEvent);\n } else {\n e.target = e.target || target;\n }\n\n var rv = true, currentTarget;\n\n // Executes all capture listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (var i = opt_ancestorsTree.length - 1;\n !e.hasPropagationStopped() && i >= 0; i--) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, true, e) && rv;\n }\n }\n\n // Executes capture and bubble listeners on the target.\n if (!e.hasPropagationStopped()) {\n currentTarget = /** @type {?} */ (e.currentTarget = target);\n rv = currentTarget.fireListeners(type, true, e) && rv;\n if (!e.hasPropagationStopped()) {\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n // Executes all bubble listeners on the ancestors, if any.\n if (opt_ancestorsTree) {\n for (i = 0; !e.hasPropagationStopped() && i < opt_ancestorsTree.length;\n i++) {\n currentTarget = e.currentTarget = opt_ancestorsTree[i];\n rv = currentTarget.fireListeners(type, false, e) && rv;\n }\n }\n\n return rv;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview JSON utility functions.\n */\n\n\ngoog.provide('goog.json');\ngoog.provide('goog.json.Replacer');\ngoog.provide('goog.json.Reviver');\ngoog.provide('goog.json.Serializer');\n\n\n/**\n * @define {boolean} If true, use the native JSON parsing API.\n * NOTE: The default `goog.json.parse` implementation is able to handle\n * invalid JSON. JSPB used to produce invalid JSON which is not the case\n * anymore so this is safe to enable for parsing JSPB. Using native JSON is\n * faster and safer than the default implementation using `eval`.\n */\ngoog.json.USE_NATIVE_JSON = goog.define('goog.json.USE_NATIVE_JSON', false);\n\n/**\n * @define {boolean} If true, try the native JSON parsing API first. If it\n * fails, log an error and use `eval` instead. This is useful when\n * transitioning to `goog.json.USE_NATIVE_JSON`. The error logger needs to\n * be set by `goog.json.setErrorLogger`. If it is not set then the error\n * is ignored.\n */\ngoog.json.TRY_NATIVE_JSON = goog.define('goog.json.TRY_NATIVE_JSON', true);\n\n\n/**\n * Tests if a string is an invalid JSON string. This only ensures that we are\n * not using any invalid characters\n * @param {string} s The string to test.\n * @return {boolean} True if the input is a valid JSON string.\n */\ngoog.json.isValid = function(s) {\n 'use strict';\n // All empty whitespace is not valid.\n if (/^\\s*$/.test(s)) {\n return false;\n }\n\n // This is taken from http://www.json.org/json2.js which is released to the\n // public domain.\n // Changes: We dissallow \\u2028 Line separator and \\u2029 Paragraph separator\n // inside strings. We also treat \\u2028 and \\u2029 as whitespace which they\n // are in the RFC but IE and Safari does not match \\s to these so we need to\n // include them in the reg exps in all places where whitespace is allowed.\n // We allowed \\x7f inside strings because some tools don't escape it,\n // e.g. http://www.json.org/java/org/json/JSONObject.java\n\n // Parsing happens in three stages. In the first stage, we run the text\n // against regular expressions that look for non-JSON patterns. We are\n // especially concerned with '()' and 'new' because they can cause invocation,\n // and '=' because it can cause mutation. But just to be safe, we want to\n // reject all unexpected forms.\n\n // We split the first stage into 4 regexp operations in order to work around\n // crippling inefficiencies in IE's and Safari's regexp engines. First we\n // replace all backslash pairs with '@' (a non-JSON character). Second, we\n // replace all simple value tokens with ']' characters, but only when followed\n // by a colon, comma, closing bracket or end of string. Third, we delete all\n // open brackets that follow a colon or comma or that begin the text. Finally,\n // we look to see that the remaining characters are only whitespace or ']' or\n // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.\n\n // Don't make these static since they have the global flag.\n const backslashesRe = /\\\\[\"\\\\\\/bfnrtu]/g;\n const simpleValuesRe =\n /(?:\"[^\"\\\\\\n\\r\\u2028\\u2029\\x00-\\x08\\x0a-\\x1f]*\"|true|false|null|-?\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d+)?)[\\s\\u2028\\u2029]*(?=:|,|]|}|$)/g;\n const openBracketsRe = /(?:^|:|,)(?:[\\s\\u2028\\u2029]*\\[)+/g;\n const remainderRe = /^[\\],:{}\\s\\u2028\\u2029]*$/;\n\n return remainderRe.test(\n s.replace(backslashesRe, '@')\n .replace(simpleValuesRe, ']')\n .replace(openBracketsRe, ''));\n};\n\n/**\n * Logs a parsing error in `JSON.parse` solvable by using `eval`\n * if `goog.json.TRY_NATIVE_JSON` is enabled.\n * @private {function(string, !Error)} The first parameter is the error message,\n * the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.errorLogger_ = goog.nullFunction;\n\n\n/**\n * Sets an error logger to use if there's a recoverable parsing error and\n * `goog.json.TRY_NATIVE_JSON` is enabled.\n * @param {function(string, !Error)} errorLogger The first parameter is the\n * error message, the second is the exception thrown by `JSON.parse`.\n */\ngoog.json.setErrorLogger = function(errorLogger) {\n 'use strict';\n goog.json.errorLogger_ = errorLogger;\n};\n\n\n/**\n * Parses a JSON string and returns the result. This throws an exception if\n * the string is an invalid JSON string.\n *\n * Note that this is very slow on large strings. Use JSON.parse if possible.\n *\n * @param {*} s The JSON string to parse.\n * @throws Error if s is invalid JSON.\n * @return {Object} The object generated from the JSON string, or null.\n * @deprecated Use JSON.parse.\n */\ngoog.json.parse = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*):Object} */ (goog.global['JSON']['parse']) :\n function(s) {\n 'use strict';\n let error;\n if (goog.json.TRY_NATIVE_JSON) {\n try {\n return goog.global['JSON']['parse'](s);\n } catch (ex) {\n error = ex;\n }\n }\n const o = String(s);\n if (goog.json.isValid(o)) {\n\n try {\n const result = /** @type {?Object} */ (eval('(' + o + ')'));\n if (error) {\n goog.json.errorLogger_('Invalid JSON: ' + o, error);\n }\n return result;\n } catch (ex) {\n }\n }\n throw new Error('Invalid JSON string: ' + o);\n };\n\n\n/**\n * JSON replacer, as defined in Section 15.12.3 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * TODO(nicksantos): Array should also be a valid replacer.\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Replacer;\n\n\n/**\n * JSON reviver, as defined in Section 15.12.2 of the ES5 spec.\n * @see http://ecma-international.org/ecma-262/5.1/#sec-15.12.3\n *\n * @typedef {function(this:Object, string, *): *}\n */\ngoog.json.Reviver;\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @param {?goog.json.Replacer=} opt_replacer A replacer function\n * called for each (key, value) pair that determines how the value\n * should be serialized. By defult, this just returns the value\n * and allows default serialization to kick in.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.serialize = goog.json.USE_NATIVE_JSON ?\n /** @type {function(*, ?goog.json.Replacer=):string} */\n (goog.global['JSON']['stringify']) :\n function(object, opt_replacer) {\n 'use strict';\n // NOTE(nicksantos): Currently, we never use JSON.stringify.\n //\n // The last time I evaluated this, JSON.stringify had subtle bugs and\n // behavior differences on all browsers, and the performance win was not\n // large enough to justify all the issues. This may change in the future\n // as browser implementations get better.\n //\n // assertSerialize in json_test contains if branches for the cases\n // that fail.\n return new goog.json.Serializer(opt_replacer).serialize(object);\n };\n\n\n\n/**\n * Class that is used to serialize JSON objects to a string.\n * @param {?goog.json.Replacer=} opt_replacer Replacer.\n * @constructor\n */\ngoog.json.Serializer = function(opt_replacer) {\n 'use strict';\n /**\n * @type {goog.json.Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n};\n\n\n/**\n * Serializes an object or a value to a JSON string.\n *\n * @param {*} object The object to serialize.\n * @throws Error if there are loops in the object graph.\n * @return {string} A JSON string representation of the input.\n */\ngoog.json.Serializer.prototype.serialize = function(object) {\n 'use strict';\n const sb = [];\n this.serializeInternal(object, sb);\n return sb.join('');\n};\n\n\n/**\n * Serializes a generic value to a JSON string\n * @protected\n * @param {*} object The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @throws Error if there are loops in the object graph.\n */\ngoog.json.Serializer.prototype.serializeInternal = function(object, sb) {\n 'use strict';\n if (object == null) {\n // undefined == null so this branch covers undefined as well as null\n sb.push('null');\n return;\n }\n\n if (typeof object == 'object') {\n if (Array.isArray(object)) {\n this.serializeArray(object, sb);\n return;\n } else if (\n object instanceof String || object instanceof Number ||\n object instanceof Boolean) {\n object = object.valueOf();\n // Fall through to switch below.\n } else {\n this.serializeObject_(/** @type {!Object} */ (object), sb);\n return;\n }\n }\n\n switch (typeof object) {\n case 'string':\n this.serializeString_(object, sb);\n break;\n case 'number':\n this.serializeNumber_(object, sb);\n break;\n case 'boolean':\n sb.push(String(object));\n break;\n case 'function':\n sb.push('null');\n break;\n default:\n throw new Error('Unknown type: ' + typeof object);\n }\n};\n\n\n/**\n * Character mappings used internally for goog.string.quote\n * @private\n * @type {!Object}\n */\ngoog.json.Serializer.charToJsonCharCache_ = {\n '\\\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n '/': '\\\\/',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n\n '\\x0B': '\\\\u000b' // '\\v' is not supported in JScript\n};\n\n\n/**\n * Regular expression used to match characters that need to be replaced.\n * The S60 browser has a bug where unicode characters are not matched by\n * regular expressions. The condition below detects such behaviour and\n * adjusts the regular expression accordingly.\n * @private\n * @type {!RegExp}\n */\ngoog.json.Serializer.charsToReplace_ = /\\uffff/.test('\\uffff') ?\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g :\n /[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\n\n\n/**\n * Serializes a string to a JSON string\n * @private\n * @param {string} s The string to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeString_ = function(s, sb) {\n 'use strict';\n // The official JSON implementation does not work with international\n // characters.\n sb.push('\"', s.replace(goog.json.Serializer.charsToReplace_, function(c) {\n 'use strict';\n // caching the result improves performance by a factor 2-3\n let rv = goog.json.Serializer.charToJsonCharCache_[c];\n if (!rv) {\n rv = '\\\\u' + (c.charCodeAt(0) | 0x10000).toString(16).substr(1);\n goog.json.Serializer.charToJsonCharCache_[c] = rv;\n }\n return rv;\n }), '\"');\n};\n\n\n/**\n * Serializes a number to a JSON string\n * @private\n * @param {number} n The number to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeNumber_ = function(n, sb) {\n 'use strict';\n sb.push(isFinite(n) && !isNaN(n) ? String(n) : 'null');\n};\n\n\n/**\n * Serializes an array to a JSON string\n * @param {Array<string>} arr The array to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n * @protected\n */\ngoog.json.Serializer.prototype.serializeArray = function(arr, sb) {\n 'use strict';\n const l = arr.length;\n sb.push('[');\n let sep = '';\n for (let i = 0; i < l; i++) {\n sb.push(sep);\n\n const value = arr[i];\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(arr, String(i), value) : value,\n sb);\n\n sep = ',';\n }\n sb.push(']');\n};\n\n\n/**\n * Serializes an object to a JSON string\n * @private\n * @param {!Object} obj The object to serialize.\n * @param {Array<string>} sb Array used as a string builder.\n */\ngoog.json.Serializer.prototype.serializeObject_ = function(obj, sb) {\n 'use strict';\n sb.push('{');\n let sep = '';\n for (const key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n // Skip functions.\n if (typeof value != 'function') {\n sb.push(sep);\n this.serializeString_(key, sb);\n sb.push(':');\n\n this.serializeInternal(\n this.replacer_ ? this.replacer_.call(obj, key, value) : value, sb);\n\n sep = ',';\n }\n }\n }\n sb.push('}');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.module('goog.async.WorkQueue');\ngoog.module.declareLegacyNamespace();\n\nconst FreeList = goog.require('goog.async.FreeList');\nconst {assert} = goog.require('goog.asserts');\n\n// TODO(johnlenz): generalize the WorkQueue if this is used by more\n// than goog.async.run.\n\n\n/**\n * A low GC workqueue. The key elements of this design:\n * - avoids the need for goog.bind or equivalent by carrying scope\n * - avoids the need for array reallocation by using a linked list\n * - minimizes work entry objects allocation by recycling objects\n * @final\n * @struct\n */\nclass WorkQueue {\n constructor() {\n this.workHead_ = null;\n this.workTail_ = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n add(fn, scope) {\n const item = this.getUnusedItem_();\n item.set(fn, scope);\n\n if (this.workTail_) {\n this.workTail_.next = item;\n this.workTail_ = item;\n } else {\n assert(!this.workHead_);\n this.workHead_ = item;\n this.workTail_ = item;\n }\n }\n\n /**\n * @return {?WorkItem}\n */\n remove() {\n let item = null;\n\n if (this.workHead_) {\n item = this.workHead_;\n this.workHead_ = this.workHead_.next;\n if (!this.workHead_) {\n this.workTail_ = null;\n }\n item.next = null;\n }\n return item;\n }\n\n /**\n * @param {!WorkItem} item\n */\n returnUnused(item) {\n WorkQueue.freelist_.put(item);\n }\n\n /**\n * @return {!WorkItem}\n * @private\n */\n getUnusedItem_() {\n return WorkQueue.freelist_.get();\n }\n}\n\n/** @define {number} The maximum number of entries to keep for recycling. */\nWorkQueue.DEFAULT_MAX_UNUSED =\n goog.define('goog.async.WorkQueue.DEFAULT_MAX_UNUSED', 100);\n\n/** @const @private {!FreeList<!WorkItem>} */\nWorkQueue.freelist_ = new FreeList(\n () => new WorkItem(), item => item.reset(), WorkQueue.DEFAULT_MAX_UNUSED);\n\n/**\n * @final\n * @struct\n */\nclass WorkItem {\n constructor() {\n /** @type {?function()} */\n this.fn = null;\n /** @type {?Object|null|undefined} */\n this.scope = null;\n /** @type {?WorkItem} */\n this.next = null;\n }\n\n /**\n * @param {function()} fn\n * @param {Object|null|undefined} scope\n */\n set(fn, scope) {\n 'use strict';\n this.fn = fn;\n this.scope = scope;\n this.next = null;\n }\n\n /** Reset the work item so they don't prevent GC before reuse */\n reset() {\n this.fn = null;\n this.scope = null;\n this.next = null;\n }\n}\n\nexports = WorkQueue;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.async.run');\n\ngoog.require('goog.async.WorkQueue');\ngoog.require('goog.async.nextTick');\ngoog.require('goog.async.throwException');\n\n/**\n * @define {boolean} If true, use the global Promise to implement goog.async.run\n * assuming either the native, or polyfill version will be used. Does still\n * permit tests to use forceNextTick.\n */\ngoog.ASSUME_NATIVE_PROMISE = goog.define('goog.ASSUME_NATIVE_PROMISE', false);\n\n/**\n * Fires the provided callback just before the current callstack unwinds, or as\n * soon as possible after the current JS execution context.\n * @param {function(this:THIS)} callback\n * @param {THIS=} opt_context Object to use as the \"this value\" when calling\n * the provided function.\n * @template THIS\n */\ngoog.async.run = function(callback, opt_context) {\n 'use strict';\n if (!goog.async.run.schedule_) {\n goog.async.run.initializeRunner_();\n }\n if (!goog.async.run.workQueueScheduled_) {\n // Nothing is currently scheduled, schedule it now.\n goog.async.run.schedule_();\n goog.async.run.workQueueScheduled_ = true;\n }\n\n goog.async.run.workQueue_.add(callback, opt_context);\n};\n\n\n/**\n * Initializes the function to use to process the work queue.\n * @private\n */\ngoog.async.run.initializeRunner_ = function() {\n 'use strict';\n if (goog.ASSUME_NATIVE_PROMISE ||\n (goog.global.Promise && goog.global.Promise.resolve)) {\n // Use goog.global.Promise instead of just Promise because the relevant\n // externs may be missing, and don't alias it because this could confuse the\n // compiler into thinking the polyfill is required when it should be treated\n // as optional.\n var promise = goog.global.Promise.resolve(undefined);\n goog.async.run.schedule_ = function() {\n 'use strict';\n promise.then(goog.async.run.processWorkQueue);\n };\n } else {\n goog.async.run.schedule_ = function() {\n 'use strict';\n goog.async.nextTick(goog.async.run.processWorkQueue);\n };\n }\n};\n\n\n/**\n * Forces goog.async.run to use nextTick instead of Promise.\n *\n * This should only be done in unit tests. It's useful because MockClock\n * replaces nextTick, but not the browser Promise implementation, so it allows\n * Promise-based code to be tested with MockClock.\n *\n * However, we also want to run promises if the MockClock is no longer in\n * control so we schedule a backup \"setTimeout\" to the unmocked timeout if\n * provided.\n *\n * @param {function(function())=} opt_realSetTimeout\n */\ngoog.async.run.forceNextTick = function(opt_realSetTimeout) {\n 'use strict';\n goog.async.run.schedule_ = function() {\n 'use strict';\n goog.async.nextTick(goog.async.run.processWorkQueue);\n if (opt_realSetTimeout) {\n opt_realSetTimeout(goog.async.run.processWorkQueue);\n }\n };\n};\n\n\n/**\n * The function used to schedule work asynchronousely.\n * @private {function()}\n */\ngoog.async.run.schedule_;\n\n\n/** @private {boolean} */\ngoog.async.run.workQueueScheduled_ = false;\n\n\n/** @private {!goog.async.WorkQueue} */\ngoog.async.run.workQueue_ = new goog.async.WorkQueue();\n\n\nif (goog.DEBUG) {\n /**\n * Reset the work queue. Only available for tests in debug mode.\n */\n goog.async.run.resetQueue = function() {\n 'use strict';\n goog.async.run.workQueueScheduled_ = false;\n goog.async.run.workQueue_ = new goog.async.WorkQueue();\n };\n\n\n /**\n * Resets the scheduler. Only available for tests in debug mode.\n */\n goog.async.run.resetSchedulerForTest = function() {\n goog.async.run.initializeRunner_();\n };\n}\n\n\n/**\n * Run any pending goog.async.run work items. This function is not intended\n * for general use, but for use by entry point handlers to run items ahead of\n * goog.async.nextTick.\n */\ngoog.async.run.processWorkQueue = function() {\n 'use strict';\n // NOTE: additional work queue items may be added while processing.\n var item = null;\n while (item = goog.async.run.workQueue_.remove()) {\n try {\n item.fn.call(item.scope);\n } catch (e) {\n goog.async.throwException(e);\n }\n goog.async.run.workQueue_.returnUnused(item);\n }\n\n // There are no more work items, allow processing to be scheduled again.\n goog.async.run.workQueueScheduled_ = false;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple freelist.\n *\n * An anterative to goog.structs.SimplePool, it imposes the requirement that the\n * objects in the list contain a \"next\" property that can be used to maintain\n * the pool.\n */\n\ngoog.provide('goog.async.FreeList');\n\n\n/**\n * @template ITEM\n */\ngoog.async.FreeList = class {\n /**\n * @param {function():ITEM} create\n * @param {function(ITEM):void} reset\n * @param {number} limit\n */\n constructor(create, reset, limit) {\n /** @private @const {number} */\n this.limit_ = limit;\n /** @private @const {function()} */\n this.create_ = create;\n /** @private @const {function(ITEM):void} */\n this.reset_ = reset;\n\n /** @private {number} */\n this.occupants_ = 0;\n /** @private {ITEM} */\n this.head_ = null;\n }\n\n /**\n * @return {ITEM}\n */\n get() {\n let item;\n if (this.occupants_ > 0) {\n this.occupants_--;\n item = this.head_;\n this.head_ = item.next;\n item.next = null;\n } else {\n item = this.create_();\n }\n return item;\n }\n\n /**\n * @param {ITEM} item An item available for possible future reuse.\n */\n put(item) {\n this.reset_(item);\n if (this.occupants_ < this.limit_) {\n this.occupants_++;\n item.next = this.head_;\n this.head_ = item;\n }\n }\n\n /**\n * Visible for testing.\n * @package\n * @return {number}\n */\n occupants() {\n return this.occupants_;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a function to throw an error without interrupting\n * the current execution context.\n */\n\ngoog.module('goog.async.throwException');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Throw an item without interrupting the current execution context. For\n * example, if processing a group of items in a loop, sometimes it is useful\n * to report an error while still allowing the rest of the batch to be\n * processed.\n * @param {*} exception\n */\nfunction throwException(exception) {\n // Each throw needs to be in its own context.\n goog.global.setTimeout(() => {\n throw exception;\n }, 0);\n}\nexports = throwException;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A timer class to which other classes and objects can listen on.\n * This is only an abstraction above `setInterval`.\n *\n * @see ../demos/timers.html\n */\n\ngoog.provide('goog.Timer');\n\ngoog.require('goog.Promise');\ngoog.require('goog.events.EventTarget');\ngoog.requireType('goog.Thenable');\n\n\n\n/**\n * Class for handling timing events.\n *\n * @param {number=} opt_interval Number of ms between ticks (default: 1ms).\n * @param {Object=} opt_timerObject An object that has `setTimeout`,\n * `setInterval`, `clearTimeout` and `clearInterval`\n * (e.g., `window`).\n * @constructor\n * @extends {goog.events.EventTarget}\n */\ngoog.Timer = function(opt_interval, opt_timerObject) {\n 'use strict';\n goog.events.EventTarget.call(this);\n\n /**\n * Number of ms between ticks\n * @private {number}\n */\n this.interval_ = opt_interval || 1;\n\n /**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the window\n * object. Changing this on {@link goog.Timer.prototype} changes the object\n * for all timer instances which can be useful if your environment has some\n * other implementation of timers than the `window` object.\n * @private {{setTimeout:!Function, clearTimeout:!Function}}\n */\n this.timerObject_ = /** @type {{setTimeout, clearTimeout}} */ (\n opt_timerObject || goog.Timer.defaultTimerObject);\n\n /**\n * Cached `tick_` bound to the object for later use in the timer.\n * @private {Function}\n * @const\n */\n this.boundTick_ = goog.bind(this.tick_, this);\n\n /**\n * Firefox browser often fires the timer event sooner (sometimes MUCH sooner)\n * than the requested timeout. So we compare the time to when the event was\n * last fired, and reschedule if appropriate. See also\n * {@link goog.Timer.intervalScale}.\n * @private {number}\n */\n this.last_ = goog.now();\n};\ngoog.inherits(goog.Timer, goog.events.EventTarget);\n\n\n/**\n * Maximum timeout value.\n *\n * Timeout values too big to fit into a signed 32-bit integer may cause overflow\n * in FF, Safari, and Chrome, resulting in the timeout being scheduled\n * immediately. It makes more sense simply not to schedule these timeouts, since\n * 24.8 days is beyond a reasonable expectation for the browser to stay open.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.MAX_TIMEOUT_ = 2147483647;\n\n\n/**\n * A timer ID that cannot be returned by any known implementation of\n * `window.setTimeout`. Passing this value to `window.clearTimeout`\n * should therefore be a no-op.\n *\n * @private {number}\n * @const\n */\ngoog.Timer.INVALID_TIMEOUT_ID_ = -1;\n\n\n/**\n * Whether this timer is enabled\n * @type {boolean}\n */\ngoog.Timer.prototype.enabled = false;\n\n\n/**\n * An object that implements `setTimeout`, `setInterval`,\n * `clearTimeout` and `clearInterval`. We default to the global\n * object. Changing `goog.Timer.defaultTimerObject` changes the object for\n * all timer instances which can be useful if your environment has some other\n * implementation of timers you'd like to use.\n * @type {{setTimeout, clearTimeout}}\n */\ngoog.Timer.defaultTimerObject = goog.global;\n\n\n/**\n * Variable that controls the timer error correction. If the timer is called\n * before the requested interval times `intervalScale`, which often\n * happens on Mozilla, the timer is rescheduled.\n * @see {@link #last_}\n * @type {number}\n */\ngoog.Timer.intervalScale = 0.8;\n\n\n/**\n * Variable for storing the result of `setInterval`.\n * @private {?number}\n */\ngoog.Timer.prototype.timer_ = null;\n\n\n/**\n * Gets the interval of the timer.\n * @return {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.getInterval = function() {\n 'use strict';\n return this.interval_;\n};\n\n\n/**\n * Sets the interval of the timer.\n * @param {number} interval Number of ms between ticks.\n */\ngoog.Timer.prototype.setInterval = function(interval) {\n 'use strict';\n this.interval_ = interval;\n if (this.timer_ && this.enabled) {\n // Stop and then start the timer to reset the interval.\n this.stop();\n this.start();\n } else if (this.timer_) {\n this.stop();\n }\n};\n\n\n/**\n * Callback for the `setTimeout` used by the timer.\n * @private\n */\ngoog.Timer.prototype.tick_ = function() {\n 'use strict';\n if (this.enabled) {\n var elapsed = goog.now() - this.last_;\n if (elapsed > 0 && elapsed < this.interval_ * goog.Timer.intervalScale) {\n this.timer_ = this.timerObject_.setTimeout(\n this.boundTick_, this.interval_ - elapsed);\n return;\n }\n\n // Prevents setInterval from registering a duplicate timeout when called\n // in the timer event handler.\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n\n this.dispatchTick();\n // The timer could be stopped in the timer event handler.\n if (this.enabled) {\n // Stop and start to ensure there is always only one timeout even if\n // start is called in the timer event handler.\n this.stop();\n this.start();\n }\n }\n};\n\n\n/**\n * Dispatches the TICK event. This is its own method so subclasses can override.\n */\ngoog.Timer.prototype.dispatchTick = function() {\n 'use strict';\n this.dispatchEvent(goog.Timer.TICK);\n};\n\n\n/**\n * Starts the timer.\n */\ngoog.Timer.prototype.start = function() {\n 'use strict';\n this.enabled = true;\n\n // If there is no interval already registered, start it now\n if (!this.timer_) {\n // IMPORTANT!\n // window.setInterval in FireFox has a bug - it fires based on\n // absolute time, rather than on relative time. What this means\n // is that if a computer is sleeping/hibernating for 24 hours\n // and the timer interval was configured to fire every 1000ms,\n // then after the PC wakes up the timer will fire, in rapid\n // succession, 3600*24 times.\n // This bug is described here and is already fixed, but it will\n // take time to propagate, so for now I am switching this over\n // to setTimeout logic.\n // https://bugzilla.mozilla.org/show_bug.cgi?id=376643\n //\n this.timer_ = this.timerObject_.setTimeout(this.boundTick_, this.interval_);\n this.last_ = goog.now();\n }\n};\n\n\n/**\n * Stops the timer.\n */\ngoog.Timer.prototype.stop = function() {\n 'use strict';\n this.enabled = false;\n if (this.timer_) {\n this.timerObject_.clearTimeout(this.timer_);\n this.timer_ = null;\n }\n};\n\n\n/** @override */\ngoog.Timer.prototype.disposeInternal = function() {\n 'use strict';\n goog.Timer.superClass_.disposeInternal.call(this);\n this.stop();\n delete this.timerObject_;\n};\n\n\n/**\n * Constant for the timer's event type.\n * @const\n */\ngoog.Timer.TICK = 'tick';\n\n\n/**\n * Calls the given function once, after the optional pause.\n * <p>\n * The function is always called asynchronously, even if the delay is 0. This\n * is a common trick to schedule a function to run after a batch of browser\n * event processing.\n *\n * @param {function(this:SCOPE)|{handleEvent:function()}|null} listener Function\n * or object that has a handleEvent method.\n * @param {number=} opt_delay Milliseconds to wait; default is 0.\n * @param {SCOPE=} opt_handler Object in whose scope to call the listener.\n * @return {number} A handle to the timer ID.\n * @template SCOPE\n */\ngoog.Timer.callOnce = function(listener, opt_delay, opt_handler) {\n 'use strict';\n if (typeof listener === 'function') {\n if (opt_handler) {\n listener = goog.bind(listener, opt_handler);\n }\n } else if (listener && typeof listener.handleEvent == 'function') {\n // using typeof to prevent strict js warning\n listener = goog.bind(listener.handleEvent, listener);\n } else {\n throw new Error('Invalid listener argument');\n }\n\n if (Number(opt_delay) > goog.Timer.MAX_TIMEOUT_) {\n // Timeouts greater than MAX_INT return immediately due to integer\n // overflow in many browsers. Since MAX_INT is 24.8 days, just don't\n // schedule anything at all.\n return goog.Timer.INVALID_TIMEOUT_ID_;\n } else {\n return goog.Timer.defaultTimerObject.setTimeout(listener, opt_delay || 0);\n }\n};\n\n\n/**\n * Clears a timeout initiated by {@link #callOnce}.\n * @param {?number} timerId A timer ID.\n */\ngoog.Timer.clear = function(timerId) {\n 'use strict';\n goog.Timer.defaultTimerObject.clearTimeout(timerId);\n};\n\n\n/**\n * @param {number} delay Milliseconds to wait.\n * @param {(RESULT|goog.Thenable<RESULT>|Thenable)=} opt_result The value\n * with which the promise will be resolved.\n * @return {!goog.Promise<RESULT>} A promise that will be resolved after\n * the specified delay, unless it is canceled first.\n * @template RESULT\n */\ngoog.Timer.promise = function(delay, opt_result) {\n 'use strict';\n var timerKey = null;\n return new goog\n .Promise(function(resolve, reject) {\n 'use strict';\n timerKey = goog.Timer.callOnce(function() {\n 'use strict';\n resolve(opt_result);\n }, delay);\n if (timerKey == goog.Timer.INVALID_TIMEOUT_ID_) {\n reject(new Error('Failed to schedule timer.'));\n }\n })\n .thenCatch(function(error) {\n 'use strict';\n // Clear the timer. The most likely reason is \"cancel\" signal.\n goog.Timer.clear(timerKey);\n throw error;\n });\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the goog.async.Throttle class.\n *\n * @see ../demos/timers.html\n */\n\ngoog.module('goog.async.Throttle');\ngoog.module.declareLegacyNamespace();\n\nconst Disposable = goog.require('goog.Disposable');\nconst Timer = goog.require('goog.Timer');\n\n\n/**\n * Throttle will perform an action that is passed in no more than once\n * per interval (specified in milliseconds). If it gets multiple signals\n * to perform the action while it is waiting, it will only perform the action\n * once at the end of the interval.\n * @final\n * @template T\n */\nclass Throttle extends Disposable {\n /**\n * @param {function(this: T, ...?)} listener Function to callback when the\n * action is triggered.\n * @param {number} interval Interval over which to throttle. The listener can\n * only be called once per interval.\n * @param {T=} handler Object in whose scope to call the listener.\n */\n constructor(listener, interval, handler) {\n super();\n /**\n * Function to callback\n * @type {function(this: T, ...?)}\n * @private\n */\n this.listener_ = handler != null ? listener.bind(handler) : listener;\n\n /**\n * Interval for the throttle time\n * @type {number}\n * @private\n */\n this.interval_ = interval;\n\n /**\n * The last arguments passed into `fire`, or null if there is no pending\n * call.\n * @private {?IArrayLike}\n */\n this.args_ = null;\n\n /**\n * Indicates that the action is pending and needs to be fired.\n * @type {boolean}\n * @private\n */\n this.shouldFire_ = false;\n\n /**\n * Indicates the count of nested pauses currently in effect on the throttle.\n * When this count is not zero, fired actions will be postponed until the\n * throttle is resumed enough times to drop the pause count to zero.\n * @type {number}\n * @private\n */\n this.pauseCount_ = 0;\n\n /**\n * Timer for scheduling the next callback\n * @type {?number}\n * @private\n */\n this.timer_ = null;\n }\n\n /**\n * Notifies the throttle that the action has happened. It will throttle\n * the call so that the callback is not called too often according to the\n * interval parameter passed to the constructor, passing the arguments\n * from the last call of this function into the throttled function.\n * @param {...?} var_args Arguments to pass on to the throttled function.\n */\n fire(var_args) {\n this.args_ = arguments;\n if (!this.timer_ && !this.pauseCount_) {\n this.doAction_();\n } else {\n this.shouldFire_ = true;\n }\n }\n\n /**\n * Cancels any pending action callback. The throttle can be restarted by\n * calling {@link #fire}.\n */\n stop() {\n if (this.timer_) {\n Timer.clear(this.timer_);\n this.timer_ = null;\n this.shouldFire_ = false;\n this.args_ = null;\n }\n }\n\n /**\n * Pauses the throttle. All pending and future action callbacks will be\n * delayed until the throttle is resumed. Pauses can be nested.\n */\n pause() {\n this.pauseCount_++;\n }\n\n /**\n * Resumes the throttle. If doing so drops the pausing count to zero,\n * pending action callbacks will be executed as soon as possible, but\n * still no sooner than an interval's delay after the previous call.\n * Future action callbacks will be executed as normal.\n */\n resume() {\n this.pauseCount_--;\n if (!this.pauseCount_ && this.shouldFire_ && !this.timer_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /** @override */\n disposeInternal() {\n super.disposeInternal();\n this.stop();\n }\n\n /**\n * Handler for the timer to fire the throttle\n * @private\n */\n onTimer_() {\n this.timer_ = null;\n\n if (this.shouldFire_ && !this.pauseCount_) {\n this.shouldFire_ = false;\n this.doAction_();\n }\n }\n\n /**\n * Calls the callback\n * @private\n */\n doAction_() {\n this.timer_ = Timer.callOnce(() => this.onTimer_(), this.interval_);\n const args = this.args_;\n // release memory first so it always happens even if listener throws\n this.args_ = null;\n this.listener_.apply(null, args);\n }\n}\n\nexports = Throttle;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class to create objects which want to handle multiple events\n * and have their listeners easily cleaned up via a dispose method.\n *\n * Example:\n * <pre>\n * function Something() {\n * Something.base(this);\n *\n * ... set up object ...\n *\n * // Add event listeners\n * this.listen(this.starEl, goog.events.EventType.CLICK, this.handleStar);\n * this.listen(this.headerEl, goog.events.EventType.CLICK, this.expand);\n * this.listen(this.collapseEl, goog.events.EventType.CLICK, this.collapse);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOVER, this.showHover);\n * this.listen(this.infoEl, goog.events.EventType.MOUSEOUT, this.hideHover);\n * }\n * goog.inherits(Something, goog.events.EventHandler);\n *\n * Something.prototype.disposeInternal = function() {\n * Something.base(this, 'disposeInternal');\n * goog.dom.removeNode(this.container);\n * };\n *\n *\n * // Then elsewhere:\n *\n * var activeSomething = null;\n * function openSomething() {\n * activeSomething = new Something();\n * }\n *\n * function closeSomething() {\n * if (activeSomething) {\n * activeSomething.dispose(); // Remove event listeners\n * activeSomething = null;\n * }\n * }\n * </pre>\n */\n\ngoog.provide('goog.events.EventHandler');\n\ngoog.require('goog.Disposable');\ngoog.require('goog.events');\ngoog.require('goog.object');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.events.EventId');\ngoog.requireType('goog.events.EventTarget');\ngoog.requireType('goog.events.EventWrapper');\n\n\n\n/**\n * Super class for objects that want to easily manage a number of event\n * listeners. It allows a short cut to listen and also provides a quick way\n * to remove all events listeners belonging to this object.\n * @param {SCOPE=} opt_scope Object in whose scope to call the listeners.\n * @constructor\n * @extends {goog.Disposable}\n * @template SCOPE\n */\ngoog.events.EventHandler = function(opt_scope) {\n 'use strict';\n goog.Disposable.call(this);\n // TODO(mknichel): Rename this to this.scope_ and fix the classes in google3\n // that access this private variable. :(\n this.handler_ = opt_scope;\n\n /**\n * Keys for events that are being listened to.\n * @type {!Object<!goog.events.Key>}\n * @private\n */\n this.keys_ = {};\n};\ngoog.inherits(goog.events.EventHandler, goog.Disposable);\n\n\n/**\n * Utility array used to unify the cases of listening for an array of types\n * and listening for a single event, without using recursion or allocating\n * an array each time.\n * @type {!Array<string>}\n * @const\n * @private\n */\ngoog.events.EventHandler.typeArray_ = [];\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listen = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listen_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|!AddEventListenerOptions|undefined} options\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenWithScope = function(\n src, type, fn, options, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listen_(src, type, fn, options, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted then the\n * EventHandler's handleEvent method will be used.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listen_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (!Array.isArray(type)) {\n if (type) {\n goog.events.EventHandler.typeArray_[0] = type.toString();\n }\n type = goog.events.EventHandler.typeArray_;\n }\n for (var i = 0; i < type.length; i++) {\n var listenerObj = goog.events.listen(\n src, type[i], opt_fn || self.handleEvent, opt_options || false,\n opt_scope || self.handler_ || self);\n\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:SCOPE, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnce = function(\n src, type, opt_fn, opt_options) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n return self.listenOnce_(src, type, opt_fn, opt_options);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired the\n * event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(this:T, EVENTOBJ):?|{handleEvent:function(this:T, ?):?}|\n * null|undefined} fn Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.listenOnceWithScope = function(\n src, type, fn, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenOnce_(src, type, fn, capture, scope);\n};\n\n\n/**\n * Listen to an event on a Listenable. If the function is omitted, then the\n * EventHandler's handleEvent method will be used. After the event has fired\n * the event listener is removed from the target. If an array of event types is\n * provided, each event type will be listened to once.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type to listen for or array of event types.\n * @param {function(EVENTOBJ):?|{handleEvent:function(?):?}|null=} opt_fn\n * Optional callback function to be used as the listener or an object with\n * handleEvent function.\n * @param {(boolean|!AddEventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenOnce_ = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.listenOnce_(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var listenerObj = goog.events.listenOnce(\n src, type, opt_fn || self.handleEvent, opt_options,\n opt_scope || self.handler_ || self);\n if (!listenerObj) {\n // When goog.events.listen run on OFF_AND_FAIL or OFF_AND_SILENT\n // (goog.events.CaptureSimulationMode) in IE8-, it will return null\n // value.\n return self;\n }\n\n var key = listenerObj.key;\n self.keys_[key] = listenerObj;\n }\n\n return self;\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:SCOPE, ?):?|{handleEvent:function(?):?}|null} listener\n * Callback method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapper = function(\n src, wrapper, listener, opt_capt) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Remove the opt_scope from this function and then\n // templatize it.\n return self.listenWithWrapper_(src, wrapper, listener, opt_capt);\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(this:T, ?):?|{handleEvent:function(this:T, ?):?}|null}\n * listener Optional callback function to be used as the\n * listener or an object with handleEvent function.\n * @param {boolean|undefined} capture Optional whether to use capture phase.\n * @param {T} scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template T, THIS\n */\ngoog.events.EventHandler.prototype.listenWithWrapperAndScope = function(\n src, wrapper, listener, capture, scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n // TODO(mknichel): Deprecate this function.\n return self.listenWithWrapper_(src, wrapper, listener, capture, scope);\n};\n\n\n/**\n * Adds an event listener with a specific event wrapper on a DOM Node or an\n * object that has implemented {@link goog.events.EventTarget}. A listener can\n * only be added once to an object.\n *\n * @param {EventTarget|goog.events.EventTarget} src The node to listen to\n * events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener Callback\n * method, or an object with a handleEvent function.\n * @param {boolean=} opt_capt Whether to fire in capture phase (defaults to\n * false).\n * @param {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n * @private\n */\ngoog.events.EventHandler.prototype.listenWithWrapper_ = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.listen(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * @return {number} Number of listeners registered by this handler.\n */\ngoog.events.EventHandler.prototype.getListenerCount = function() {\n 'use strict';\n var count = 0;\n for (var key in this.keys_) {\n if (Object.prototype.hasOwnProperty.call(this.keys_, key)) {\n count++;\n }\n }\n return count;\n};\n\n\n/**\n * Unlistens on an event.\n * @param {goog.events.ListenableType} src Event source.\n * @param {string|Array<string>|\n * !goog.events.EventId<EVENTOBJ>|!Array<!goog.events.EventId<EVENTOBJ>>}\n * type Event type or array of event types to unlisten to.\n * @param {function(this:?, EVENTOBJ):?|{handleEvent:function(?):?}|null=}\n * opt_fn Optional callback function to be used as the listener or an object\n * with handleEvent function.\n * @param {(boolean|!EventListenerOptions)=} opt_options\n * @param {Object=} opt_scope Object in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template EVENTOBJ, THIS\n */\ngoog.events.EventHandler.prototype.unlisten = function(\n src, type, opt_fn, opt_options, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n if (Array.isArray(type)) {\n for (var i = 0; i < type.length; i++) {\n self.unlisten(src, type[i], opt_fn, opt_options, opt_scope);\n }\n } else {\n var capture =\n goog.isObject(opt_options) ? !!opt_options.capture : !!opt_options;\n var listener = goog.events.getListener(\n src, type, opt_fn || self.handleEvent, capture,\n opt_scope || self.handler_ || self);\n\n if (listener) {\n goog.events.unlistenByKey(listener);\n delete self.keys_[listener.key];\n }\n }\n\n return self;\n};\n\n\n/**\n * Removes an event listener which was added with listenWithWrapper().\n *\n * @param {EventTarget|goog.events.EventTarget} src The target to stop\n * listening to events on.\n * @param {goog.events.EventWrapper} wrapper Event wrapper to use.\n * @param {function(?):?|{handleEvent:function(?):?}|null} listener The\n * listener function to remove.\n * @param {boolean=} opt_capt In DOM-compliant browsers, this determines\n * whether the listener is fired during the capture or bubble phase of the\n * event.\n * @param {Object=} opt_scope Element in whose scope to call the listener.\n * @return {THIS} This object, allowing for chaining of calls.\n * @this {THIS}\n * @template THIS\n */\ngoog.events.EventHandler.prototype.unlistenWithWrapper = function(\n src, wrapper, listener, opt_capt, opt_scope) {\n 'use strict';\n var self = /** @type {!goog.events.EventHandler} */ (this);\n wrapper.unlisten(\n src, listener, opt_capt, opt_scope || self.handler_ || self, self);\n return self;\n};\n\n\n/**\n * Unlistens to all events.\n */\ngoog.events.EventHandler.prototype.removeAll = function() {\n 'use strict';\n goog.object.forEach(this.keys_, function(listenerObj, key) {\n 'use strict';\n if (this.keys_.hasOwnProperty(key)) {\n goog.events.unlistenByKey(listenerObj);\n }\n }, this);\n\n this.keys_ = {};\n};\n\n\n/**\n * Disposes of this EventHandler and removes all listeners that it registered.\n * @override\n * @protected\n */\ngoog.events.EventHandler.prototype.disposeInternal = function() {\n 'use strict';\n goog.events.EventHandler.superClass_.disposeInternal.call(this);\n this.removeAll();\n};\n\n\n/**\n * Default event handler\n * @param {goog.events.Event} e Event object.\n */\ngoog.events.EventHandler.prototype.handleEvent = function(e) {\n 'use strict';\n throw new Error('EventHandler.handleEvent not implemented');\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides a utility for tracing and debugging WebChannel\n * requests.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.require('goog.json');\ngoog.require('goog.log');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.net.XmlHttp.ReadyState');\n\n\n\n/**\n * Logs and keeps a buffer of debugging info for the Channel.\n *\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.WebChannelDebug = function() {\n 'use strict';\n /**\n * The logger instance.\n * @const\n * @private {?goog.log.Logger}\n */\n this.logger_ = goog.log.getLogger('goog.labs.net.webChannel.WebChannelDebug');\n\n /**\n * Whether to enable redact. Defaults to true.\n * @private {boolean}\n */\n this.redactEnabled_ = true;\n};\n\n\ngoog.scope(function() {\n'use strict';\nvar WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Turns off redact.\n */\nWebChannelDebug.prototype.disableRedact = function() {\n 'use strict';\n this.redactEnabled_ = false;\n};\n\n\n/**\n * Logs that the browser went offline during the lifetime of a request.\n * @param {goog.Uri} url The URL being requested.\n */\nWebChannelDebug.prototype.browserOfflineResponse = function(url) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'BROWSER_OFFLINE: ' + url;\n });\n};\n\n\n/**\n * Logs an XmlHttp request..\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {?string} postData The data posted in the request.\n */\nWebChannelDebug.prototype.xmlHttpChannelRequest = function(\n verb, uri, id, attempt, postData) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP REQ (' + id + ') [attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + self.maybeRedactPostData_(postData);\n });\n};\n\n\n/**\n * Logs the meta data received from an XmlHttp request.\n * @param {string} verb The request type (GET/POST).\n * @param {goog.Uri} uri The request destination.\n * @param {string|number|undefined} id The request id.\n * @param {number} attempt Which attempt # the request was.\n * @param {goog.net.XmlHttp.ReadyState} readyState The ready state.\n * @param {number} statusCode The HTTP status code.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseMetaData = function(\n verb, uri, id, attempt, readyState, statusCode) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'XMLHTTP RESP (' + id + ') [ attempt ' + attempt + ']: ' + verb +\n '\\n' + uri + '\\n' + readyState + ' ' + statusCode;\n });\n};\n\n\n/**\n * Logs the response data received from an XmlHttp request.\n * @param {string|number|undefined} id The request id.\n * @param {?string} responseText The response text.\n * @param {?string=} opt_desc Optional request description.\n */\nWebChannelDebug.prototype.xmlHttpChannelResponseText = function(\n id, responseText, opt_desc) {\n 'use strict';\n var self = this;\n this.info(function() {\n 'use strict';\n return 'XMLHTTP TEXT (' + id + '): ' + self.redactResponse_(responseText) +\n (opt_desc ? ' ' + opt_desc : '');\n });\n};\n\n\n/**\n * Logs a request timeout.\n * @param {goog.Uri} uri The uri that timed out.\n */\nWebChannelDebug.prototype.timeoutResponse = function(uri) {\n 'use strict';\n this.info(function() {\n 'use strict';\n return 'TIMEOUT: ' + uri;\n });\n};\n\n\n/**\n * Logs a debug message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.debug = function(text) {\n 'use strict';\n goog.log.fine(this.logger_, text);\n};\n\n\n/**\n * Logs an exception\n * @param {Error} e The error or error event.\n * @param {goog.log.Loggable=} opt_msg The optional message,\n * defaults to 'Exception'.\n */\nWebChannelDebug.prototype.dumpException = function(e, opt_msg) {\n 'use strict';\n goog.log.error(this.logger_, opt_msg || 'Exception', e);\n};\n\n\n/**\n * Logs an info message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.info = function(text) {\n 'use strict';\n goog.log.info(this.logger_, text);\n};\n\n\n/**\n * Logs a warning message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.warning = function(text) {\n 'use strict';\n goog.log.warning(this.logger_, text);\n};\n\n\n/**\n * Logs a severe message.\n * @param {!goog.log.Loggable} text The message.\n */\nWebChannelDebug.prototype.severe = function(text) {\n 'use strict';\n goog.log.error(this.logger_, text);\n};\n\n\n/**\n * Removes potentially private data from a response so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} responseText A JSON response to clean.\n * @return {?string} The cleaned response.\n * @private\n */\nWebChannelDebug.prototype.redactResponse_ = function(responseText) {\n 'use strict';\n if (!this.redactEnabled_) {\n return responseText;\n }\n\n if (!responseText) {\n return null;\n }\n\n try {\n var responseArray = JSON.parse(responseText);\n if (responseArray) {\n for (var i = 0; i < responseArray.length; i++) {\n if (Array.isArray(responseArray[i])) {\n this.maybeRedactArray_(responseArray[i]);\n }\n }\n }\n\n return goog.json.serialize(responseArray);\n } catch (e) {\n this.debug('Exception parsing expected JS array - probably was not JS');\n return responseText;\n }\n};\n\n\n/**\n * Removes data from a response array that may be sensitive.\n * @param {!Array<?>} array The array to clean.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactArray_ = function(array) {\n 'use strict';\n if (array.length < 2) {\n return;\n }\n var dataPart = array[1];\n if (!Array.isArray(dataPart)) {\n return;\n }\n if (dataPart.length < 1) {\n return;\n }\n\n var type = dataPart[0];\n if (type != 'noop' && type != 'stop' && type != 'close') {\n // redact all fields in the array\n for (var i = 1; i < dataPart.length; i++) {\n dataPart[i] = '';\n }\n }\n};\n\n\n/**\n * Removes potentially private data from a request POST body so that we don't\n * accidentally save private and personal data to the server logs.\n * @param {?string} data The data string to clean.\n * @return {?string} The data string with sensitive data replaced by 'redacted'.\n * @private\n */\nWebChannelDebug.prototype.maybeRedactPostData_ = function(data) {\n 'use strict';\n if (!this.redactEnabled_) {\n return data;\n }\n\n if (!data) {\n return null;\n }\n var out = '';\n var params = data.split('&');\n for (var i = 0; i < params.length; i++) {\n var param = params[i];\n var keyValue = param.split('=');\n if (keyValue.length > 1) {\n var key = keyValue[0];\n var value = keyValue[1];\n\n var keyParts = key.split('_');\n if (keyParts.length >= 2 && keyParts[1] == 'type') {\n out += key + '=' + value + '&';\n } else {\n out += key + '=' +\n 'redacted' +\n '&';\n }\n }\n }\n return out;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Static utilities for collecting stats associated with\n * ChannelRequest.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.requestStats');\ngoog.provide('goog.labs.net.webChannel.requestStats.Event');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachability');\ngoog.provide('goog.labs.net.webChannel.requestStats.ServerReachabilityEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.Stat');\ngoog.provide('goog.labs.net.webChannel.requestStats.StatEvent');\ngoog.provide('goog.labs.net.webChannel.requestStats.TimingEvent');\n\ngoog.require('goog.events.Event');\ngoog.require('goog.events.EventTarget');\n\n\ngoog.scope(function() {\n'use strict';\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\n\n/**\n * Events fired.\n * @const\n */\nrequestStats.Event = {};\n\n\n/**\n * Singleton event target for firing stat events\n * @type {?goog.events.EventTarget}\n * @private\n */\nrequestStats.eventTarget_ = null;\n\n/**\n * Singleton event target for firing stat events\n * @return {!goog.events.EventTarget}\n * @private\n */\nrequestStats.getStatEventTarget_ = function() {\n 'use strict';\n requestStats.eventTarget_ =\n requestStats.eventTarget_ || new goog.events.EventTarget();\n return requestStats.eventTarget_;\n};\n\n/**\n * The type of event that occurs every time some information about how reachable\n * the server is is discovered.\n */\nrequestStats.Event.SERVER_REACHABILITY_EVENT = 'serverreachability';\n\n\n/**\n * Types of events which reveal information about the reachability of the\n * server.\n * @enum {number}\n */\nrequestStats.ServerReachability = {\n REQUEST_MADE: 1,\n REQUEST_SUCCEEDED: 2,\n REQUEST_FAILED: 3,\n BACK_CHANNEL_ACTIVITY: 4 // any response data received\n};\n\n\n\n/**\n * Event class for SERVER_REACHABILITY_EVENT.\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.ServerReachabilityEvent = function(target, reachabilityType) {\n 'use strict';\n goog.events.Event.call(\n this, requestStats.Event.SERVER_REACHABILITY_EVENT, target);\n\n /**\n * @type {requestStats.ServerReachability}\n */\n this.reachabilityType = reachabilityType;\n};\ngoog.inherits(requestStats.ServerReachabilityEvent, goog.events.Event);\n\n\n/**\n * Notify the channel that a particular fine grained network event has occurred.\n * Should be considered package-private.\n * @param {requestStats.ServerReachability} reachabilityType\n * The reachability event type.\n */\nrequestStats.notifyServerReachabilityEvent = function(reachabilityType) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.ServerReachabilityEvent(target, reachabilityType));\n};\n\n\n/**\n * Stat Event that fires when things of interest happen that may be useful for\n * applications to know about for stats or debugging purposes.\n */\nrequestStats.Event.STAT_EVENT = 'statevent';\n\n\n/**\n * Enum that identifies events for statistics that are interesting to track.\n * @enum {number}\n */\nrequestStats.Stat = {\n /** Event indicating a new connection attempt. */\n CONNECT_ATTEMPT: 0,\n\n /** Event indicating a connection error due to a general network problem. */\n ERROR_NETWORK: 1,\n\n /**\n * Event indicating a connection error that isn't due to a general network\n * problem.\n */\n ERROR_OTHER: 2,\n\n /** Event indicating the start of test stage one. */\n TEST_STAGE_ONE_START: 3,\n\n /** Event indicating the start of test stage two. */\n TEST_STAGE_TWO_START: 4,\n\n /** Event indicating the first piece of test data was received. */\n TEST_STAGE_TWO_DATA_ONE: 5,\n\n /**\n * Event indicating that the second piece of test data was received and it was\n * received separately from the first.\n */\n TEST_STAGE_TWO_DATA_TWO: 6,\n\n /** Event indicating both pieces of test data were received simultaneously. */\n TEST_STAGE_TWO_DATA_BOTH: 7,\n\n /** Event indicating stage one of the test request failed. */\n TEST_STAGE_ONE_FAILED: 8,\n\n /** Event indicating stage two of the test request failed. */\n TEST_STAGE_TWO_FAILED: 9,\n\n /**\n * Event indicating that a buffering proxy is likely between the client and\n * the server.\n */\n PROXY: 10,\n\n /**\n * Event indicating that no buffering proxy is likely between the client and\n * the server.\n */\n NOPROXY: 11,\n\n /** Event indicating an unknown SID error. */\n REQUEST_UNKNOWN_SESSION_ID: 12,\n\n /** Event indicating a bad status code was received. */\n REQUEST_BAD_STATUS: 13,\n\n /** Event indicating incomplete data was received */\n REQUEST_INCOMPLETE_DATA: 14,\n\n /** Event indicating bad data was received */\n REQUEST_BAD_DATA: 15,\n\n /** Event indicating no data was received when data was expected. */\n REQUEST_NO_DATA: 16,\n\n /** Event indicating a request timeout. */\n REQUEST_TIMEOUT: 17,\n\n /**\n * Event indicating that the server never received our hanging GET and so it\n * is being retried.\n */\n BACKCHANNEL_MISSING: 18,\n\n /**\n * Event indicating that we have determined that our hanging GET is not\n * receiving data when it should be. Thus it is dead dead and will be retried.\n */\n BACKCHANNEL_DEAD: 19,\n\n /**\n * The browser declared itself offline during the lifetime of a request, or\n * was offline when a request was initially made.\n */\n BROWSER_OFFLINE: 20\n};\n\n\n\n/**\n * Event class for STAT_EVENT.\n *\n * @param {goog.events.EventTarget} eventTarget The stat event target for\n the channel.\n * @param {requestStats.Stat} stat The stat.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.StatEvent = function(eventTarget, stat) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.STAT_EVENT, eventTarget);\n\n /**\n * The stat\n * @type {requestStats.Stat}\n */\n this.stat = stat;\n};\ngoog.inherits(requestStats.StatEvent, goog.events.Event);\n\n\n/**\n * Returns the singleton event target for stat events.\n * @return {!goog.events.EventTarget} The event target for stat events.\n */\nrequestStats.getStatEventTarget = function() {\n 'use strict';\n return requestStats.getStatEventTarget_();\n};\n\n\n/**\n * Helper function to call the stat event callback.\n * @param {requestStats.Stat} stat The stat.\n */\nrequestStats.notifyStatEvent = function(stat) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(new requestStats.StatEvent(target, stat));\n};\n\n\n/**\n * An event that fires when POST requests complete successfully, indicating\n * the size of the POST and the round trip time.\n */\nrequestStats.Event.TIMING_EVENT = 'timingevent';\n\n\n\n/**\n * Event class for requestStats.Event.TIMING_EVENT\n *\n * @param {goog.events.EventTarget} target The stat event target for\n the channel.\n * @param {number} size The number of characters in the POST data.\n * @param {number} rtt The total round trip time from POST to response in MS.\n * @param {number} retries The number of times the POST had to be retried.\n * @constructor\n * @extends {goog.events.Event}\n */\nrequestStats.TimingEvent = function(target, size, rtt, retries) {\n 'use strict';\n goog.events.Event.call(this, requestStats.Event.TIMING_EVENT, target);\n\n /**\n * @type {number}\n */\n this.size = size;\n\n /**\n * @type {number}\n */\n this.rtt = rtt;\n\n /**\n * @type {number}\n */\n this.retries = retries;\n};\ngoog.inherits(requestStats.TimingEvent, goog.events.Event);\n\n\n/**\n * Helper function to notify listeners about POST request performance.\n *\n * @param {number} size Number of characters in the POST data.\n * @param {number} rtt The amount of time from POST start to response.\n * @param {number} retries The number of times the POST had to be retried.\n */\nrequestStats.notifyTimingEvent = function(size, rtt, retries) {\n 'use strict';\n const target = requestStats.getStatEventTarget_();\n target.dispatchEvent(\n new requestStats.TimingEvent(target, size, rtt, retries));\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * starts processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} startHook The function for the start hook.\n */\nrequestStats.setStartThreadExecutionHook = function(startHook) {\n 'use strict';\n requestStats.startExecutionHook_ = startHook;\n};\n\n\n/**\n * Allows the application to set an execution hooks for when a channel\n * stops processing requests. This is useful to track timing or logging\n * special information. The function takes no parameters and return void.\n * @param {Function} endHook The function for the end hook.\n */\nrequestStats.setEndThreadExecutionHook = function(endHook) {\n 'use strict';\n requestStats.endExecutionHook_ = endHook;\n};\n\n\n/**\n * Application provided execution hook for the start hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.startExecutionHook_ = function() {};\n\n\n/**\n * Application provided execution hook for the end hook.\n *\n * @type {Function}\n * @private\n */\nrequestStats.endExecutionHook_ = function() {};\n\n\n/**\n * Helper function to call the start hook\n */\nrequestStats.onStartExecution = function() {\n 'use strict';\n requestStats.startExecutionHook_();\n};\n\n\n/**\n * Helper function to call the end hook\n */\nrequestStats.onEndExecution = function() {\n 'use strict';\n requestStats.endExecutionHook_();\n};\n\n\n/**\n * Wrapper around SafeTimeout which calls the start and end execution hooks\n * with a try...finally block.\n * @param {Function} fn The callback function.\n * @param {number} ms The time in MS for the timer.\n * @return {number} The ID of the timer.\n */\nrequestStats.setTimeout = function(fn, ms) {\n 'use strict';\n if (typeof fn !== 'function') {\n throw new Error('Fn must not be null and must be a function');\n }\n return goog.global.setTimeout(function() {\n 'use strict';\n requestStats.onStartExecution();\n try {\n fn();\n } finally {\n requestStats.onEndExecution();\n }\n }, ms);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Error codes shared between goog.net.IframeIo and\n * goog.net.XhrIo.\n */\n\ngoog.provide('goog.net.ErrorCode');\n\n\n/**\n * Error codes\n * @enum {number}\n */\ngoog.net.ErrorCode = {\n\n /**\n * There is no error condition.\n */\n NO_ERROR: 0,\n\n /**\n * The most common error from iframeio, unfortunately, is that the browser\n * responded with an error page that is classed as a different domain. The\n * situations, are when a browser error page is shown -- 404, access denied,\n * DNS failure, connection reset etc.)\n *\n */\n ACCESS_DENIED: 1,\n\n /**\n * Currently the only case where file not found will be caused is when the\n * code is running on the local file system and a non-IE browser makes a\n * request to a file that doesn't exist.\n */\n FILE_NOT_FOUND: 2,\n\n /**\n * If Firefox shows a browser error page, such as a connection reset by\n * server or access denied, then it will fail silently without the error or\n * load handlers firing.\n */\n FF_SILENT_ERROR: 3,\n\n /**\n * Custom error provided by the client through the error check hook.\n */\n CUSTOM_ERROR: 4,\n\n /**\n * Exception was thrown while processing the request.\n */\n EXCEPTION: 5,\n\n /**\n * The Http response returned a non-successful http status code.\n */\n HTTP_ERROR: 6,\n\n /**\n * The request was aborted.\n */\n ABORT: 7,\n\n /**\n * The request timed out.\n */\n TIMEOUT: 8,\n\n /**\n * The resource is not available offline.\n */\n OFFLINE: 9,\n};\n\n\n/**\n * Returns a friendly error message for an error code. These messages are for\n * debugging and are not localized.\n * @param {goog.net.ErrorCode} errorCode An error code.\n * @return {string} A message for debugging.\n */\ngoog.net.ErrorCode.getDebugMessage = function(errorCode) {\n 'use strict';\n switch (errorCode) {\n case goog.net.ErrorCode.NO_ERROR:\n return 'No Error';\n\n case goog.net.ErrorCode.ACCESS_DENIED:\n return 'Access denied to content document';\n\n case goog.net.ErrorCode.FILE_NOT_FOUND:\n return 'File not found';\n\n case goog.net.ErrorCode.FF_SILENT_ERROR:\n return 'Firefox silently errored';\n\n case goog.net.ErrorCode.CUSTOM_ERROR:\n return 'Application custom error';\n\n case goog.net.ErrorCode.EXCEPTION:\n return 'An exception occurred';\n\n case goog.net.ErrorCode.HTTP_ERROR:\n return 'Http response at 400 or 500 level';\n\n case goog.net.ErrorCode.ABORT:\n return 'Request was aborted';\n\n case goog.net.ErrorCode.TIMEOUT:\n return 'Request timed out';\n\n case goog.net.ErrorCode.OFFLINE:\n return 'The resource is not available offline';\n\n default:\n return 'Unrecognized error code';\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Common events for the network classes.\n */\n\n\ngoog.provide('goog.net.EventType');\n\n\n/**\n * Event names for network events\n * @enum {string}\n */\ngoog.net.EventType = {\n COMPLETE: 'complete',\n SUCCESS: 'success',\n ERROR: 'error',\n ABORT: 'abort',\n READY: 'ready',\n READY_STATE_CHANGE: 'readystatechange',\n TIMEOUT: 'timeout',\n INCREMENTAL_DATA: 'incrementaldata',\n PROGRESS: 'progress',\n // DOWNLOAD_PROGRESS and UPLOAD_PROGRESS are special events dispatched by\n // goog.net.XhrIo to allow binding listeners specific to each type of\n // progress.\n DOWNLOAD_PROGRESS: 'downloadprogress',\n UPLOAD_PROGRESS: 'uploadprogress',\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface for a factory for creating XMLHttpRequest objects\n * and metadata about them.\n */\n\ngoog.provide('goog.net.XmlHttpFactory');\n\n/** @suppress {extraRequire} Typedef. */\ngoog.require('goog.net.XhrLike');\n\n\n\n/**\n * Abstract base class for an XmlHttpRequest factory.\n * @constructor\n */\ngoog.net.XmlHttpFactory = function() {};\n\n\n/**\n * Cache of options - we only actually call internalGetOptions once.\n * @type {?Object}\n * @private\n */\ngoog.net.XmlHttpFactory.prototype.cachedOptions_ = null;\n\n\n/**\n * @return {!goog.net.XhrLike.OrNative} A new XhrLike instance.\n */\ngoog.net.XmlHttpFactory.prototype.createInstance = goog.abstractMethod;\n\n\n/**\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n */\ngoog.net.XmlHttpFactory.prototype.getOptions = function() {\n 'use strict';\n return this.cachedOptions_ ||\n (this.cachedOptions_ = this.internalGetOptions());\n};\n\n\n/**\n * Override this method in subclasses to preserve the caching offered by\n * getOptions().\n * @return {Object} Options describing how xhr objects obtained from this\n * factory should be used.\n * @protected\n */\ngoog.net.XmlHttpFactory.prototype.internalGetOptions = goog.abstractMethod;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The API spec for the WebChannel messaging library.\n *\n * Similar to HTML5 WebSocket, WebChannel offers an abstraction for\n * point-to-point socket-like communication between a browser client and\n * a remote origin.\n *\n * WebChannels are created via <code>WebChannel</code>. Multiple WebChannels\n * may be multiplexed over the same WebChannelTransport, which encapsulates\n * the underlying physical connectivity over standard wire protocols\n * such as HTTP.\n *\n * A WebChannel in turn represents a logical communication channel between\n * the client and server endpoint. A WebChannel remains open for as long\n * as the client or server endpoint allows.\n *\n * Messages are delivered in-order and reliably over the same WebChannel,\n * and the choice of the underlying wire protocols is completely transparent\n * to the API users.\n *\n * Note that we have no immediate plan to move this API out of labs. While\n * the implementation is production ready, the API is subject to change.\n */\n\ngoog.provide('goog.net.WebChannel');\ngoog.provide('goog.net.WebChannel.Options');\n\ngoog.require('goog.events');\ngoog.require('goog.events.Event');\ngoog.require('goog.events.Listenable');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * A WebChannel represents a logical bi-directional channel over which the\n * client communicates with a remote server that holds the other endpoint\n * of the channel. A WebChannel is always created in the context of a shared\n * {@link WebChannelTransport} instance. It is up to the underlying client-side\n * and server-side implementations to decide how or when multiplexing is\n * to be enabled.\n *\n * @interface\n * @extends {goog.events.Listenable}\n */\ngoog.net.WebChannel = function() {};\n\n\n\n/**\n * This interface defines a pluggable API to allow WebChannel runtime to support\n * customized algorithms in order to recover from transient failures such as\n * those failures caused by network or proxies (intermediaries).\n *\n * The algorithm may also choose to fail-fast, e.g. switch the client to some\n * offline mode.\n *\n * Extra measurements and logging could also be implemented in the custom\n * module, which has the full knowledge of all the state transitions\n * (due to failures).\n *\n * A default algorithm will be provided by the webchannel library itself. Custom\n * algorithms are expected to be tailored to specific client platforms or\n * networking environments, e.g. mobile, cellular network.\n *\n * @interface\n */\ngoog.net.WebChannel.FailureRecovery = function() {};\n\n\n/**\n * Configuration spec for newly created WebChannel instances.\n *\n * WebChannels are configured in the context of the containing\n * {@link WebChannelTransport}. The configuration parameters are specified\n * when a new instance of WebChannel is created via {@link WebChannelTransport}.\n * @record\n */\ngoog.net.WebChannel.Options = function() {};\n\n/**\n * Transport-metadata support.\n *\n * Custom HTTP headers to be added to every message sent to the\n * server. This object is mutable, and custom headers may be changed, removed,\n * or added during the runtime after a channel has been opened.\n *\n * Custom headers may trigger CORS preflight. See other related options.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageHeaders;\n\n/**\n * Transport-metadata support.\n *\n * Similar to messageHeaders, but any custom HTTP headers will\n * be sent only once when the channel is opened as part of the handshae request.\n * Typical usage is to send an auth header to the server, which only checks\n * the auth header at the time during the handshake when the channel is opened.\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.initMessageHeaders;\n\n/**\n * Sent as initMessageHeaders via X-WebChannel-Content-Type,\n * to inform the server the MIME type of WebChannel messages.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageContentType;\n\n/**\n * Transport-metadata support.\n *\n * Custom url query parameters to be added to every message\n * sent to the server. This object is mutable, and custom parameters may be\n * changed, removed or added during the runtime after a channel has been opened.\n *\n * TODO: initMessageUrlParams\n * TODO: closeMessageUrlParams (custom url query params to be added to the\n * channel-close message. Custom headers are not supported due to the use of\n * SendBeacon)\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.messageUrlParams;\n\n/**\n * Whether a special header should be added to\n * each message so that the server can dispatch webchannel messages without\n * knowing the URL path prefix. Defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProtocolHeaderRequired;\n\n/**\n * The maximum number of in-flight HTTP requests allowed\n * when SPDY is enabled. Currently we only detect SPDY in Chrome.\n * This parameter defaults to 10. When SPDY is not enabled, this parameter\n * will have no effect.\n * @type {number|undefined}\n */\ngoog.net.WebChannel.Options.prototype.concurrentRequestLimit;\n\n/**\n * Setting this to true to allow the use of sub-domains\n * (as configured by the server) to send XHRs with the CORS withCredentials\n * bit set to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.supportsCrossDomainXhr;\n\n/**\n * Whether to bypass v8 encoding of client-sent messages.\n * This defaults to false now due to legacy servers. New applications should\n * always configure this option to true.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.sendRawJson;\n\n/**\n * The URL parameter name that contains the session id (for sticky routing of\n * HTTP requests). When this param is specified, a server that supports this\n * option will respond with an opaque session id as part of the initial\n * handshake (via the X-HTTP-Session-Id header); and all the subsequent requests\n * will contain the httpSessionIdParam. This option will take precedence over\n * any duplicated parameter specified with messageUrlParams, whose value will be\n * ignored.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpSessionIdParam;\n\n/**\n * The URL parameter name to allow custom HTTP\n * headers to be overwritten as a URL param to bypass CORS preflight.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.httpHeadersOverwriteParam;\n\n/**\n * Whether to encode Options.initMessageHeaders in the HTTP request body.\n * This option defaults to false. If true, Options.httpHeadersOverwriteParam\n * will be ignored.\n *\n * This option should not be set if Options.fastHandshake is set (which\n * uses GET for handshake).\n *\n * Web-only feature.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.encodeInitMessageHeaders;\n\n/**\n * Whether to force long-polling from client to server.\n * This defaults to false. Long-polling may be necessary when a (MITM) proxy\n * is buffering data sent by the server.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.forceLongPolling;\n\n/**\n * Whether to enable automatic detection of buffering proxies. In the presence\n * of any buffering proxy, webchannel will use long-polling to send messages\n * from the server to the client. This option defaults to false.\n * Currently when fastHandshake is enabled, this option will be ignored.\n * Compared to \"forceLongPolling\", this option may introduce up to 2-RTT\n * extra latency for delivering messages generated immediately after the\n * handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.detectBufferingProxy;\n\n/**\n * Enable true 0-RTT message delivery, including\n * leveraging QUIC 0-RTT (which requires GET to be used). This option\n * defaults to false. Note it is allowed to send messages before Open event is\n * received, after a channel has been opened. In order to enable 0-RTT,\n * messages will be encoded as part of URL and therefore there needs be a size\n * limit for those initial messages that are sent immediately as part of the\n * GET handshake request. With sendRawJson=true, this limit is currently set\n * to 4K chars and data beyond this limit will be buffered till the handshake\n * (1-RTT) finishes. With sendRawJson=false, it's up to the application\n * to limit the amount of data that is sent as part of the handshake.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.fastHandshake;\n\n/**\n * Enable the blocking RPC semantics for the handshake:\n * 1) the completion of handshake is blocked by the server-side application\n * logic for handling the handshake (HTTP) request; 2) the client application\n * will inspect the handshake (HTTP) response headers as generated\n * by the server application (v.s. by only the webchannel runtime). This option\n * defaults to false.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.blockingHandshake;\n\n/**\n * Whether to disable logging redact. By default, redact is\n * enabled to remove any message payload or user-provided info\n * from closure logs.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.disableRedact;\n\n/**\n * Inform the server about the client profile to enable\n * customized configs that are optimized for certain clients or environments.\n * Currently this information is sent via X-WebChannel-Client-Profile header.\n * @type {string|undefined}\n */\ngoog.net.WebChannel.Options.prototype.clientProfile;\n\n/**\n * The internal channel parameter name to allow\n * experimental channel configurations. Supported options include fastfail,\n * baseRetryDelayMs, retryDelaySeedMs, forwardChannelMaxRetries and\n * forwardChannelRequestTimeoutMs. Note that these options are subject to\n * change.\n * @type {!Object<string, boolean|number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.internalChannelParams;\n\n/**\n * Allows the caller to override the factory used to create\n * XMLHttpRequest objects. This is introduced to disable CORS on firefox OS.\n * @type {!goog.net.XmlHttpFactory|undefined}\n */\ngoog.net.WebChannel.Options.prototype.xmlHttpFactory;\n\n/**\n * Client-side thresholds that decide when to refresh\n * an underlying HTTP request, to limit memory consumption due to XHR buffering\n * or compression context. The client-side thresholds should be significantly\n * smaller than the server-side thresholds. This allows the client to eliminate\n * any latency introduced by request refreshing, i.e. an RTT window during which\n * messages may be buffered on the server-side. Supported params include\n * totalBytesReceived, totalDurationMs.\n * @type {!Object<string, number>|undefined}\n */\ngoog.net.WebChannel.Options.prototype.requestRefreshThresholds;\n\n/**\n * This is an experimental feature to use WHATWG Fetch/streams (when supported)\n * for the backchannel. If a custom 'xmlHttpFactory' is speficied, this option\n * will not be effective. This option defaults to false now and will eventually\n * be turned on by default.\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.useFetchStreams;\n\n/**\n * Opt-in to enable Chrome origin trials from the WebChannel client. See\n * https://github.com/GoogleChrome/OriginTrials\n *\n * Origin trial history:\n * - fetch upload (11/2020 - 07/2021)\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * Participating in the origin trials will help Chrome to release new Web\n * platform features sooner, which will in turn help improve WebChannel\n * performance.\n *\n * Origin trials are not expected to interfere with WebChannel wire messages\n * and should not introduce any noticeable overhead.\n *\n * This is enabled by default with any on-going origin-trial.\n *\n * @type {boolean|undefined}\n */\ngoog.net.WebChannel.Options.prototype.enableOriginTrials;\n\n\n/**\n * Types that are allowed as message data.\n *\n * Note that JS objects (sent by the client) can only have string encoded\n * values due to the limitation of the current wire protocol.\n *\n * Unicode strings (sent by the server) may or may not need be escaped, as\n * decided by the server.\n *\n * @typedef {(!ArrayBuffer|!Blob|!Object<string, !Object|string>|!Array|string)}\n */\ngoog.net.WebChannel.MessageData;\n\n\n/**\n * Open the WebChannel against the URI specified in the constructor.\n */\ngoog.net.WebChannel.prototype.open = goog.abstractMethod;\n\n\n/**\n * Close the WebChannel.\n *\n * This is a full close (shutdown) with no guarantee of FIFO delivery in respect\n * to any in-flight messages sent to the server.\n *\n * If you need such a guarantee, see the Half the halfClose() method.\n */\ngoog.net.WebChannel.prototype.close = goog.abstractMethod;\n\n\n/**\n * Half-close the WebChannel.\n *\n * Half-close semantics:\n * 1. delivered as a regular message in FIFO programming order\n * 2. the server is expected to return a half-close too (with or without\n * application involved), which will trigger a full close (shutdown)\n * on the client side\n * 3. for now, the half-close event defined for server-initiated\n * half-close is not exposed to the client application\n * 4. a client-side half-close may be triggered internally when the client\n * receives a half-close from the server; and the client is expected to\n * do a full close after the half-close is acked and delivered\n * on the server-side.\n * 5. Full close is always a forced one. See the close() method.\n *\n * New messages sent after halfClose() will be dropped.\n *\n * NOTE: This is not yet implemented, and will throw an exception if called.\n */\ngoog.net.WebChannel.prototype.halfClose = goog.abstractMethod;\n\n\n/**\n * Sends a message to the server that maintains the other endpoint of\n * the WebChannel.\n *\n * O-RTT behavior:\n * 1. messages sent before open() is called will always be delivered as\n * part of the handshake, i.e. with 0-RTT\n * 2. messages sent after open() is called but before the OPEN event\n * is received will be delivered as part of the handshake if\n * send() is called from the same execution context as open().\n * 3. otherwise, those messages will be buffered till the handshake\n * is completed (which will fire the OPEN event).\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n */\ngoog.net.WebChannel.prototype.send = goog.abstractMethod;\n\n\n/**\n * Common events fired by WebChannels.\n * @enum {string}\n */\ngoog.net.WebChannel.EventType = {\n /** Dispatched when the channel is opened. */\n OPEN: goog.events.getUniqueId('open'),\n\n /** Dispatched when the channel is closed. */\n CLOSE: goog.events.getUniqueId('close'),\n\n /**\n * Dispatched when the channel is aborted due to errors.\n *\n * For backward compatibility reasons, a CLOSE event will also be\n * dispatched, following the ERROR event, which indicates that the channel\n * has been completely shutdown .\n */\n ERROR: goog.events.getUniqueId('error'),\n\n /** Dispatched when the channel has received a new message. */\n MESSAGE: goog.events.getUniqueId('message')\n};\n\n\n\n/**\n * The event interface for the MESSAGE event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.MessageEvent = function() {\n 'use strict';\n goog.net.WebChannel.MessageEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.MESSAGE);\n};\ngoog.inherits(goog.net.WebChannel.MessageEvent, goog.events.Event);\n\n\n/**\n * The content of the message received from the server.\n *\n * @type {!goog.net.WebChannel.MessageData}\n */\ngoog.net.WebChannel.MessageEvent.prototype.data;\n\n\n/**\n * The metadata key when the MESSAGE event represents a metadata message.\n *\n * @type {string|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.metadataKey;\n\n\n/**\n * Metadata as HTTP status code. Typically sent before the channel is\n * half-closed by the server. To be implemented.\n *\n * @type {number|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.statusCode;\n\n\n/**\n * Metadata as HTTP headers. Typically sent before the channel is\n * half-closed by the server. To be implemented.\n *\n * @type {!Object<string, string>|undefined}\n */\ngoog.net.WebChannel.MessageEvent.prototype.responseHeaders;\n\n\n/**\n * WebChannel level error conditions.\n *\n * Summary of error debugging and reporting in WebChannel:\n *\n * Network Error\n * 1. By default the webchannel library will set the error status to\n * NETWORK_ERROR when a channel has to be aborted or closed. NETWORK_ERROR\n * may be recovered by the application by retrying and opening a new channel.\n * 2. There may be lost messages (not acked by the server) when a channel is\n * aborted. Currently we don't have a public API to retrieve messages that\n * are waiting to be acked on the client side. File a bug if you think it\n * is useful to expose such an API.\n * 3. Details of why a channel fails are available via closure debug logs,\n * and stats events (see webchannel/requeststats.js). Those are internal\n * stats and are subject to change. File a bug if you think it's useful to\n * version and expose such stats as part of the WebChannel API.\n *\n * Server Error\n * 1. SERVER_ERROR is intended to indicate a non-recoverable condition, e.g.\n * when auth fails.\n * 2. We don't currently generate any such errors, because most of the time\n * it's the responsibility of upper-layer frameworks or the application\n * itself to indicate to the client why a webchannel has been failed\n * by the server.\n * 3. When a channel is failed by the server explicitly, we still signal\n * NETWORK_ERROR to the client. Explicit server failure may happen when the\n * server does a fail-over, or becomes overloaded, or conducts a forced\n * shutdown etc.\n * 4. We use some heuristic to decide if the network (aka cloud) is down\n * v.s. the actual server is down.\n *\n * RuntimeProperties.getLastStatusCode is a useful state that we expose to\n * the client to indicate the HTTP response status code of the last HTTP\n * request initiated by the WebChannel client library, for debugging\n * purposes only.\n *\n * See WebChannel.Options.backChannelFailureRecovery and\n * WebChannel.FailureRecovery to install a custom failure-recovery algorithm.\n *\n * @enum {number}\n */\ngoog.net.WebChannel.ErrorStatus = {\n /** No error has occurred. */\n OK: 0,\n\n /** Communication to the server has failed. */\n NETWORK_ERROR: 1,\n\n /** The server fails to accept or process the WebChannel. */\n SERVER_ERROR: 2\n};\n\n\n\n/**\n * The event interface for the ERROR event.\n *\n * @constructor\n * @extends {goog.events.Event}\n */\ngoog.net.WebChannel.ErrorEvent = function() {\n 'use strict';\n goog.net.WebChannel.ErrorEvent.base(\n this, 'constructor', goog.net.WebChannel.EventType.ERROR);\n};\ngoog.inherits(goog.net.WebChannel.ErrorEvent, goog.events.Event);\n\n\n/**\n * The error status.\n *\n * @type {!goog.net.WebChannel.ErrorStatus}\n */\ngoog.net.WebChannel.ErrorEvent.prototype.status;\n\n\n/**\n * @return {!goog.net.WebChannel.RuntimeProperties} The runtime properties\n * of the WebChannel instance.\n */\ngoog.net.WebChannel.prototype.getRuntimeProperties = goog.abstractMethod;\n\n\n\n/**\n * The runtime properties of the WebChannel instance.\n *\n * This class is defined for debugging and monitoring purposes, as well as for\n * runtime functions that the application may choose to manage by itself.\n *\n * @interface\n */\ngoog.net.WebChannel.RuntimeProperties = function() {};\n\n\n/**\n * @return {number} The effective limit for the number of concurrent HTTP\n * requests that are allowed to be made for sending messages from the client\n * to the server. When SPDY is not enabled, this limit will be one.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getConcurrentRequestLimit =\n goog.abstractMethod;\n\n\n/**\n * For applications that need support multiple channels (e.g. from\n * different tabs) to the same origin, use this method to decide if SPDY is\n * enabled and therefore it is safe to open multiple channels.\n *\n * If SPDY is disabled, the application may choose to limit the number of active\n * channels to one or use other means such as sub-domains to work around\n * the browser connection limit.\n *\n * @return {boolean} Whether SPDY is enabled for the origin against which\n * the channel is created.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.isSpdyEnabled =\n goog.abstractMethod;\n\n\n/**\n * @return {number} The number of requests (for sending messages to the server)\n * that are pending. If this number is approaching the value of\n * getConcurrentRequestLimit(), client-to-server message delivery may experience\n * a higher latency.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getPendingRequestCount =\n goog.abstractMethod;\n\n\n/**\n * For applications to query the current HTTP session id, sent by the server\n * during the initial handshake.\n *\n * @return {?string} the HTTP session id or null if no HTTP session is in use.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getHttpSessionId =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method generates an in-band commit request to the server, which will\n * ack the commit request as soon as all messages sent prior to this commit\n * request have been committed by the application.\n *\n * Committing a message has a stronger semantics than delivering a message\n * to the application. Detail spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Timeout or cancellation is not supported and the application is expected to\n * abort the channel if the commit-ack fails to arrive in time.\n *\n * ===\n *\n * This is currently implemented only in the client layer and the commit\n * callback will be invoked after all the pending client-sent messages have been\n * delivered by the server-side webchannel endpoint. This semantics is\n * different and weaker than what's required for end-to-end ack which requires\n * the server application to ack the in-order delivery of messages that are sent\n * before the commit request is issued.\n *\n * Commit should only be called after the channel open event is received.\n * Duplicated commits are allowed and only the last callback is guaranteed.\n * Commit called after the channel has been closed will be ignored.\n *\n * @param {function()} callback The callback will be invoked once an\n * ack has been received for the current commit or any newly issued commit.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.commit = goog.abstractMethod;\n\n\n/**\n * This method may be used by the application to recover from a peer failure\n * or to enable sender-initiated flow-control.\n *\n * Detail spec: https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * Note that the caller should NOT modify the list of returned messages.\n *\n * @return {!Array<!goog.net.WebChannel.MessageData>} The list of messages that\n * have not received commit-ack from the server; or if no commit has been\n * issued, the list of messages that have not been delivered to the server\n * application.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getNonAckedMessages =\n goog.abstractMethod;\n\n\n/**\n * A low water-mark message count to notify the application when the\n * flow-control condition is cleared, that is, when the application is\n * able to send more messages.\n *\n * We expect the application to configure a high water-mark message count,\n * which is checked via getNonAckedMessageCount(). When the high water-mark\n * is exceeded, the application should install a callback via this method\n * to be notified when to start to send new messages.\n *\n * This is not yet implemented.\n *\n * @param {number} count The low water-mark count. It is an error to pass\n * a non-positive value.\n * @param {function()} callback The call back to notify the application\n * when NonAckedMessageCount is below the specified low water-mark count.\n * Any previously registered callback is cleared. This new callback will\n * be cleared once it has been fired, or when the channel is closed or aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method registers a callback to handle the commit request sent\n * by the server. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {function(!Object)} callback The callback will take an opaque\n * commitId which needs be passed back to the server when an ack-commit\n * response is generated by the client application, via ackCommit().\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.onCommit = goog.abstractMethod;\n\n\n/**\n * Experimental API.\n *\n * This method is used by the application to generate an ack-commit response\n * for the given commitId. Commit protocol spec:\n * https://github.com/bidiweb/webchannel/blob/master/commit.md\n *\n * This is not yet implemented.\n *\n * @param {!Object} commitId The commitId which denotes the commit request\n * from the server that needs be ack'ed.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.ackCommit = goog.abstractMethod;\n\n\n/**\n * Transport-metadata support.\n *\n * TODO: getLastResponseHeaders (only for non-200 status)\n * TODO: getInitStatusCode (handshake)\n * TODO: getInitResponseHeaders (handshake)\n *\n * Note that response headers from client-initiated close (abort) are not\n * available.\n *\n * In future when client-initiated half-close is supported, its response status\n * will be available via this API.\n *\n * @return {number} The non-200 HTTP status code received that causes the\n * channel to be aborted.\n */\ngoog.net.WebChannel.RuntimeProperties.prototype.getLastStatusCode =\n goog.abstractMethod;\n\n\n/**\n * Enum to indicate the current recovery state.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.State = {\n /** Initial state. */\n INIT: 'init',\n\n /** Once a failure has been detected. */\n FAILED: 'failed',\n\n /**\n * Once a recovery operation has been issued, e.g. a new request to resume\n * communication.\n */\n RECOVERING: 'recovering',\n\n /** The channel has been closed. */\n CLOSED: 'closed'\n};\n\n\n/**\n * Enum to indicate different failure conditions as detected by the webchannel\n * runtime.\n *\n * This enum is to be used only between the runtime and FailureRecovery module,\n * and new states are expected to be introduced in future.\n *\n * @enum {string}\n */\ngoog.net.WebChannel.FailureRecovery.FailureCondition = {\n /**\n * The HTTP response returned a non-successful http status code.\n */\n HTTP_ERROR: 'http_error',\n\n /**\n * The request was aborted.\n */\n ABORT: 'abort',\n\n /**\n * The request timed out.\n */\n TIMEOUT: 'timeout',\n\n /**\n * Exception was thrown while processing the request/response.\n */\n EXCEPTION: 'exception'\n};\n\n\n/**\n * @return {!goog.net.WebChannel.FailureRecovery.State} the current state,\n * mainly for debugging use.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.getState = goog.abstractMethod;\n\n\n/**\n * This method is for WebChannel runtime to set the current failure condition\n * and to provide a callback for the algorithm to signal to the runtime\n * when it is time to issue a recovery operation, e.g. a new request to the\n * server.\n *\n * Supported transitions include:\n * INIT->FAILED\n * FAILED->FAILED (re-entry ok)\n * RECOVERY->FAILED.\n *\n * Ignored if state == CLOSED.\n *\n * Advanced implementations are expected to track all the state transitions\n * and their timestamps for monitoring purposes.\n *\n * @param {!goog.net.WebChannel.FailureRecovery.FailureCondition} failure The\n * new failure condition generated by the WebChannel runtime.\n * @param {!Function} operation The callback function to the WebChannel\n * runtime to issue a recovery operation, e.g. a new request. E.g. the default\n * recovery algorithm will issue timeout-based recovery operations.\n * Post-condition for the callback: state transition to RECOVERING.\n *\n * @return {!goog.net.WebChannel.FailureRecovery.State} The updated state\n * as decided by the failure recovery module. Upon a recoverable failure event,\n * the state is transitioned to RECOVERING; or the state is transitioned to\n * FAILED which indicates a fail-fast decision for the runtime to execute.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.setFailure = goog.abstractMethod;\n\n\n/**\n * The Webchannel runtime needs call this method when webchannel is closed or\n * aborted.\n *\n * Once the instance is closed, any access to the instance will be a no-op.\n */\ngoog.net.WebChannel.FailureRecovery.prototype.close = goog.abstractMethod;\n\n\n/**\n * A request header to indicate to the server the messaging protocol\n * each HTTP message is speaking.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL = 'X-Client-Protocol';\n\n\n/**\n * The value for x-client-protocol when the messaging protocol is WebChannel.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL = 'webchannel';\n\n\n/**\n * A response header for the server to signal the wire-protocol that\n * the browser establishes with the server (or proxy), e.g. \"spdy\" (aka http/2)\n * \"quic\". This information avoids the need to use private APIs to decide if\n * HTTP requests are multiplexed etc.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL = 'X-Client-Wire-Protocol';\n\n\n/**\n * A response header for the server to send back the HTTP session id as part of\n * the initial handshake. The value of the HTTP session id is opaque to the\n * WebChannel protocol.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_SESSION_ID = 'X-HTTP-Session-Id';\n\n\n/**\n * A response header for the server to send back any initial response data as a\n * header to avoid any possible buffering by an intermediary, which may\n * be undesired during the handshake.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_HTTP_INITIAL_RESPONSE = 'X-HTTP-Initial-Response';\n\n\n/**\n * A request header for specifying the content-type of WebChannel messages,\n * e.g. application-defined JSON encoding styles. Currently this header\n * is sent by the client via initMessageHeaders when the channel is opened.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE = 'X-WebChannel-Content-Type';\n\n\n/**\n * A request header for specifying the client profile in order to apply\n * customized config params on the server side, e.g. timeouts.\n *\n * @type {string}\n */\ngoog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE = 'X-WebChannel-Client-Profile';\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Low level handling of XMLHttpRequest.\n */\n\ngoog.provide('goog.net.DefaultXmlHttpFactory');\ngoog.provide('goog.net.XmlHttp');\ngoog.provide('goog.net.XmlHttp.OptionType');\ngoog.provide('goog.net.XmlHttp.ReadyState');\ngoog.provide('goog.net.XmlHttpDefines');\n\ngoog.require('goog.asserts');\ngoog.require('goog.net.WrapperXmlHttpFactory');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.requireType('goog.net.XhrLike');\n\n\n/**\n * Static class for creating XMLHttpRequest objects.\n * @return {!goog.net.XhrLike.OrNative} A new XMLHttpRequest object.\n */\ngoog.net.XmlHttp = function() {\n 'use strict';\n return goog.net.XmlHttp.factory_.createInstance();\n};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true bypasses the ActiveX probing code.\n * NOTE(ruilopes): Due to the way JSCompiler works, this define *will not* strip\n * out the ActiveX probing code from binaries. To achieve this, use\n * `goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR` instead.\n * TODO(ruilopes): Collapse both defines.\n */\ngoog.net.XmlHttp.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttp.ASSUME_NATIVE_XHR', false);\n\n\n/** @const */\ngoog.net.XmlHttpDefines = {};\n\n\n/**\n * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to\n * true eliminates the ActiveX probing code.\n */\ngoog.net.XmlHttpDefines.ASSUME_NATIVE_XHR =\n goog.define('goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR', false);\n\n\n/**\n * Gets the options to use with the XMLHttpRequest objects obtained using\n * the static methods.\n * @return {Object} The options.\n */\ngoog.net.XmlHttp.getOptions = function() {\n 'use strict';\n return goog.net.XmlHttp.factory_.getOptions();\n};\n\n\n/**\n * Type of options that an XmlHttp object can have.\n * @enum {number}\n */\ngoog.net.XmlHttp.OptionType = {\n /**\n * Whether a goog.nullFunction should be used to clear the onreadystatechange\n * handler instead of null.\n */\n USE_NULL_FUNCTION: 0,\n\n /**\n * NOTE(user): In IE if send() errors on a *local* request the readystate\n * is still changed to COMPLETE. We need to ignore it and allow the\n * try/catch around send() to pick up the error.\n */\n LOCAL_REQUEST_ERROR: 1,\n};\n\n\n/**\n * Status constants for XMLHTTP, matches:\n * https://msdn.microsoft.com/en-us/library/ms534361(v=vs.85).aspx\n * @enum {number}\n */\ngoog.net.XmlHttp.ReadyState = {\n /**\n * Constant for when xmlhttprequest.readyState is uninitialized\n */\n UNINITIALIZED: 0,\n\n /**\n * Constant for when xmlhttprequest.readyState is loading.\n */\n LOADING: 1,\n\n /**\n * Constant for when xmlhttprequest.readyState is loaded.\n */\n LOADED: 2,\n\n /**\n * Constant for when xmlhttprequest.readyState is in an interactive state.\n */\n INTERACTIVE: 3,\n\n /**\n * Constant for when xmlhttprequest.readyState is completed\n */\n COMPLETE: 4,\n};\n\n\n/**\n * The global factory instance for creating XMLHttpRequest objects.\n * @type {goog.net.XmlHttpFactory}\n * @private\n */\ngoog.net.XmlHttp.factory_;\n\n\n/**\n * Sets the factories for creating XMLHttpRequest objects and their options.\n * @param {Function} factory The factory for XMLHttpRequest objects.\n * @param {Function} optionsFactory The factory for options.\n * @deprecated Use setGlobalFactory instead.\n */\ngoog.net.XmlHttp.setFactory = function(factory, optionsFactory) {\n 'use strict';\n goog.net.XmlHttp.setGlobalFactory(new goog.net.WrapperXmlHttpFactory(\n goog.asserts.assert(factory), goog.asserts.assert(optionsFactory)));\n};\n\n\n/**\n * Sets the global factory object.\n * @param {!goog.net.XmlHttpFactory} factory New global factory object.\n */\ngoog.net.XmlHttp.setGlobalFactory = function(factory) {\n 'use strict';\n goog.net.XmlHttp.factory_ = factory;\n};\n\n\n\n/**\n * Default factory to use when creating xhr objects. You probably shouldn't be\n * instantiating this directly, but rather using it via goog.net.XmlHttp.\n * @extends {goog.net.XmlHttpFactory}\n * @constructor\n */\ngoog.net.DefaultXmlHttpFactory = function() {\n 'use strict';\n goog.net.XmlHttpFactory.call(this);\n};\ngoog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.createInstance = function() {\n 'use strict';\n const progId = this.getProgId_();\n if (progId) {\n return new ActiveXObject(progId);\n } else {\n return new XMLHttpRequest();\n }\n};\n\n\n/** @override */\ngoog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() {\n 'use strict';\n const progId = this.getProgId_();\n const options = {};\n if (progId) {\n options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true;\n options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true;\n }\n return options;\n};\n\n\n/**\n * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized.\n * @type {string|undefined}\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.ieProgId_;\n\n\n/**\n * Initialize the private state used by other functions.\n * @return {string} The ActiveX PROG ID string to use to create xhr's in IE.\n * @private\n */\ngoog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() {\n 'use strict';\n if (goog.net.XmlHttp.ASSUME_NATIVE_XHR ||\n goog.net.XmlHttpDefines.ASSUME_NATIVE_XHR) {\n return '';\n }\n\n // The following blog post describes what PROG IDs to use to create the\n // XMLHTTP object in Internet Explorer:\n // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx\n // However we do not (yet) fully trust that this will be OK for old versions\n // of IE on Win9x so we therefore keep the last 2.\n if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' &&\n typeof ActiveXObject != 'undefined') {\n // Candidate Active X types.\n const ACTIVE_X_IDENTS = [\n 'MSXML2.XMLHTTP.6.0',\n 'MSXML2.XMLHTTP.3.0',\n 'MSXML2.XMLHTTP',\n 'Microsoft.XMLHTTP',\n ];\n for (let i = 0; i < ACTIVE_X_IDENTS.length; i++) {\n const candidate = ACTIVE_X_IDENTS[i];\n\n try {\n new ActiveXObject(candidate);\n // NOTE(user): cannot assign progid and return candidate in one line\n // because JSCompiler complaings: BUG 658126\n this.ieProgId_ = candidate;\n return candidate;\n } catch (e) {\n // do nothing; try next choice\n }\n }\n\n // couldn't find any matches\n throw new Error(\n 'Could not create ActiveXObject. ActiveX might be disabled,' +\n ' or MSXML might not be installed');\n }\n\n return /** @type {string} */ (this.ieProgId_);\n};\n\n\n// Set the global factory to an instance of the default factory.\ngoog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory());\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Definition of the ChannelRequest class. The request\n * object encapsulates the logic for making a single request, either for the\n * forward channel, back channel, or test channel, to the server. It contains\n * the logic for the two types of transports we use:\n * XMLHTTP and Image request. It provides timeout detection. More transports\n * to be added in future, such as Fetch, WebSocket.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.ChannelRequest');\n\ngoog.require('goog.Timer');\ngoog.require('goog.asserts');\ngoog.require('goog.async.Throttle');\ngoog.require('goog.dispose');\ngoog.require('goog.events.EventHandler');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.ErrorCode');\ngoog.require('goog.net.EventType');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XmlHttp');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.userAgent');\ngoog.requireType('goog.Uri');\ngoog.requireType('goog.events.Event');\ngoog.requireType('goog.labs.net.webChannel.Wire.QueuedMap');\ngoog.requireType('goog.net.XhrIo');\n\n\n\n/**\n * A new ChannelRequest is created for each request to the server.\n *\n * @param {goog.labs.net.webChannel.Channel} channel\n * The channel that owns this request.\n * @param {goog.labs.net.webChannel.WebChannelDebug} channelDebug A\n * WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @constructor\n * @struct\n * @final\n */\ngoog.labs.net.webChannel.ChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n /**\n * The channel object that owns the request.\n * @private {goog.labs.net.webChannel.Channel}\n */\n this.channel_ = channel;\n\n /**\n * The channel debug to use for logging\n * @private {goog.labs.net.webChannel.WebChannelDebug}\n */\n this.channelDebug_ = channelDebug;\n\n /**\n * The Session ID for the channel.\n * @private {string|undefined}\n */\n this.sid_ = opt_sessionId;\n\n /**\n * The RID (request ID) for the request.\n * @private {string|number|undefined}\n */\n this.rid_ = opt_requestId;\n\n /**\n * The attempt number of the current request.\n * @private {number}\n */\n this.retryId_ = opt_retryId || 1;\n\n /**\n * An object to keep track of the channel request event listeners.\n * @private {!goog.events.EventHandler<\n * !goog.labs.net.webChannel.ChannelRequest>}\n */\n this.eventHandler_ = new goog.events.EventHandler(this);\n\n /**\n * The timeout in ms before failing the request.\n * @private {number}\n */\n this.timeout_ = goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_;\n\n /**\n * A timer for polling responseText in browsers that don't fire\n * onreadystatechange during incremental loading of responseText.\n * @private {goog.Timer}\n */\n this.pollingTimer_ =\n new goog.Timer(goog.labs.net.webChannel.environment.getPollingInterval());\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n\n /**\n * Whether the request was successful. This is only set to true after the\n * request successfully completes.\n * @private {boolean}\n */\n this.successful_ = false;\n\n\n /**\n * The TimerID of the timer used to detect if the request has timed-out.\n * @type {?number}\n * @private\n */\n this.watchDogTimerId_ = null;\n\n /**\n * The time in the future when the request will timeout.\n * @private {?number}\n */\n this.watchDogTimeoutTime_ = null;\n\n /**\n * The time the request started.\n * @private {?number}\n */\n this.requestStartTime_ = null;\n\n /**\n * The type of request (XMLHTTP, IMG)\n * @private {?number}\n */\n this.type_ = null;\n\n /**\n * The base Uri for the request. The includes all the parameters except the\n * one that indicates the retry number.\n * @private {?goog.Uri}\n */\n this.baseUri_ = null;\n\n /**\n * The request Uri that was actually used for the most recent request attempt.\n * @private {?goog.Uri}\n */\n this.requestUri_ = null;\n\n /**\n * The post data, if the request is a post.\n * @private {?string}\n */\n this.postData_ = null;\n\n /**\n * An array of pending messages that we have either received a non-successful\n * response for, or no response at all, and which therefore may or may not\n * have been received by the server.\n * @private {!Array<goog.labs.net.webChannel.Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n\n /**\n * The XhrLte request if the request is using XMLHTTP\n * @private {?goog.net.XhrIo}\n */\n this.xmlHttp_ = null;\n\n /**\n * The position of where the next unprocessed chunk starts in the response\n * text.\n * @private {number}\n */\n this.xmlHttpChunkStart_ = 0;\n\n /**\n * The verb (Get or Post) for the request.\n * @private {?string}\n */\n this.verb_ = null;\n\n /**\n * The last error if the request failed.\n * @private {?goog.labs.net.webChannel.ChannelRequest.Error}\n */\n this.lastError_ = null;\n\n /**\n * The last status code received.\n * @private {number}\n */\n this.lastStatusCode_ = -1;\n\n /**\n * Whether the request has been cancelled due to a call to cancel.\n * @private {boolean}\n */\n this.cancelled_ = false;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n * If set to zero no throttle is used.\n *\n * See WebChannelBase.prototype.readyStateChangeThrottleMs_\n *\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * The throttle for readystatechange events for the current request, or null\n * if there is none.\n * @private {?goog.async.Throttle}\n */\n this.readyStateChangeThrottle_ = null;\n\n /**\n * Whether to the result is expected to be encoded for chunking and thus\n * requires decoding.\n * @private {boolean}\n */\n this.decodeChunks_ = false;\n\n /**\n * Whether to decode x-http-initial-response.\n * @private {boolean}\n */\n this.decodeInitialResponse_ = false;\n\n /**\n * Whether x-http-initial-response has been decoded (dispatched).\n * @private {boolean}\n */\n this.initialResponseDecoded_ = false;\n\n /**\n * Whether the first byte of response body has arrived, for a successful\n * response.\n * @private {boolean}\n */\n this.firstByteReceived_ = false;\n\n /**\n * The current state of fetch responses if webchannel is using WHATWG\n * fetch/streams.\n * @private {!goog.labs.net.webChannel.FetchResponseState}\n */\n this.fetchResponseState_ = new goog.labs.net.webChannel.FetchResponseState();\n};\n\n/**\n * A collection of fetch/stream properties.\n * @struct\n * @constructor\n */\ngoog.labs.net.webChannel.FetchResponseState = function() {\n 'use strict';\n /**\n * The TextDecoder for decoding Uint8Array responses from fetch request.\n * @type {?goog.global.TextDecoder}\n */\n this.textDecoder = null;\n\n /**\n * The unconsumed response text from the fetch requests.\n * @type {string}\n */\n this.responseBuffer = '';\n\n /**\n * Whether or not the response body has arrived.\n * @type {boolean}\n */\n this.responseArrivedForFetch = false;\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst Channel = goog.labs.net.webChannel.Channel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst FetchResponseState = goog.labs.net.webChannel.FetchResponseState;\nconst requestStats = goog.labs.net.webChannel.requestStats;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst environment = goog.labs.net.webChannel.environment;\n\n/**\n * Default timeout in MS for a request. The server must return data within this\n * time limit for the request to not timeout.\n * @private {number}\n */\nChannelRequest.TIMEOUT_MS_ = 45 * 1000;\n\n\n/**\n * Enum for channel requests type\n * @enum {number}\n * @private\n */\nChannelRequest.Type_ = {\n /**\n * XMLHTTP requests.\n */\n XML_HTTP: 1,\n\n /**\n * IMG requests.\n */\n CLOSE_REQUEST: 2\n};\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nChannelRequest.Error = {\n /**\n * Errors due to a non-200 status code.\n */\n STATUS: 0,\n\n /**\n * Errors due to no data being returned.\n */\n NO_DATA: 1,\n\n /**\n * Errors due to a timeout.\n */\n TIMEOUT: 2,\n\n /**\n * Errors due to the server returning an unknown.\n */\n UNKNOWN_SESSION_ID: 3,\n\n /**\n * Errors due to bad data being received.\n */\n BAD_DATA: 4,\n\n /**\n * Errors due to the handler throwing an exception.\n */\n HANDLER_EXCEPTION: 5,\n\n /**\n * The browser declared itself offline during the request.\n */\n BROWSER_OFFLINE: 6\n};\n\n\n/**\n * Returns a useful error string for debugging based on the specified error\n * code.\n * @param {?ChannelRequest.Error} errorCode The error code.\n * @param {number} statusCode The HTTP status code.\n * @return {string} The error string for the given code combination.\n */\nChannelRequest.errorStringFromCode = function(errorCode, statusCode) {\n 'use strict';\n switch (errorCode) {\n case ChannelRequest.Error.STATUS:\n return 'Non-200 return code (' + statusCode + ')';\n case ChannelRequest.Error.NO_DATA:\n return 'XMLHTTP failure (no data)';\n case ChannelRequest.Error.TIMEOUT:\n return 'HttpConnection timeout';\n default:\n return 'Unknown error';\n }\n};\n\n\n/**\n * Sentinel value used to indicate an invalid chunk in a multi-chunk response.\n * @private {!Object}\n */\nChannelRequest.INVALID_CHUNK_ = {};\n\n\n/**\n * Sentinel value used to indicate an incomplete chunk in a multi-chunk\n * response.\n * @private {!Object}\n */\nChannelRequest.INCOMPLETE_CHUNK_ = {};\n\n\n/**\n * Returns whether XHR streaming is supported on this browser.\n *\n * @return {boolean} Whether XHR streaming is supported.\n * @see http://code.google.com/p/closure-library/issues/detail?id=346\n */\nChannelRequest.supportsXhrStreaming = function() {\n 'use strict';\n return !goog.userAgent.IE || goog.userAgent.isDocumentModeOrHigher(10);\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers.\n */\nChannelRequest.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Overrides the default HTTP method.\n *\n * @param {string} verb The HTTP method\n */\nChannelRequest.prototype.setVerb = function(verb) {\n 'use strict';\n this.verb_ = verb;\n};\n\n\n/**\n * Sets the timeout for a request\n *\n * @param {number} timeout The timeout in MS for when we fail the request.\n */\nChannelRequest.prototype.setTimeout = function(timeout) {\n 'use strict';\n this.timeout_ = timeout;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nChannelRequest.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets the pending messages that this request is handling.\n *\n * @param {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} pendingMessages\n * The pending messages for this request.\n */\nChannelRequest.prototype.setPendingMessages = function(pendingMessages) {\n 'use strict';\n this.pendingMessages_ = pendingMessages;\n};\n\n\n/**\n * Gets the pending messages that this request is handling, in case of a retry.\n *\n * @return {!Array<goog.labs.net.webChannel.Wire.QueuedMap>} The pending\n * messages for this request.\n */\nChannelRequest.prototype.getPendingMessages = function() {\n 'use strict';\n return this.pendingMessages_;\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP POST to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {?string} postData The data for the post body.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n */\nChannelRequest.prototype.xmlHttpPost = function(uri, postData, decodeChunks) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = postData;\n this.decodeChunks_ = decodeChunks;\n this.sendXmlHttp_(null /* hostPrefix */);\n};\n\n\n/**\n * Uses XMLHTTP to send an HTTP GET to the server.\n *\n * @param {goog.Uri} uri The uri of the request.\n * @param {boolean} decodeChunks Whether to the result is expected to be\n * encoded for chunking and thus requires decoding.\n * @param {?string} hostPrefix The host prefix, if we might be using a\n * secondary domain. Note that it should also be in the URL, adding this\n * won't cause it to be added to the URL.\n */\nChannelRequest.prototype.xmlHttpGet = function(uri, decodeChunks, hostPrefix) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.XML_HTTP;\n this.baseUri_ = uri.clone().makeUnique();\n this.postData_ = null;\n this.decodeChunks_ = decodeChunks;\n\n this.sendXmlHttp_(hostPrefix);\n};\n\n\n/**\n * Sends a request via XMLHTTP according to the current state of the request\n * object.\n *\n * @param {?string} hostPrefix The host prefix, if we might be using a secondary\n * domain.\n * @private\n */\nChannelRequest.prototype.sendXmlHttp_ = function(hostPrefix) {\n 'use strict';\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n\n // clone the base URI to create the request URI. The request uri has the\n // attempt number as a parameter which helps in debugging.\n this.requestUri_ = this.baseUri_.clone();\n this.requestUri_.setParameterValues('t', this.retryId_);\n\n // send the request either as a POST or GET\n this.xmlHttpChunkStart_ = 0;\n const useSecondaryDomains = this.channel_.shouldUseSecondaryDomains();\n this.fetchResponseState_ = new FetchResponseState();\n // If the request is a GET request, start a backchannel to transfer streaming\n // data. Note that WebChannel GET request can also be used for closing the\n // channel as in method ChannelRequest#sendCloseRequest.\n // The second parameter of Channel#createXhrIo is JS only.\n this.xmlHttp_ = this.channel_.createXhrIo(\n useSecondaryDomains ? hostPrefix : null, !this.postData_);\n\n if (this.readyStateChangeThrottleMs_ > 0) {\n this.readyStateChangeThrottle_ = new goog.async.Throttle(\n goog.bind(this.xmlHttpHandler_, this, this.xmlHttp_),\n this.readyStateChangeThrottleMs_);\n }\n\n this.eventHandler_.listen(\n this.xmlHttp_, goog.net.EventType.READY_STATE_CHANGE,\n this.readyStateChangeHandler_);\n\n const headers =\n this.extraHeaders_ ? goog.object.clone(this.extraHeaders_) : {};\n if (this.postData_) {\n if (!this.verb_) {\n this.verb_ = 'POST';\n }\n headers['Content-Type'] = 'application/x-www-form-urlencoded';\n this.xmlHttp_.send(this.requestUri_, this.verb_, this.postData_, headers);\n } else {\n this.verb_ = 'GET';\n this.xmlHttp_.send(this.requestUri_, this.verb_, null, headers);\n }\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_MADE);\n this.channelDebug_.xmlHttpChannelRequest(\n this.verb_, this.requestUri_, this.rid_, this.retryId_, this.postData_);\n};\n\n\n/**\n * Handles a readystatechange event.\n * @param {goog.events.Event} evt The event.\n * @private\n */\nChannelRequest.prototype.readyStateChangeHandler_ = function(evt) {\n 'use strict';\n const xhr = /** @type {goog.net.XhrIo} */ (evt.target);\n const throttle = this.readyStateChangeThrottle_;\n if (throttle &&\n xhr.getReadyState() == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n // Only throttle in the partial data case.\n this.channelDebug_.debug('Throttling readystatechange.');\n throttle.fire();\n } else {\n // If we haven't throttled, just handle response directly.\n this.xmlHttpHandler_(xhr);\n }\n};\n\n\n/**\n * XmlHttp handler\n * @param {goog.net.XhrIo} xmlhttp The XhrIo object for the current request.\n * @private\n */\nChannelRequest.prototype.xmlHttpHandler_ = function(xmlhttp) {\n 'use strict';\n requestStats.onStartExecution();\n\n try {\n if (xmlhttp == this.xmlHttp_) {\n this.onXmlHttpReadyStateChanged_();\n } else {\n this.channelDebug_.warning(\n 'Called back with an ' +\n 'unexpected xmlhttp');\n }\n } catch (ex) {\n this.channelDebug_.debug('Failed call to OnXmlHttpReadyStateChanged_');\n if (this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.dumpException(ex, function() {\n 'use strict';\n return 'ResponseText: ' + channelRequest.xmlHttp_.getResponseText();\n });\n } else {\n this.channelDebug_.dumpException(ex, 'No response text');\n }\n } finally {\n requestStats.onEndExecution();\n }\n};\n\n\n/**\n * Called by the readystate handler for XMLHTTP requests.\n *\n * @private\n */\nChannelRequest.prototype.onXmlHttpReadyStateChanged_ = function() {\n 'use strict';\n const readyState = this.xmlHttp_.getReadyState();\n const errorCode = this.xmlHttp_.getLastErrorCode();\n const statusCode = this.xmlHttp_.getStatus();\n\n // we get partial results in browsers that support ready state interactive.\n // We also make sure that getResponseText is not null in interactive mode\n // before we continue.\n if (readyState < goog.net.XmlHttp.ReadyState.INTERACTIVE ||\n (readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE &&\n !environment.isPollingRequired() && // otherwise, go on to startPolling\n !this.hasResponseBody_())) {\n return; // not yet ready\n }\n\n // Dispatch any appropriate network events.\n if (!this.cancelled_ && readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n errorCode != goog.net.ErrorCode.ABORT) {\n // Pretty conservative, these are the only known scenarios which we'd\n // consider indicative of a truly non-functional network connection.\n if (errorCode == goog.net.ErrorCode.TIMEOUT || statusCode <= 0) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n } else {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_SUCCEEDED);\n }\n }\n\n // got some data so cancel the watchdog timer\n this.cancelWatchDogTimer_();\n\n const status = this.xmlHttp_.getStatus();\n this.lastStatusCode_ = status;\n const responseText = this.decodeXmlHttpResponse_();\n\n if (!this.hasResponseBody_()) {\n const channelRequest = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'No response text for uri ' + channelRequest.requestUri_ +\n ' status ' + status;\n });\n }\n this.successful_ = (status == 200);\n\n this.channelDebug_.xmlHttpChannelResponseMetaData(\n /** @type {string} */ (this.verb_), this.requestUri_, this.rid_,\n this.retryId_, readyState, status);\n\n if (!this.successful_) {\n if (status == 400 && responseText.indexOf('Unknown SID') > 0) {\n // the server error string will include 'Unknown SID' which indicates the\n // server doesn't know about the session (maybe it got restarted, maybe\n // the user got moved to another server, etc.,). Handlers can special\n // case this error\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID;\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning('XMLHTTP Unknown SID (' + this.rid_ + ')');\n } else {\n this.lastError_ = ChannelRequest.Error.STATUS;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_STATUS);\n this.channelDebug_.warning(\n 'XMLHTTP Bad status ' + status + ' (' + this.rid_ + ')');\n }\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n\n if (this.shouldCheckInitialResponse_()) {\n const initialResponse = this.getInitialResponse_();\n if (initialResponse) {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, initialResponse,\n 'Initial handshake response via ' +\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n this.initialResponseDecoded_ = true;\n this.safeOnRequestData_(initialResponse);\n } else {\n this.successful_ = false;\n this.lastError_ = ChannelRequest.Error.UNKNOWN_SESSION_ID; // fail-fast\n requestStats.notifyStatEvent(\n requestStats.Stat.REQUEST_UNKNOWN_SESSION_ID);\n this.channelDebug_.warning(\n 'XMLHTTP Missing X_HTTP_INITIAL_RESPONSE' +\n ' (' + this.rid_ + ')');\n this.cleanup_();\n this.dispatchFailure_();\n return;\n }\n }\n\n if (this.decodeChunks_) {\n this.decodeNextChunks_(readyState, responseText);\n if (environment.isPollingRequired() && this.successful_ &&\n readyState == goog.net.XmlHttp.ReadyState.INTERACTIVE) {\n this.startPolling_();\n }\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, null);\n this.safeOnRequestData_(responseText);\n }\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.cleanup_();\n }\n\n if (!this.successful_) {\n return;\n }\n\n if (!this.cancelled_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.channel_.onRequestComplete(this);\n } else {\n // The default is false, the result from this callback shouldn't carry\n // over to the next callback, otherwise the request looks successful if\n // the watchdog timer gets called\n this.successful_ = false;\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Whether we need check the initial-response header that is sent during the\n * fast handshake.\n *\n * @return {boolean} true if the initial-response header is yet to be processed.\n * @private\n */\nChannelRequest.prototype.shouldCheckInitialResponse_ = function() {\n 'use strict';\n return this.decodeInitialResponse_ && !this.initialResponseDecoded_;\n};\n\n\n/**\n * Queries the initial response header that is sent during the handshake.\n *\n * @return {?string} The non-empty header value or null.\n * @private\n */\nChannelRequest.prototype.getInitialResponse_ = function() {\n 'use strict';\n if (this.xmlHttp_) {\n const value = this.xmlHttp_.getStreamingResponseHeader(\n WebChannel.X_HTTP_INITIAL_RESPONSE);\n if (value && !goog.string.isEmptyOrWhitespace(value)) {\n return value;\n }\n }\n\n return null;\n};\n\n\n/**\n * Check if the initial response header has been handled.\n *\n * @return {boolean} true if X_HTTP_INITIAL_RESPONSE has been handled.\n */\nChannelRequest.prototype.isInitialResponseDecoded = function() {\n 'use strict';\n return this.initialResponseDecoded_;\n};\n\n\n/**\n * Decodes X_HTTP_INITIAL_RESPONSE if present.\n */\nChannelRequest.prototype.setDecodeInitialResponse = function() {\n 'use strict';\n this.decodeInitialResponse_ = true;\n};\n\n\n\n/**\n * Decodes the responses from XhrIo object.\n * @returns {string} responseText\n * @private\n */\nChannelRequest.prototype.decodeXmlHttpResponse_ = function() {\n 'use strict';\n if (!this.useFetchStreamsForResponse_()) {\n return this.xmlHttp_.getResponseText();\n }\n const responseChunks =\n /** @type {!Array<!Uint8Array>} */ (this.xmlHttp_.getResponse());\n let responseText = '';\n const responseLength = responseChunks.length;\n const requestCompleted =\n this.xmlHttp_.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;\n if (!this.fetchResponseState_.textDecoder) {\n if (typeof TextDecoder === 'undefined') {\n this.channelDebug_.severe(\n 'TextDecoder is not supported by this browser.');\n this.cleanup_();\n this.dispatchFailure_();\n return '';\n }\n this.fetchResponseState_.textDecoder = new goog.global.TextDecoder();\n }\n for (let i = 0; i < responseLength; i++) {\n this.fetchResponseState_.responseArrivedForFetch = true;\n const isLastChunk = requestCompleted && i == responseLength - 1;\n responseText += this.fetchResponseState_.textDecoder.decode(\n responseChunks[i], {stream: isLastChunk});\n }\n responseChunks.splice(0, responseLength);\n this.fetchResponseState_.responseBuffer += responseText;\n this.xmlHttpChunkStart_ = 0;\n return this.fetchResponseState_.responseBuffer;\n};\n\n\n/**\n * Whether or not the response has response body.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.hasResponseBody_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n if (this.fetchResponseState_.responseArrivedForFetch) {\n return true;\n }\n return !(!this.xmlHttp_.getResponseText() && !this.xmlHttp_.getResponse());\n};\n\n/**\n * Whether or not the response body is streamed.\n * @private\n * @returns {boolean}\n */\nChannelRequest.prototype.useFetchStreamsForResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return false;\n }\n return (\n this.verb_ == 'GET' && this.type_ != ChannelRequest.Type_.CLOSE_REQUEST &&\n this.channel_.usesFetchStreams());\n};\n\n\n/**\n * Resets the response buffer if the saved chunk has been processed.\n * @private\n * @param {string|!Object|undefined} chunkText\n */\nChannelRequest.prototype.maybeResetBuffer_ = function(chunkText) {\n 'use strict';\n if (this.useFetchStreamsForResponse_() &&\n chunkText != ChannelRequest.INCOMPLETE_CHUNK_ &&\n chunkText != ChannelRequest.INVALID_CHUNK_) {\n this.fetchResponseState_.responseBuffer = '';\n this.xmlHttpChunkStart_ = 0;\n }\n};\n\n\n/**\n * Decodes the next set of available chunks in the response.\n * @param {number} readyState The value of readyState.\n * @param {string} responseText The value of responseText.\n * @private\n */\nChannelRequest.prototype.decodeNextChunks_ = function(\n readyState, responseText) {\n 'use strict';\n let decodeNextChunksSuccessful = true;\n\n let chunkText;\n while (!this.cancelled_ && this.xmlHttpChunkStart_ < responseText.length) {\n chunkText = this.getNextChunk_(responseText);\n if (chunkText == ChannelRequest.INCOMPLETE_CHUNK_) {\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {\n // should have consumed entire response when the request is done\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_INCOMPLETE_DATA);\n decodeNextChunksSuccessful = false;\n }\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, null, '[Incomplete Response]');\n break;\n } else if (chunkText == ChannelRequest.INVALID_CHUNK_) {\n this.lastError_ = ChannelRequest.Error.BAD_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_BAD_DATA);\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunk]');\n decodeNextChunksSuccessful = false;\n break;\n } else {\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, /** @type {string} */ (chunkText), null);\n this.safeOnRequestData_(/** @type {string} */ (chunkText));\n }\n }\n\n this.maybeResetBuffer_(chunkText);\n\n if (readyState == goog.net.XmlHttp.ReadyState.COMPLETE &&\n responseText.length == 0 &&\n !this.fetchResponseState_.responseArrivedForFetch) {\n // also an error if we didn't get any response\n this.lastError_ = ChannelRequest.Error.NO_DATA;\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_NO_DATA);\n decodeNextChunksSuccessful = false;\n }\n\n this.successful_ = this.successful_ && decodeNextChunksSuccessful;\n\n if (!decodeNextChunksSuccessful) {\n // malformed response - we make this trigger retry logic\n this.channelDebug_.xmlHttpChannelResponseText(\n this.rid_, responseText, '[Invalid Chunked Response]');\n this.cleanup_();\n this.dispatchFailure_();\n } else {\n if (responseText.length > 0 && !this.firstByteReceived_) {\n this.firstByteReceived_ = true;\n this.channel_.onFirstByteReceived(this, responseText);\n }\n }\n};\n\n\n/**\n * Polls the response for new data.\n * @private\n */\nChannelRequest.prototype.pollResponse_ = function() {\n 'use strict';\n if (!this.xmlHttp_) {\n return; // already closed\n }\n const readyState = this.xmlHttp_.getReadyState();\n const responseText = this.xmlHttp_.getResponseText();\n if (this.xmlHttpChunkStart_ < responseText.length) {\n this.cancelWatchDogTimer_();\n this.decodeNextChunks_(readyState, responseText);\n if (this.successful_ &&\n readyState != goog.net.XmlHttp.ReadyState.COMPLETE) {\n this.ensureWatchDogTimer_();\n }\n }\n};\n\n\n/**\n * Starts a polling interval for changes to responseText of the\n * XMLHttpRequest, for browsers that don't fire onreadystatechange\n * as data comes in incrementally. This timer is disabled in\n * cleanup_().\n * @private\n */\nChannelRequest.prototype.startPolling_ = function() {\n 'use strict';\n this.eventHandler_.listen(\n this.pollingTimer_, goog.Timer.TICK, this.pollResponse_);\n this.pollingTimer_.start();\n};\n\n\n/**\n * Returns the next chunk of a chunk-encoded response. This is not standard\n * HTTP chunked encoding because browsers don't expose the chunk boundaries to\n * the application through XMLHTTP. So we have an additional chunk encoding at\n * the application level that lets us tell where the beginning and end of\n * individual responses are so that we can only try to eval a complete JS array.\n *\n * The encoding is the size of the chunk encoded as a decimal string followed\n * by a newline followed by the data.\n *\n * @param {string} responseText The response text from the XMLHTTP response.\n * @return {string|!Object} The next chunk string or a sentinel object\n * indicating a special condition.\n * @private\n */\nChannelRequest.prototype.getNextChunk_ = function(responseText) {\n 'use strict';\n const sizeStartIndex = this.xmlHttpChunkStart_;\n const sizeEndIndex = responseText.indexOf('\\n', sizeStartIndex);\n if (sizeEndIndex == -1) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const sizeAsString = responseText.substring(sizeStartIndex, sizeEndIndex);\n const size = Number(sizeAsString);\n if (isNaN(size)) {\n return ChannelRequest.INVALID_CHUNK_;\n }\n\n const chunkStartIndex = sizeEndIndex + 1;\n if (chunkStartIndex + size > responseText.length) {\n return ChannelRequest.INCOMPLETE_CHUNK_;\n }\n\n const chunkText = responseText.substr(chunkStartIndex, size);\n this.xmlHttpChunkStart_ = chunkStartIndex + size;\n return chunkText;\n};\n\n\n/**\n * Uses an IMG tag or navigator.sendBeacon to send an HTTP get to the server.\n *\n * This is only currently used to terminate the connection, as an IMG tag is\n * the most reliable way to send something to the server while the page\n * is getting torn down.\n *\n * Navigator.sendBeacon is available on Chrome and Firefox as a formal\n * solution to ensure delivery without blocking window close. See\n * https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon\n *\n * For Chrome Apps, sendBeacon is always necessary due to Content Security\n * Policy (CSP) violation of using an IMG tag.\n *\n * For react-native, we use xhr to send the actual close request, and assume\n * there is no page-close issue with react-native.\n *\n * @param {goog.Uri} uri The uri to send a request to.\n */\nChannelRequest.prototype.sendCloseRequest = function(uri) {\n 'use strict';\n this.type_ = ChannelRequest.Type_.CLOSE_REQUEST;\n this.baseUri_ = uri.clone().makeUnique();\n\n let requestSent = false;\n\n if (goog.global.navigator && goog.global.navigator.sendBeacon) {\n // empty string body to avoid 413 error on chrome < 41\n requestSent =\n goog.global.navigator.sendBeacon(this.baseUri_.toString(), '');\n }\n\n if (!requestSent && goog.global.Image) {\n const eltImg = new Image();\n eltImg.src = this.baseUri_;\n requestSent = true;\n }\n\n if (!requestSent) {\n // no handler is set to match the sendBeacon/Image behavior\n this.xmlHttp_ = this.channel_.createXhrIo(null);\n this.xmlHttp_.send(this.baseUri_);\n }\n\n this.requestStartTime_ = Date.now();\n this.ensureWatchDogTimer_();\n};\n\n\n/**\n * Cancels the request no matter what the underlying transport is.\n */\nChannelRequest.prototype.cancel = function() {\n 'use strict';\n this.cancelled_ = true;\n this.cleanup_();\n};\n\n\n/**\n * Resets the timeout.\n *\n * @param {number=} opt_timeout The new timeout\n */\nChannelRequest.prototype.resetTimeout = function(opt_timeout) {\n 'use strict';\n if (opt_timeout) {\n this.setTimeout(opt_timeout);\n }\n // restart only if a timer is currently set\n if (this.watchDogTimerId_) {\n this.cancelWatchDogTimer_();\n this.ensureWatchDogTimer_();\n }\n};\n\n\n/**\n * Ensures that there is watchdog timeout which is used to ensure that\n * the connection completes in time.\n *\n * @private\n */\nChannelRequest.prototype.ensureWatchDogTimer_ = function() {\n 'use strict';\n this.watchDogTimeoutTime_ = Date.now() + this.timeout_;\n this.startWatchDogTimer_(this.timeout_);\n};\n\n\n/**\n * Starts the watchdog timer which is used to ensure that the connection\n * completes in time.\n * @param {number} time The number of milliseconds to wait.\n * @private\n */\nChannelRequest.prototype.startWatchDogTimer_ = function(time) {\n 'use strict';\n if (this.watchDogTimerId_ != null) {\n // assertion\n throw new Error('WatchDog timer not null');\n }\n this.watchDogTimerId_ =\n requestStats.setTimeout(goog.bind(this.onWatchDogTimeout_, this), time);\n};\n\n\n/**\n * Cancels the watchdog timer if it has been started.\n *\n * @private\n */\nChannelRequest.prototype.cancelWatchDogTimer_ = function() {\n 'use strict';\n if (this.watchDogTimerId_) {\n goog.global.clearTimeout(this.watchDogTimerId_);\n this.watchDogTimerId_ = null;\n }\n};\n\n\n/**\n * Called when the watchdog timer is triggered. It also handles a case where it\n * is called too early which we suspect may be happening sometimes\n * (not sure why)\n *\n * @private\n */\nChannelRequest.prototype.onWatchDogTimeout_ = function() {\n 'use strict';\n this.watchDogTimerId_ = null;\n const now = Date.now();\n goog.asserts.assert(\n this.watchDogTimeoutTime_, 'WatchDog timeout time missing?');\n if (now - this.watchDogTimeoutTime_ >= 0) {\n this.handleTimeout_();\n } else {\n // got called too early for some reason\n this.channelDebug_.warning('WatchDog timer called too early');\n this.startWatchDogTimer_(this.watchDogTimeoutTime_ - now);\n }\n};\n\n\n/**\n * Called when the request has actually timed out. Will cleanup and notify the\n * channel of the failure.\n *\n * @private\n */\nChannelRequest.prototype.handleTimeout_ = function() {\n 'use strict';\n if (this.successful_) {\n // Should never happen.\n this.channelDebug_.severe(\n 'Received watchdog timeout even though request loaded successfully');\n }\n\n this.channelDebug_.timeoutResponse(this.requestUri_);\n\n // IMG or SendBeacon requests never notice if they were successful,\n // and always 'time out'. This fact says nothing about reachability.\n if (this.type_ != ChannelRequest.Type_.CLOSE_REQUEST) {\n requestStats.notifyServerReachabilityEvent(\n requestStats.ServerReachability.REQUEST_FAILED);\n requestStats.notifyStatEvent(requestStats.Stat.REQUEST_TIMEOUT);\n }\n\n this.cleanup_();\n\n // Set error and dispatch failure.\n // This is called for CLOSE_REQUEST too to ensure channel_.onRequestComplete.\n this.lastError_ = ChannelRequest.Error.TIMEOUT;\n this.dispatchFailure_();\n};\n\n\n/**\n * Notifies the channel that this request failed.\n * @private\n */\nChannelRequest.prototype.dispatchFailure_ = function() {\n 'use strict';\n if (this.channel_.isClosed() || this.cancelled_) {\n return;\n }\n\n this.channel_.onRequestComplete(this);\n};\n\n\n/**\n * Cleans up the objects used to make the request. This function is\n * idempotent.\n *\n * @private\n */\nChannelRequest.prototype.cleanup_ = function() {\n 'use strict';\n this.cancelWatchDogTimer_();\n\n goog.dispose(this.readyStateChangeThrottle_);\n this.readyStateChangeThrottle_ = null;\n\n // Stop the polling timer, if necessary.\n this.pollingTimer_.stop();\n\n // Unhook all event handlers.\n this.eventHandler_.removeAll();\n\n if (this.xmlHttp_) {\n // clear out this.xmlHttp_ before aborting so we handle getting reentered\n // inside abort\n const xmlhttp = this.xmlHttp_;\n this.xmlHttp_ = null;\n xmlhttp.abort();\n xmlhttp.dispose();\n }\n};\n\n\n/**\n * Indicates whether the request was successful. Only valid after the handler\n * is called to indicate completion of the request.\n *\n * @return {boolean} True if the request succeeded.\n */\nChannelRequest.prototype.getSuccess = function() {\n 'use strict';\n return this.successful_;\n};\n\n\n/**\n * If the request was not successful, returns the reason.\n *\n * @return {?ChannelRequest.Error} The last error.\n */\nChannelRequest.prototype.getLastError = function() {\n 'use strict';\n return this.lastError_;\n};\n\n\n/**\n * Returns the status code of the last request.\n * @return {number} The status code of the last request.\n */\nChannelRequest.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.lastStatusCode_;\n};\n\n\n/**\n * Returns the session id for this channel.\n *\n * @return {string|undefined} The session ID.\n */\nChannelRequest.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Returns the request id for this request. Each request has a unique request\n * id and the request IDs are a sequential increasing count.\n *\n * @return {string|number|undefined} The request ID.\n */\nChannelRequest.prototype.getRequestId = function() {\n 'use strict';\n return this.rid_;\n};\n\n\n/**\n * Returns the data for a post, if this request is a post.\n *\n * @return {?string} The POST data provided by the request initiator.\n */\nChannelRequest.prototype.getPostData = function() {\n 'use strict';\n return this.postData_;\n};\n\n\n/**\n * Returns the XhrIo request object.\n *\n * @return {?goog.net.XhrIo} Any XhrIo request created for this object.\n */\nChannelRequest.prototype.getXhr = function() {\n 'use strict';\n return this.xmlHttp_;\n};\n\n\n/**\n * Returns the time that the request started, if it has started.\n *\n * @return {?number} The time the request started, as returned by Date.now().\n */\nChannelRequest.prototype.getRequestStartTime = function() {\n 'use strict';\n return this.requestStartTime_;\n};\n\n\n/**\n * Helper to call the callback's onRequestData, which catches any\n * exception.\n * @param {string} data The request data.\n * @private\n */\nChannelRequest.prototype.safeOnRequestData_ = function(data) {\n 'use strict';\n try {\n this.channel_.onRequestData(this, data);\n const stats = requestStats.ServerReachability;\n requestStats.notifyServerReachabilityEvent(stats.BACK_CHANNEL_ACTIVITY);\n } catch (e) {\n // Dump debug info, but keep going without closing the channel.\n this.channelDebug_.dumpException(e, 'Error in httprequest callback');\n }\n};\n\n\n/**\n * Convenience factory method.\n *\n * @param {Channel} channel The channel object that owns this request.\n * @param {WebChannelDebug} channelDebug A WebChannelDebug to use for logging.\n * @param {string=} opt_sessionId The session id for the channel.\n * @param {string|number=} opt_requestId The request id for this request.\n * @param {number=} opt_retryId The retry id for this request.\n * @return {!ChannelRequest} The created channel request.\n */\nChannelRequest.createChannelRequest = function(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId) {\n 'use strict';\n return new ChannelRequest(\n channel, channelDebug, opt_sessionId, opt_requestId, opt_retryId);\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A single module to define user-agent specific environment\n * details.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.environment');\n\ngoog.module.declareLegacyNamespace();\n\nvar userAgent = goog.require('goog.userAgent');\n\n\n/**\n * The default polling interval in millis for Edge.\n *\n * Currently on edge, new-chunk events may be not be fired (at all) if a new\n * chunk arrives within 50ms following the previous chunk. This may be fixed\n * in future, which requires changes to the whatwg spec too.\n *\n * @private @const {number}\n */\nvar EDGE_POLLING_INTERVAL_ = 125;\n\n\n/**\n * History:\n *\n * IE11 is still using Trident, the traditional engine for IE.\n * Edge is using EdgeHTML, a fork of Trident. We are seeing the same issue\n * on IE-11 (reported in 2017), so treat IE the same as Edge for now.\n *\n * We used to do polling for Opera (only) with an 250ms interval, because Opera\n * only fires readyState == INTERACTIVE once. Opera switched to WebKit in 2013,\n * and then to Blink (chrome).\n *\n * TODO(user): check the raw UA string to keep polling for old, mobile operas\n * that may still be affected. For old Opera, double the polling interval\n * to 250ms.\n *\n * @return {boolean} True if polling is required with XHR.\n */\nexports.isPollingRequired = function() {\n return userAgent.EDGE_OR_IE;\n};\n\n\n/**\n * How often to poll (in MS) for changes to responseText in browsers that don't\n * fire onreadystatechange during incremental loading of the response body.\n *\n * @return {number|undefined} The polling interval (MS) for the current U-A;\n * or undefined if polling is not supposed to be enabled.\n */\nexports.getPollingInterval = function() {\n if (userAgent.EDGE_OR_IE) {\n return EDGE_POLLING_INTERVAL_;\n }\n\n return undefined;\n};\n\n/**\n * Origin trial token for google.com\n *\n * https://developers.chrome.com/origintrials/#/trials\n *\n * http://googlechrome.github.io/OriginTrials/check-token.html\n * Origin: https://google.com:443\n * Matches Subdomains? Yes\n * Matches Third-party? Yes\n * Feature: FetchUploadStreaming\n * Up to Chrome 95 (ends with the rollout of next Chrome release), no later\n * than Nov 9, 2021\n *\n * Token for googleapis.com will be registered after google.com's is deployed.\n *\n */\nconst OT_TOKEN_GOOGLE_COM =\n 'A0eNbltY1nd4MP7XTHXnTxWogDL6mWTdgIIKfKOTJoUHNbFFMZQBoiHHjJ9UK9lgYndWFaxOWR7ld8uUjcWmcwIAAAB/eyJvcmlnaW4iOiJodHRwczovL2dvb2dsZS5jb206NDQzIiwiZmVhdHVyZSI6IkZldGNoVXBsb2FkU3RyZWFtaW5nIiwiZXhwaXJ5IjoxNjM2NTAyMzk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ==';\n\n\n/**\n * Creates ReadableStream to upload\n * @return {!ReadableStream} ReadableStream to upload\n */\nfunction createStream() {\n const encoder = new goog.global.TextEncoder();\n return new goog.global.ReadableStream({\n start: controller => {\n for (const obj of ['test\\r\\n', 'test\\r\\n']) {\n controller.enqueue(encoder.encode(obj));\n }\n controller.close();\n }\n });\n}\n\n/**\n * Detect the user agent is chrome and its version is higher than M90.\n * This code is hard-coded from goog.labs.userAgent.browser to avoid file size\n * increasing.\n * @return {boolean} Whether the above is true.\n */\nfunction isChromeM90OrHigher() {\n const userAgentStr = function() {\n const navigator = goog.global.navigator;\n if (navigator) {\n const userAgent = navigator.userAgent;\n if (userAgent) {\n return userAgent;\n }\n }\n return '';\n }();\n\n const matchUserAgent = function(str) {\n return userAgentStr.indexOf(str) != -1;\n };\n\n if (!matchUserAgent('Chrome') || matchUserAgent('Edg')) {\n return false;\n }\n\n const match = /Chrome\\/(\\d+)/.exec(userAgentStr);\n const chromeVersion = parseInt(match[1], 10);\n return chromeVersion >= 90;\n}\n\n/**\n * Detect the URL origin is *.google.com.\n * @param {string} url The target URL.\n * @return {boolean} Whether the above is true.\n */\nfunction isUrlGoogle(url) {\n const match = /\\/\\/([^\\/]+)\\//.exec(url);\n if (!match) {\n return false;\n }\n const origin = match[1];\n return origin.endsWith('google.com');\n}\n\n/**\n * The flag to run the origin trials code only once.\n */\nlet isStartOriginTrialsCalled = false;\n\n/**\n * For Fetch/upload OT, make three requests against the server endpoint.\n * POST requests contain only dummy payload.\n *\n * https://developers.chrome.com/origintrials/#/view_trial/3524066708417413121\n *\n * This function is expected to be called from background during the handshake.\n * Exceptions will be logged by the caller.\n *\n * No stats or logs are collected on the client-side. To be disabled once the\n * OT is expired.\n *\n * @param {string} path The base URL path for the requests\n * @param {function(*)} logError A function to execute when exceptions are\n * caught.\n */\nexports.startOriginTrials = function(path, logError) {\n if (isStartOriginTrialsCalled) {\n return;\n }\n isStartOriginTrialsCalled = true;\n // NE: may need check if path has already contains query params?\n\n // Accept only Chrome M90 or later due to service worker support.\n if (!isChromeM90OrHigher()) {\n return;\n }\n\n // Accept only only google.com and subdoamins.\n if (!isUrlGoogle(path)) {\n return;\n }\n // Since 3P OT is not supported yet, we should check the current page matches\n // the path (absolute one?) to disable this OT for cross-origin calls\n if (!window || !window.document || !isUrlGoogle(window.document.URL)) {\n return;\n }\n\n // Enable origin trial by injecting OT <meta> tag\n const tokenElement =\n /** @type {! HTMLMetaElement} */ (document.createElement('meta'));\n tokenElement.httpEquiv = 'origin-trial';\n tokenElement.content = OT_TOKEN_GOOGLE_COM;\n // appendChild() synchronously enables OT.\n document.head.appendChild(tokenElement);\n\n // Check if fetch upload stream is actually enabled.\n // By the spec, Streaming request doesn't has the Content-Type header:\n // https://fetch.spec.whatwg.org/#concept-bodyinit-extract\n // If Chrome doesn't support Streaming, the body stream is converted to a\n // string \"[object ReadableStream]\" for fallback then it has \"Content-Type:\n // text/plain;charset=UTF-8\".\n const supportsRequestStreams = !new Request('', {\n body: new ReadableStream(),\n method: 'POST',\n }).headers.has('Content-Type');\n if (!supportsRequestStreams) {\n return;\n }\n\n // 1st req: path?ot=1\n // non-streaming upload request\n goog.global.fetch(`${path}?ot=1`, {method: 'POST', body: 'test\\r\\n'})\n .catch(logError);\n\n // 2nd req: path?ot=2\n // h2-only streaming upload request\n goog.global\n .fetch(`${path}?ot=2`, {\n method: 'POST',\n body: createStream(),\n allowHTTP1ForStreamingUpload: false,\n })\n .catch(logError);\n\n // 3rd req: path?ot=3\n // h1-allowed streaming upload request\n goog.global\n .fetch(`${path}?ot=3`, {\n method: 'POST',\n body: createStream(),\n allowHTTP1ForStreamingUpload: true,\n })\n .catch(logError);\n\n // Example calling a Chrome API:\n // goog.global.chrome.loadTimes().wasFetchedViaSpdy\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Base WebChannel implementation.\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBase');\n\ngoog.require('goog.Uri');\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.async.run');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.Channel');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.ConnectionState');\ngoog.require('goog.labs.net.webChannel.ForwardChannelRequestPool');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.labs.net.webChannel.WireV8');\ngoog.require('goog.labs.net.webChannel.environment');\ngoog.require('goog.labs.net.webChannel.netUtils');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.XhrIo');\ngoog.require('goog.net.XmlHttpFactory');\ngoog.require('goog.net.rpc.HttpCors');\ngoog.require('goog.object');\ngoog.require('goog.string');\ngoog.require('goog.structs');\n\ngoog.scope(function() {\n'use strict';\nconst WebChannel = goog.net.WebChannel;\nconst ChannelRequest = goog.labs.net.webChannel.ChannelRequest;\nconst ConnectionState = goog.labs.net.webChannel.ConnectionState;\nconst ForwardChannelRequestPool =\n goog.labs.net.webChannel.ForwardChannelRequestPool;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\nconst Wire = goog.labs.net.webChannel.Wire;\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst environment = goog.labs.net.webChannel.environment;\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst requestStats = goog.labs.net.webChannel.requestStats;\n\nconst httpCors = goog.module.get('goog.net.rpc.HttpCors');\n\n/**\n * @define {boolean} If WebChannel should compile with Origin Trial features.\n */\nconst ALLOW_ORIGIN_TRIAL_FEATURES =\n goog.define('goog.net.webChannel.ALLOW_ORIGIN_TRIAL_FEATURES', true);\n\n/**\n * Gets an internal channel parameter in a type-safe way.\n *\n * @param {string} paramName the key of the parameter to fetch.\n * @param {!T} defaultValue the default value to return\n * @param {!goog.net.WebChannel.Options=} options Configuration for the\n * WebChannel instance.\n * @return {T}\n * @template T\n */\nfunction getInternalChannelParam(paramName, defaultValue, options) {\n if (!options || !options.internalChannelParams) {\n return defaultValue;\n }\n return /** @type {T} */ (options.internalChannelParams[paramName]) ||\n defaultValue;\n}\n\n/**\n * This WebChannel implementation is branched off goog.net.BrowserChannel\n * for now. Ongoing changes to goog.net.BrowserChannel will be back\n * ported to this implementation as needed.\n *\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * WebChannel instance.\n * @param {number=} opt_clientVersion An application-specific version number\n * that is sent to the server when connected.\n * @param {!ConnectionState=} opt_conn Previously determined connection\n * conditions.\n * @constructor\n * @struct\n * @implements {goog.labs.net.webChannel.Channel}\n */\ngoog.labs.net.webChannel.WebChannelBase = function(\n opt_options, opt_clientVersion, opt_conn) {\n 'use strict';\n /**\n * The client library version (capabilities).\n * @private {number}\n */\n this.clientVersion_ = opt_clientVersion || 0;\n\n /**\n * The server library version (capabilities).\n * @private {number}\n */\n this.serverVersion_ = 0;\n\n\n /**\n * An array of queued maps that need to be sent to the server.\n * @private {!Array<Wire.QueuedMap>}\n */\n this.outgoingMaps_ = [];\n\n /**\n * The channel debug used for logging\n * @private {!WebChannelDebug}\n */\n this.channelDebug_ = new WebChannelDebug();\n\n /**\n * Connectivity state.\n * @private {!ConnectionState}\n */\n this.connState_ = opt_conn || new ConnectionState();\n\n /**\n * Extra HTTP headers to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraHeaders_ = null;\n\n /**\n * Extra HTTP headers to add to the init request(s) sent to the server.\n * @private {?Object}\n */\n this.initHeaders_ = null;\n\n /**\n * @private {?string} The URL param name to overwrite custom HTTP headers\n * to bypass CORS preflight.\n */\n this.httpHeadersOverwriteParam_ = null;\n\n /**\n * Extra parameters to add to all the requests sent to the server.\n * @private {?Object}\n */\n this.extraParams_ = null;\n\n /**\n * Parameter name for the http session id.\n * @private {?string}\n */\n this.httpSessionIdParam_ = null;\n\n /**\n * The http session id, to be sent with httpSessionIdParam_ with each\n * request after the initial handshake.\n * @private {?string}\n */\n this.httpSessionId_ = null;\n\n /**\n * The ChannelRequest object for the backchannel.\n * @private {?ChannelRequest}\n */\n this.backChannelRequest_ = null;\n\n /**\n * The relative path (in the context of the page hosting the browser channel)\n * for making requests to the server.\n * @private {?string}\n */\n this.path_ = null;\n\n /**\n * The absolute URI for the forwardchannel request.\n * @private {?goog.Uri}\n */\n this.forwardChannelUri_ = null;\n\n /**\n * The absolute URI for the backchannel request.\n * @private {?goog.Uri}\n */\n this.backChannelUri_ = null;\n\n /**\n * A subdomain prefix for using a subdomain in IE for the backchannel\n * requests.\n * @private {?string}\n */\n this.hostPrefix_ = null;\n\n /**\n * Whether we allow the use of a subdomain in IE for the backchannel requests.\n * @private {boolean}\n */\n this.allowHostPrefix_ = true;\n\n /**\n * The next id to use for the RID (request identifier) parameter. This\n * identifier uniquely identifies the forward channel request.\n * @private {number}\n */\n this.nextRid_ = 0;\n\n /**\n * The id to use for the next outgoing map. This identifier uniquely\n * identifies a sent map.\n * @private {number}\n */\n this.nextMapId_ = 0;\n\n /**\n * Whether to fail forward-channel requests after one try or a few tries.\n * @private {boolean}\n */\n this.failFast_ = getInternalChannelParam('failFast', false, opt_options);\n\n /**\n * The handler that receive callbacks for state changes and data.\n * @private {?goog.labs.net.webChannel.WebChannelBase.Handler}\n */\n this.handler_ = null;\n\n /**\n * Timer identifier for asynchronously making a forward channel request.\n * This is set to true if the func is scheduled with async.run, which\n * is equivalent to setTimeout(0).\n * @private {?number|?boolean}\n */\n this.forwardChannelTimerId_ = null;\n\n /**\n * Timer identifier for asynchronously making a back channel request.\n * @private {?number}\n */\n this.backChannelTimerId_ = null;\n\n /**\n * Timer identifier for the timer that waits for us to retry the backchannel\n * in the case where it is dead and no longer receiving data.\n * @private {?number}\n */\n this.deadBackChannelTimerId_ = null;\n\n /**\n * Whether the client's network conditions can support streamed responses.\n * @private {?boolean}\n */\n this.enableStreaming_ = null;\n\n /**\n * Whether streaming mode is allowed. In certain debugging situations, it's\n * useful to disable this.\n * @private {boolean}\n */\n this.allowStreamingMode_ = true;\n\n /**\n * The array identifier of the last array received from the server for the\n * backchannel request.\n * @private {number}\n */\n this.lastArrayId_ = -1;\n\n /**\n * The array id of the last array sent by the server that we know about.\n * @private {number}\n */\n this.lastPostResponseArrayId_ = -1;\n\n /**\n * The last status code received (until `State.CLOSED` is reached).\n * @private {number}\n */\n this.lastStatusCode_ = -1;\n\n /**\n * Number of times we have retried the current forward channel request.\n * @private {number}\n */\n this.forwardChannelRetryCount_ = 0;\n\n /**\n * Number of times in a row that we have retried the current back channel\n * request and received no data.\n * @private {number}\n */\n this.backChannelRetryCount_ = 0;\n\n /**\n * The attempt id for the current back channel request. Starts at 1 and\n * increments for each reconnect. The server uses this to log if our\n * connection is flaky or not.\n * @private {number}\n */\n this.backChannelAttemptId_ = 0;\n\n /**\n * The base part of the time before firing next retry request. Default is 5\n * seconds. Note that a random delay is added (see {@link retryDelaySeedMs_})\n * for all retries, and linear backoff is applied to the sum for subsequent\n * retries.\n * @private {number}\n */\n this.baseRetryDelayMs_ =\n getInternalChannelParam('baseRetryDelayMs', 5 * 1000, opt_options);\n\n /**\n * A random time between 0 and this number of MS is added to the\n * {@link baseRetryDelayMs_}. Default is 10 seconds.\n * @private {number}\n */\n this.retryDelaySeedMs_ =\n getInternalChannelParam('retryDelaySeedMs', 10 * 1000, opt_options);\n\n /**\n * Maximum number of attempts to connect to the server for forward channel\n * requests. Defaults to 2.\n * @private {number}\n */\n this.forwardChannelMaxRetries_ =\n getInternalChannelParam('forwardChannelMaxRetries', 2, opt_options);\n\n /**\n * The timeout in milliseconds for a forward channel request. Defaults to 20\n * seconds. Note that part of this timeout can be randomized.\n * @private {number}\n */\n this.forwardChannelRequestTimeoutMs_ = getInternalChannelParam(\n 'forwardChannelRequestTimeoutMs', 20 * 1000, opt_options);\n\n /**\n * The custom factory used to create XMLHttpRequest objects.\n * @private {!goog.net.XmlHttpFactory | undefined}\n */\n this.xmlHttpFactory_ =\n (opt_options && opt_options.xmlHttpFactory) || undefined;\n\n /**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @private {boolean}\n */\n this.usesFetchStreams_ =\n (opt_options && opt_options.useFetchStreams) || false;\n\n /**\n * The timeout in milliseconds for a back channel request. Defaults to using\n * the timeout configured in ChannelRequest (45s). If server-side\n * keepaliveInterval is known to the client, set the backchannel request\n * timeout to 1.5 * keepaliveInterval (ms).\n *\n * @private {number|undefined}\n */\n this.backChannelRequestTimeoutMs_ = undefined;\n\n /**\n * A throttle time in ms for readystatechange events for the backchannel.\n * Useful for throttling when ready state is INTERACTIVE (partial data).\n *\n * This throttle is useful if the server sends large data chunks down the\n * backchannel. It prevents examining XHR partial data on every readystate\n * change event. This is useful because large chunks can trigger hundreds\n * of readystatechange events, each of which takes ~5ms or so to handle,\n * in turn making the UI unresponsive for a significant period.\n *\n * If set to zero no throttle is used.\n * @private {number}\n */\n this.readyStateChangeThrottleMs_ = 0;\n\n /**\n * Whether cross origin requests are supported for the channel.\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @private {boolean}\n */\n this.supportsCrossDomainXhrs_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * The current session id.\n * @private {string}\n */\n this.sid_ = '';\n\n /**\n * The current ChannelRequest pool for the forward channel.\n * @private {!ForwardChannelRequestPool}\n */\n this.forwardChannelRequestPool_ = new ForwardChannelRequestPool(\n opt_options && opt_options.concurrentRequestLimit);\n\n /**\n * The V8 codec.\n * @private {!WireV8}\n */\n this.wireCodec_ = new WireV8();\n\n /**\n * Whether to turn on the fast handshake behavior.\n *\n * @private {boolean}\n */\n this.fastHandshake_ = (opt_options && opt_options.fastHandshake) || false;\n\n /**\n * Whether to encode initMessageHeaders in the body.\n *\n * @private {boolean}\n */\n this.encodeInitMessageHeaders_ =\n (opt_options && opt_options.encodeInitMessageHeaders) || false;\n\n if (this.fastHandshake_ && this.encodeInitMessageHeaders_) {\n this.channelDebug_.warning(\n 'Ignore encodeInitMessageHeaders because fastHandshake is set.');\n this.encodeInitMessageHeaders_ = false;\n }\n\n /**\n * Whether to signal to the server to enable blocking handshake.\n *\n * @private {boolean}\n */\n this.blockingHandshake_ =\n (opt_options && opt_options.blockingHandshake) || false;\n\n\n if (opt_options && opt_options.disableRedact) {\n this.channelDebug_.disableRedact();\n }\n\n if (opt_options && opt_options.forceLongPolling) {\n this.allowStreamingMode_ = false;\n }\n\n /**\n * Whether to detect buffering proxies.\n *\n * fastHandshake + detectBufferingProxy are yet to be implemented.\n *\n * @private {boolean}\n */\n this.detectBufferingProxy_ =\n (!this.fastHandshake_ && this.allowStreamingMode_ && opt_options &&\n opt_options.detectBufferingProxy) ||\n false;\n\n /**\n * Callback when all the pending client-sent messages have been flushed.\n *\n * @private {function()|undefined}\n */\n this.forwardChannelFlushedCallback_ = undefined;\n\n /**\n * TODO(user): move all backchannel states to its own class similar to\n * forwardchannelrequestpool.js and log more stats.\n *\n * The estimated handshake RTT (ms) as measured from when the handshake\n * request is sent and when the handshake response headers are received.\n * If the value is 0, the RTT is unknown.\n *\n * @private {number}\n */\n this.handshakeRttMs_ = 0;\n\n /**\n * If BP detection is done or still in progress.\n * Should only be checked when detectBufferingProxy is turned on.\n * @private {boolean}\n */\n this.bpDetectionDone_ = false;\n\n /**\n * The timer for detecting buffering proxy. This needs be reset with each\n * backchannel request. If this is not null, bpDetectionDone_ == false.\n * @private {?number}\n */\n this.bpDetectionTimerId_ = null;\n\n /***\n * Whether to attempt Chrome Origin Trials as part of the handshake.\n * @private @const {boolean}\n */\n this.enableOriginTrials_ = ALLOW_ORIGIN_TRIAL_FEATURES &&\n (!opt_options || opt_options.enableOriginTrials !== false);\n\n /**\n * The array of non-acked maps at the time of channel close. Refer to\n * `getNonAckedMessagesWithClosedChannel()` API for definitions of non-acked\n * messages.\n *\n * @private {?Array<!Wire.QueuedMap>}\n */\n this.nonAckedMapsAtChannelClose_ = null;\n};\n\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\n\n\n/**\n * The channel version that we negotiated with the server for this session.\n * Starts out as the version we request, and then is changed to the negotiated\n * version after the initial open.\n * @private {number}\n */\nWebChannelBase.prototype.channelVersion_ = Wire.LATEST_CHANNEL_VERSION;\n\n\n/**\n * Enum type for the channel state machine.\n * @enum {number}\n */\nWebChannelBase.State = {\n /** The channel is closed. */\n CLOSED: 0,\n\n /** The channel has been initialized but hasn't yet initiated a connection. */\n INIT: 1,\n\n /** The channel is in the process of opening a connection to the server. */\n OPENING: 2,\n\n /** The channel is open. */\n OPENED: 3\n};\n\n\n/**\n * The current state of the WebChannel.\n * @private {!WebChannelBase.State}\n */\nWebChannelBase.prototype.state_ = WebChannelBase.State.INIT;\n\n\n/**\n * The timeout in milliseconds for a forward channel request.\n * @type {number}\n */\nWebChannelBase.FORWARD_CHANNEL_RETRY_TIMEOUT = 20 * 1000;\n\n\n/**\n * Maximum number of attempts to connect to the server for back channel\n * requests.\n * @type {number}\n */\nWebChannelBase.BACK_CHANNEL_MAX_RETRIES = 3;\n\n\n/**\n * A number in MS of how long we guess the maxmium amount of time a round trip\n * to the server should take. In the future this could be substituted with a\n * real measurement of the RTT.\n * @type {number}\n */\nWebChannelBase.RTT_ESTIMATE = 3 * 1000;\n\n\n/**\n * When retrying for an inactive channel, we will multiply the total delay by\n * this number.\n * @type {number}\n */\nWebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR = 2;\n\n\n/**\n * Enum type for identifying an error.\n * @enum {number}\n */\nWebChannelBase.Error = {\n /** Value that indicates no error has occurred. */\n OK: 0,\n\n /** An error due to a request failing. */\n REQUEST_FAILED: 2,\n\n /** An error due to the user being logged out. */\n LOGGED_OUT: 4,\n\n /** An error due to server response which contains no data. */\n NO_DATA: 5,\n\n /** An error due to a server response indicating an unknown session id */\n UNKNOWN_SESSION_ID: 6,\n\n /** An error due to a server response requesting to stop the channel. */\n STOP: 7,\n\n /** A general network error. */\n NETWORK: 8,\n\n /** An error due to bad data being returned from the server. */\n BAD_DATA: 10,\n\n /** An error due to a response that is not parsable. */\n BAD_RESPONSE: 11\n};\n\n\n/**\n * Internal enum type for the two channel types.\n * @enum {number}\n * @private\n */\nWebChannelBase.ChannelType_ = {\n FORWARD_CHANNEL: 1,\n\n BACK_CHANNEL: 2\n};\n\n\n/**\n * The maximum number of maps that can be sent in one POST. Should match\n * MAX_MAPS_PER_REQUEST on the server code.\n * @type {number}\n * @private\n */\nWebChannelBase.MAX_MAPS_PER_REQUEST_ = 1000;\n\n\n/**\n * The maximum number of utf-8 chars that can be sent in one GET to enable 0-RTT\n * handshake.\n *\n * @const @private {number}\n */\nWebChannelBase.MAX_CHARS_PER_GET_ = 4 * 1024;\n\n\n/**\n * A guess at a cutoff at which to no longer assume the backchannel is dead\n * when we are slow to receive data. Number in bytes.\n *\n * Assumption: The worst bandwidth we work on is 50 kilobits/sec\n * 50kbits/sec * (1 byte / 8 bits) * 6 sec dead backchannel timeout\n * @type {number}\n */\nWebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF = 37500;\n\n\n/**\n * @return {number} The server version or 0 if undefined\n */\nWebChannelBase.prototype.getServerVersion = function() {\n 'use strict';\n return this.serverVersion_;\n};\n\n\n/**\n * @return {!ForwardChannelRequestPool} The forward channel request pool.\n */\nWebChannelBase.prototype.getForwardChannelRequestPool = function() {\n 'use strict';\n return this.forwardChannelRequestPool_;\n};\n\n\n/**\n * @return {!Object} The codec object.\n */\nWebChannelBase.prototype.getWireCodec = function() {\n 'use strict';\n return this.wireCodec_;\n};\n\n\n/**\n * Returns the logger.\n *\n * @return {!WebChannelDebug} The channel debug object.\n */\nWebChannelBase.prototype.getChannelDebug = function() {\n 'use strict';\n return this.channelDebug_;\n};\n\n\n/**\n * Sets the logger.\n *\n * @param {!WebChannelDebug} channelDebug The channel debug object.\n */\nWebChannelBase.prototype.setChannelDebug = function(channelDebug) {\n 'use strict';\n this.channelDebug_ = channelDebug;\n};\n\n\n/**\n * Starts the channel. This initiates connections to the server.\n *\n * @param {string} channelPath The path for the channel connection.\n * @param {!Object=} opt_extraParams Extra parameter keys and values to add to\n * the requests.\n * @param {string=} opt_oldSessionId Session ID from a previous session.\n * @param {number=} opt_oldArrayId The last array ID from a previous session.\n */\nWebChannelBase.prototype.connect = function(\n channelPath, opt_extraParams, opt_oldSessionId, opt_oldArrayId) {\n 'use strict';\n this.channelDebug_.debug('connect()');\n\n this.startOriginTrials_(channelPath);\n\n requestStats.notifyStatEvent(requestStats.Stat.CONNECT_ATTEMPT);\n\n this.path_ = channelPath;\n this.extraParams_ = opt_extraParams || {};\n\n // Attach parameters about the previous session if reconnecting.\n if (opt_oldSessionId && opt_oldArrayId !== undefined) {\n this.extraParams_['OSID'] = opt_oldSessionId;\n this.extraParams_['OAID'] = opt_oldArrayId;\n }\n\n this.enableStreaming_ = this.allowStreamingMode_;\n this.connectChannel_();\n};\n\n\n/**\n * Disconnects and closes the channel.\n */\nWebChannelBase.prototype.disconnect = function() {\n 'use strict';\n this.channelDebug_.debug('disconnect()');\n\n this.cancelRequests_();\n\n if (this.state_ == WebChannelBase.State.OPENED) {\n const rid = this.nextRid_++;\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('TYPE', 'terminate');\n\n this.addAdditionalParams_(uri);\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid);\n request.sendCloseRequest(uri);\n }\n\n this.onClose_();\n};\n\n\n/**\n * Returns the session id of the channel. Only available after the\n * channel has been opened.\n * @return {string} Session ID.\n */\nWebChannelBase.prototype.getSessionId = function() {\n 'use strict';\n return this.sid_;\n};\n\n\n/**\n * Starts the connection.\n * @private\n */\nWebChannelBase.prototype.connectChannel_ = function() {\n 'use strict';\n this.channelDebug_.debug('connectChannel_()');\n this.ensureInState_(WebChannelBase.State.INIT, WebChannelBase.State.CLOSED);\n this.forwardChannelUri_ =\n this.getForwardChannelUri(/** @type {string} */ (this.path_));\n this.ensureForwardChannel_();\n};\n\n\n/**\n * Starts the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.startOriginTrials_ = function(channelPath) {\n 'use strict';\n\n if (!this.enableOriginTrials_) {\n return;\n }\n\n this.channelDebug_.info('Origin Trials enabled.');\n goog.async.run(goog.bind(this.runOriginTrials_, this, channelPath));\n};\n\n\n/**\n * Runs the Origin Trials.\n * @param {string} channelPath The path for the channel connection.\n * @private\n */\nWebChannelBase.prototype.runOriginTrials_ = function(channelPath) {\n 'use strict';\n\n try {\n // Since startOriginTrials might throw exceptions asynchronously, we should\n // capture it in promise-catch.\n environment.startOriginTrials(channelPath, e => {\n this.channelDebug_.dumpException(\n /** @type {?Error} */ (e), 'Error in running origin trials');\n });\n this.channelDebug_.info('Origin Trials invoked: ' + channelPath);\n } catch (e) {\n this.channelDebug_.dumpException(e, 'Error in running origin trials');\n }\n};\n\n\n/**\n * Cancels backchannel request.\n * @private\n */\nWebChannelBase.prototype.cancelBackChannelRequest_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n this.clearBpDetectionTimer_();\n this.backChannelRequest_.cancel();\n this.backChannelRequest_ = null;\n }\n};\n\n\n/**\n * Cancels all outstanding requests.\n * @private\n */\nWebChannelBase.prototype.cancelRequests_ = function() {\n 'use strict';\n this.cancelBackChannelRequest_();\n\n if (this.backChannelTimerId_) {\n goog.global.clearTimeout(this.backChannelTimerId_);\n this.backChannelTimerId_ = null;\n }\n\n this.clearDeadBackchannelTimer_();\n\n this.forwardChannelRequestPool_.cancel();\n\n if (this.forwardChannelTimerId_) {\n this.clearForwardChannelTimer_();\n }\n};\n\n\n/**\n * Clears the forward channel timer.\n * @private\n */\nWebChannelBase.prototype.clearForwardChannelTimer_ = function() {\n 'use strict';\n if (typeof this.forwardChannelTimerId_ === 'number') {\n goog.global.clearTimeout(this.forwardChannelTimerId_);\n }\n\n this.forwardChannelTimerId_ = null;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to all the requests sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getExtraHeaders = function() {\n 'use strict';\n return this.extraHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to all the requests sent to the server.\n *\n * @param {Object} extraHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setExtraHeaders = function(extraHeaders) {\n 'use strict';\n this.extraHeaders_ = extraHeaders;\n};\n\n\n/**\n * Returns the extra HTTP headers to add to the init requests\n * sent to the server.\n *\n * @return {Object} The HTTP headers, or null.\n */\nWebChannelBase.prototype.getInitHeaders = function() {\n 'use strict';\n return this.initHeaders_;\n};\n\n\n/**\n * Sets extra HTTP headers to add to the init requests sent to the server.\n *\n * @param {Object} initHeaders The HTTP headers, or null.\n */\nWebChannelBase.prototype.setInitHeaders = function(initHeaders) {\n 'use strict';\n this.initHeaders_ = initHeaders;\n};\n\n\n/**\n * Sets the URL param name to overwrite custom HTTP headers.\n *\n * @param {string} httpHeadersOverwriteParam The URL param name.\n */\nWebChannelBase.prototype.setHttpHeadersOverwriteParam = function(\n httpHeadersOverwriteParam) {\n 'use strict';\n this.httpHeadersOverwriteParam_ = httpHeadersOverwriteParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionIdParam = function(httpSessionIdParam) {\n 'use strict';\n this.httpSessionIdParam_ = httpSessionIdParam;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionIdParam = function() {\n 'use strict';\n return this.httpSessionIdParam_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.setHttpSessionId = function(httpSessionId) {\n 'use strict';\n this.httpSessionId_ = httpSessionId;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getHttpSessionId = function() {\n 'use strict';\n return this.httpSessionId_;\n};\n\n\n/**\n * Sets the throttle for handling onreadystatechange events for the request.\n *\n * @param {number} throttle The throttle in ms. A value of zero indicates\n * no throttle.\n */\nWebChannelBase.prototype.setReadyStateChangeThrottle = function(throttle) {\n 'use strict';\n this.readyStateChangeThrottleMs_ = throttle;\n};\n\n\n/**\n * Sets whether cross origin requests are supported for the channel.\n *\n * Setting this allows the creation of requests to secondary domains and\n * sends XHRs with the CORS withCredentials bit set to true.\n *\n * In order for cross-origin requests to work, the server will also need to set\n * CORS response headers as per:\n * https://developer.mozilla.org/en-US/docs/HTTP_access_control\n *\n * See {@link goog.net.XhrIo#setWithCredentials}.\n * @param {boolean} supportCrossDomain Whether cross domain XHRs are supported.\n */\nWebChannelBase.prototype.setSupportsCrossDomainXhrs = function(\n supportCrossDomain) {\n 'use strict';\n this.supportsCrossDomainXhrs_ = supportCrossDomain;\n};\n\n\n/**\n * Returns the handler used for channel callback events.\n *\n * @return {WebChannelBase.Handler} The handler.\n */\nWebChannelBase.prototype.getHandler = function() {\n 'use strict';\n return this.handler_;\n};\n\n\n/**\n * Sets the handler used for channel callback events.\n * @param {WebChannelBase.Handler} handler The handler to set.\n */\nWebChannelBase.prototype.setHandler = function(handler) {\n 'use strict';\n this.handler_ = handler;\n};\n\n\n/**\n * Returns whether the channel allows the use of a subdomain. There may be\n * cases where this isn't allowed.\n * @return {boolean} Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.getAllowHostPrefix = function() {\n 'use strict';\n return this.allowHostPrefix_;\n};\n\n\n/**\n * Sets whether the channel allows the use of a subdomain. There may be cases\n * where this isn't allowed, for example, logging in with troutboard where\n * using a subdomain causes Apache to force the user to authenticate twice.\n * @param {boolean} allowHostPrefix Whether a host prefix is allowed.\n */\nWebChannelBase.prototype.setAllowHostPrefix = function(allowHostPrefix) {\n 'use strict';\n this.allowHostPrefix_ = allowHostPrefix;\n};\n\n\n/**\n * Returns whether the channel is buffered or not. This may be\n * queried in the WebChannelBase.okToMakeRequest() callback.\n *\n * @return {boolean} Whether the channel is buffered.\n */\nWebChannelBase.prototype.isBuffered = function() {\n 'use strict';\n return !this.enableStreaming_;\n};\n\n\n/**\n * Returns whether streaming mode is allowed. In certain debugging situations,\n * it's useful for the application to have a way to disable streaming mode for a\n * user.\n\n * @return {boolean} Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.getAllowStreamingMode = function() {\n 'use strict';\n return this.allowStreamingMode_;\n};\n\n\n/**\n * Sets whether streaming mode is allowed. In certain debugging situations, it's\n * useful for the application to have a way to disable streaming mode for a\n * user.\n * @param {boolean} allowStreamingMode Whether streaming mode is allowed.\n */\nWebChannelBase.prototype.setAllowStreamingMode = function(allowStreamingMode) {\n 'use strict';\n this.allowStreamingMode_ = allowStreamingMode;\n};\n\n\n/**\n * Sends a request to the server. The format of the request is a Map data\n * structure of key/value pairs. These maps are then encoded in a format\n * suitable for the wire and then reconstituted as a Map data structure that\n * the server can process.\n * @param {!Object|!goog.collections.maps.MapLike} map The map to send.\n * @param {!Object=} opt_context The context associated with the map.\n */\nWebChannelBase.prototype.sendMap = function(map, opt_context) {\n 'use strict';\n goog.asserts.assert(\n this.state_ != WebChannelBase.State.CLOSED,\n 'Invalid operation: sending map when state is closed');\n\n // We can only send 1000 maps per POST, but typically we should never have\n // that much to send, so warn if we exceed that (we still send all the maps).\n if (this.outgoingMaps_.length == WebChannelBase.MAX_MAPS_PER_REQUEST_) {\n // severe() is temporary so that we get these uploaded and can figure out\n // what's causing them. Afterwards can change to warning().\n this.channelDebug_.severe(function() {\n 'use strict';\n return 'Already have ' + WebChannelBase.MAX_MAPS_PER_REQUEST_ +\n ' queued maps upon queueing ' + goog.json.serialize(map);\n });\n }\n\n this.outgoingMaps_.push(\n new Wire.QueuedMap(this.nextMapId_++, map, opt_context));\n\n // Messages need be buffered during OPENING to avoid server-side race\n if (this.state_ == WebChannelBase.State.OPENED) {\n this.ensureForwardChannel_();\n }\n};\n\n\n/**\n * When set to true, this changes the behavior of the forward channel so it\n * will not retry requests; it will fail after one network failure, and if\n * there was already one network failure, the request will fail immediately.\n * @param {boolean} failFast Whether or not to fail fast.\n */\nWebChannelBase.prototype.setFailFast = function(failFast) {\n 'use strict';\n this.failFast_ = failFast;\n this.channelDebug_.info('setFailFast: ' + failFast);\n if ((this.forwardChannelRequestPool_.hasPendingRequest() ||\n this.forwardChannelTimerId_) &&\n this.forwardChannelRetryCount_ > this.getForwardChannelMaxRetries()) {\n const self = this;\n this.channelDebug_.info(function() {\n 'use strict';\n return 'Retry count ' + self.forwardChannelRetryCount_ +\n ' > new maxRetries ' + self.getForwardChannelMaxRetries() +\n '. Fail immediately!';\n });\n\n if (!this.forwardChannelRequestPool_.forceComplete(\n goog.bind(this.onRequestComplete, this))) {\n // i.e., this.forwardChannelTimerId_\n this.clearForwardChannelTimer_();\n // The error code from the last failed request is gone, so just use a\n // generic one.\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n }\n }\n};\n\n\n/**\n * @return {number} The max number of forward-channel retries, which will be 0\n * in fail-fast mode.\n */\nWebChannelBase.prototype.getForwardChannelMaxRetries = function() {\n 'use strict';\n return this.failFast_ ? 0 : this.forwardChannelMaxRetries_;\n};\n\n\n/**\n * Sets the maximum number of attempts to connect to the server for forward\n * channel requests.\n * @param {number} retries The maximum number of attempts.\n */\nWebChannelBase.prototype.setForwardChannelMaxRetries = function(retries) {\n 'use strict';\n this.forwardChannelMaxRetries_ = retries;\n};\n\n\n/**\n * Sets the timeout for a forward channel request.\n * @param {number} timeoutMs The timeout in milliseconds.\n */\nWebChannelBase.prototype.setForwardChannelRequestTimeout = function(timeoutMs) {\n 'use strict';\n this.forwardChannelRequestTimeoutMs_ = timeoutMs;\n};\n\n\n/**\n * @return {number} The max number of back-channel retries, which is a constant.\n */\nWebChannelBase.prototype.getBackChannelMaxRetries = function() {\n 'use strict';\n // Back-channel retries is a constant.\n return WebChannelBase.BACK_CHANNEL_MAX_RETRIES;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isClosed = function() {\n 'use strict';\n return this.state_ == WebChannelBase.State.CLOSED;\n};\n\n\n/**\n * Returns the channel state.\n * @return {WebChannelBase.State} The current state of the channel.\n */\nWebChannelBase.prototype.getState = function() {\n 'use strict';\n return this.state_;\n};\n\n\n/**\n * @return {number} The last status code received (until `State.CLOSED` is\n * reached).\n */\nWebChannelBase.prototype.getLastStatusCode = function() {\n 'use strict';\n return this.lastStatusCode_;\n};\n\n\n/**\n * @return {number} The last array id received.\n */\nWebChannelBase.prototype.getLastArrayId = function() {\n 'use strict';\n return this.lastArrayId_;\n};\n\n\n/**\n * Returns whether there are outstanding requests servicing the channel.\n * @return {boolean} true if there are outstanding requests.\n */\nWebChannelBase.prototype.hasOutstandingRequests = function() {\n 'use strict';\n return this.getOutstandingRequests_() != 0;\n};\n\n\n/**\n * Returns the number of outstanding requests.\n * @return {number} The number of outstanding requests to the server.\n * @private\n */\nWebChannelBase.prototype.getOutstandingRequests_ = function() {\n 'use strict';\n let count = 0;\n if (this.backChannelRequest_) {\n count++;\n }\n count += this.forwardChannelRequestPool_.getRequestCount();\n return count;\n};\n\n\n/**\n * Ensures that a forward channel request is scheduled.\n * @private\n */\nWebChannelBase.prototype.ensureForwardChannel_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.isFull()) {\n // enough connection in process - no need to start a new request\n return;\n }\n\n if (this.forwardChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n this.forwardChannelTimerId_ = true;\n goog.async.run(this.onStartForwardChannelTimer_, this);\n\n this.forwardChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a forward-channel retry for the specified request, unless the max\n * retries has been reached.\n * @param {!ChannelRequest} request The failed request to retry.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryForwardChannel_ = function(request) {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() >=\n this.forwardChannelRequestPool_.getMaxSize() -\n (this.forwardChannelTimerId_ ? 1 : 0)) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Unexpected retry request is scheduled.');\n return false;\n }\n\n if (this.forwardChannelTimerId_) {\n this.channelDebug_.debug(\n 'Use the retry request that is already scheduled.');\n this.outgoingMaps_ =\n request.getPendingMessages().concat(this.outgoingMaps_);\n return true;\n }\n\n // No retry for open_() and fail-fast\n if (this.state_ == WebChannelBase.State.INIT ||\n this.state_ == WebChannelBase.State.OPENING ||\n (this.forwardChannelRetryCount_ >= this.getForwardChannelMaxRetries())) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry POST');\n\n this.forwardChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartForwardChannelTimer_, this, request),\n this.getRetryTime_(this.forwardChannelRetryCount_));\n this.forwardChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureForwardChannel\n * @param {ChannelRequest=} opt_retryRequest A failed request\n * to retry.\n * @private\n */\nWebChannelBase.prototype.onStartForwardChannelTimer_ = function(\n opt_retryRequest) {\n 'use strict';\n // null is possible if scheduled with async.run\n if (this.forwardChannelTimerId_) {\n this.forwardChannelTimerId_ = null;\n this.startForwardChannel_(opt_retryRequest);\n }\n};\n\n\n/**\n * Begins a new forward channel operation to the server.\n * @param {ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.startForwardChannel_ = function(opt_retryRequest) {\n 'use strict';\n this.channelDebug_.debug('startForwardChannel_');\n if (!this.okToMakeRequest_()) {\n return; // channel is cancelled\n } else if (this.state_ == WebChannelBase.State.INIT) {\n if (opt_retryRequest) {\n this.channelDebug_.severe('Not supposed to retry the open');\n return;\n }\n this.open_();\n this.state_ = WebChannelBase.State.OPENING;\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (opt_retryRequest) {\n this.makeForwardChannelRequest_(opt_retryRequest);\n return;\n }\n\n if (this.outgoingMaps_.length == 0) {\n this.channelDebug_.debug(\n 'startForwardChannel_ returned: ' +\n 'nothing to send');\n // no need to start a new forward channel request\n return;\n }\n\n if (this.forwardChannelRequestPool_.isFull()) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe(\n 'startForwardChannel_ returned: ' +\n 'connection already in progress');\n return;\n }\n\n this.makeForwardChannelRequest_();\n this.channelDebug_.debug('startForwardChannel_ finished, sent request');\n }\n};\n\n\n/**\n * Establishes a new channel session with the server.\n * @private\n */\nWebChannelBase.prototype.open_ = function() {\n 'use strict';\n this.channelDebug_.debug('open_()');\n this.nextRid_ = Math.floor(Math.random() * 100000);\n\n const rid = this.nextRid_++;\n const request =\n ChannelRequest.createChannelRequest(this, this.channelDebug_, '', rid);\n\n // mix the init headers\n let extraHeaders = this.extraHeaders_;\n if (this.initHeaders_) {\n if (extraHeaders) {\n extraHeaders = goog.object.clone(extraHeaders);\n goog.object.extend(extraHeaders, this.initHeaders_);\n } else {\n extraHeaders = this.initHeaders_;\n }\n }\n\n if (this.httpHeadersOverwriteParam_ === null &&\n !this.encodeInitMessageHeaders_) {\n request.setExtraHeaders(extraHeaders);\n extraHeaders = null;\n }\n\n let requestText = this.dequeueOutgoingMaps_(\n request,\n this.fastHandshake_ ? this.getMaxNumMessagesForFastHandshake_() :\n WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('RID', rid);\n\n if (this.clientVersion_ > 0) {\n uri.setParameterValue('CVER', this.clientVersion_);\n }\n\n // http-session-id to be generated as the response\n if (this.getHttpSessionIdParam()) {\n uri.setParameterValue(\n WebChannel.X_HTTP_SESSION_ID, this.getHttpSessionIdParam());\n }\n\n this.addAdditionalParams_(uri);\n\n if (extraHeaders) {\n if (this.encodeInitMessageHeaders_) {\n let encodedHeaders =\n httpCors.generateEncodedHttpHeadersOverwriteParam(extraHeaders);\n requestText = 'headers=' + encodedHeaders + '&' + requestText;\n } else if (this.httpHeadersOverwriteParam_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, extraHeaders);\n } // else - should not happen\n }\n\n this.forwardChannelRequestPool_.addRequest(request);\n\n if (this.blockingHandshake_) {\n uri.setParameterValue('TYPE', 'init'); // default to blocking in future\n }\n\n // Check the option and use GET to enable QUIC 0-RTT\n if (this.fastHandshake_) {\n uri.setParameterValue('$req', requestText);\n\n // enable handshake upgrade\n uri.setParameterValue('SID', 'null');\n request.setDecodeInitialResponse();\n\n request.xmlHttpPost(uri, null, true); // Send as a GET\n } else {\n request.xmlHttpPost(uri, requestText, true);\n }\n};\n\n\n/**\n * @return {number} The number of raw JSON messages to be encoded\n * with the fast-handshake (GET) request, including zero. If messages are not\n * encoded as raw JSON data, return WebChannelBase.MAX_MAPS_PER_REQUEST_\n * @private\n */\nWebChannelBase.prototype.getMaxNumMessagesForFastHandshake_ = function() {\n 'use strict';\n let total = 0;\n for (let i = 0; i < this.outgoingMaps_.length; i++) {\n const map = this.outgoingMaps_[i];\n const size = map.getRawDataSize();\n if (size === undefined) {\n break;\n }\n total += size;\n\n if (total > WebChannelBase.MAX_CHARS_PER_GET_) {\n return i;\n }\n\n if (total === WebChannelBase.MAX_CHARS_PER_GET_ ||\n i === this.outgoingMaps_.length - 1) {\n return i + 1;\n }\n }\n\n return WebChannelBase.MAX_MAPS_PER_REQUEST_;\n};\n\n\n\n/**\n * Makes a forward channel request using XMLHTTP.\n * @param {!ChannelRequest=} opt_retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.makeForwardChannelRequest_ = function(\n opt_retryRequest) {\n 'use strict';\n let rid;\n if (opt_retryRequest) {\n rid = opt_retryRequest.getRequestId(); // Reuse the same RID for a retry\n } else {\n rid = this.nextRid_++;\n }\n\n const uri = this.forwardChannelUri_.clone();\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('RID', rid);\n uri.setParameterValue('AID', this.lastArrayId_);\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n const request = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, rid,\n this.forwardChannelRetryCount_ + 1);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n request.setExtraHeaders(this.extraHeaders_);\n }\n\n let requestText;\n if (opt_retryRequest) {\n this.requeuePendingMaps_(opt_retryRequest);\n }\n requestText =\n this.dequeueOutgoingMaps_(request, WebChannelBase.MAX_MAPS_PER_REQUEST_);\n\n // Randomize from 50%-100% of the forward channel timeout to avoid\n // a big hit if servers happen to die at once.\n request.setTimeout(\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50) +\n Math.round(this.forwardChannelRequestTimeoutMs_ * 0.50 * Math.random()));\n this.forwardChannelRequestPool_.addRequest(request);\n request.xmlHttpPost(uri, requestText, true);\n};\n\n\n/**\n * Adds additional query parameters from `extraParams_` and `handler_` to the\n * given URI.\n * @param {!goog.Uri} uri The URI to add the parameters to.\n * @private\n */\nWebChannelBase.prototype.addAdditionalParams_ = function(uri) {\n 'use strict';\n if (this.extraParams_) {\n goog.object.forEach(this.extraParams_, function(value, key) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n\n if (this.handler_) {\n const params = this.handler_.getAdditionalParams(this);\n if (params) {\n goog.structs.forEach(params, function(value, key, coll) {\n 'use strict';\n uri.setParameterValue(key, value);\n });\n }\n }\n};\n\n\n/**\n * Returns the request text from the outgoing maps and resets it.\n * @param {!ChannelRequest} request The new request for sending the messages.\n * @param {number} maxNum The maximum number of messages to be encoded\n * @return {string} The encoded request text created from all the currently\n * queued outgoing maps.\n * @private\n */\nWebChannelBase.prototype.dequeueOutgoingMaps_ = function(request, maxNum) {\n 'use strict';\n const count = Math.min(this.outgoingMaps_.length, maxNum);\n\n const badMapHandler = this.handler_ ?\n goog.bind(this.handler_.badMapError, this.handler_, this) :\n null;\n const result = this.wireCodec_.encodeMessageQueue(\n this.outgoingMaps_, count, badMapHandler);\n\n request.setPendingMessages(this.outgoingMaps_.splice(0, count));\n\n return result;\n};\n\n\n/**\n * Requeues unacknowledged sent arrays for retransmission in the next forward\n * channel request.\n * @param {!ChannelRequest} retryRequest A failed request to retry.\n * @private\n */\nWebChannelBase.prototype.requeuePendingMaps_ = function(retryRequest) {\n 'use strict';\n this.outgoingMaps_ =\n retryRequest.getPendingMessages().concat(this.outgoingMaps_);\n};\n\n\n/**\n * Ensures there is a backchannel request for receiving data from the server.\n * @private\n */\nWebChannelBase.prototype.ensureBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_) {\n // already have one\n return;\n }\n\n if (this.backChannelTimerId_) {\n // no need to start a new request - one is already scheduled\n return;\n }\n\n this.backChannelAttemptId_ = 1;\n\n // Use async.run instead of setTimeout(0) to avoid the 1s message delay\n // from chrome/firefox background tabs\n // backChannelTimerId_ stays unset, as with setTimeout(0)\n goog.async.run(this.onStartBackChannelTimer_, this);\n\n this.backChannelRetryCount_ = 0;\n};\n\n\n/**\n * Schedules a back-channel retry, unless the max retries has been reached.\n * @return {boolean} true iff a retry was scheduled.\n * @private\n */\nWebChannelBase.prototype.maybeRetryBackChannel_ = function() {\n 'use strict';\n if (this.backChannelRequest_ || this.backChannelTimerId_) {\n // Should be impossible to be called in this state.\n this.channelDebug_.severe('Request already in progress');\n return false;\n }\n\n if (this.backChannelRetryCount_ >= this.getBackChannelMaxRetries()) {\n return false;\n }\n\n this.channelDebug_.debug('Going to retry GET');\n\n this.backChannelAttemptId_++;\n this.backChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onStartBackChannelTimer_, this),\n this.getRetryTime_(this.backChannelRetryCount_));\n this.backChannelRetryCount_++;\n return true;\n};\n\n\n/**\n * Timer callback for ensureBackChannel_.\n * @private\n */\nWebChannelBase.prototype.onStartBackChannelTimer_ = function() {\n 'use strict';\n this.backChannelTimerId_ = null;\n this.startBackChannel_();\n\n if (!this.detectBufferingProxy_) {\n return;\n }\n\n if (this.bpDetectionDone_) {\n return;\n }\n\n if (this.backChannelRequest_ == null || this.handshakeRttMs_ <= 0) {\n this.channelDebug_.warning(\n 'Skip bpDetectionTimerId_ ' + this.backChannelRequest_ + ' ' +\n this.handshakeRttMs_);\n return;\n }\n\n // This goes with each new request until bpDetectionDone_\n const bpDetectionTimeout = 2 * this.handshakeRttMs_;\n this.channelDebug_.info('BP detection timer enabled: ' + bpDetectionTimeout);\n\n this.bpDetectionTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBpDetectionTimer_, this), bpDetectionTimeout);\n};\n\n\n/**\n * Timer callback for bpDetection.\n * @private\n */\nWebChannelBase.prototype.onBpDetectionTimer_ = function() {\n 'use strict';\n if (!this.bpDetectionTimerId_) {\n this.channelDebug_.warning('Invalid operation.');\n return;\n }\n\n this.bpDetectionTimerId_ = null;\n this.channelDebug_.info('BP detection timeout reached.');\n\n goog.asserts.assert(\n this.backChannelRequest_ != null,\n 'Invalid state: no backchannel request');\n\n // We wait for extra response payload in addition to just headers to\n // cancel the timer.\n if (this.backChannelRequest_.getXhr() != null) {\n const responseData = this.backChannelRequest_.getXhr().getResponseText();\n if (responseData) {\n this.channelDebug_.warning(\n 'Timer should have been cancelled : ' + responseData);\n }\n }\n\n // Enable long-polling\n this.channelDebug_.info(\n 'Buffering proxy detected and switch to long-polling!');\n this.enableStreaming_ = false;\n\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.PROXY);\n\n // Cancel the request and start a new one immediately\n this.cancelBackChannelRequest_();\n this.startBackChannel_();\n};\n\n\n/**\n * Clears the timer for BP detection.\n * @private\n */\nWebChannelBase.prototype.clearBpDetectionTimer_ = function() {\n 'use strict';\n if (this.bpDetectionTimerId_ != null) {\n this.channelDebug_.debug('Cancel the BP detection timer.');\n goog.global.clearTimeout(this.bpDetectionTimerId_);\n this.bpDetectionTimerId_ = null;\n }\n};\n\n\n/**\n * Begins a new back channel operation to the server.\n * @private\n */\nWebChannelBase.prototype.startBackChannel_ = function() {\n 'use strict';\n if (!this.okToMakeRequest_()) {\n // channel is cancelled\n return;\n }\n\n this.channelDebug_.debug('Creating new HttpRequest');\n this.backChannelRequest_ = ChannelRequest.createChannelRequest(\n this, this.channelDebug_, this.sid_, 'rpc', this.backChannelAttemptId_);\n\n if (this.httpHeadersOverwriteParam_ === null) {\n this.backChannelRequest_.setExtraHeaders(this.extraHeaders_);\n }\n\n this.backChannelRequest_.setReadyStateChangeThrottle(\n this.readyStateChangeThrottleMs_);\n const uri = this.backChannelUri_.clone();\n uri.setParameterValue('RID', 'rpc');\n uri.setParameterValue('SID', this.sid_);\n uri.setParameterValue('CI', this.enableStreaming_ ? '0' : '1');\n uri.setParameterValue('AID', this.lastArrayId_);\n uri.setParameterValue('TYPE', 'xmlhttp');\n\n this.addAdditionalParams_(uri);\n\n if (this.httpHeadersOverwriteParam_ && this.extraHeaders_) {\n httpCors.setHttpHeadersWithOverwriteParam(\n uri, this.httpHeadersOverwriteParam_, this.extraHeaders_);\n }\n\n if (this.backChannelRequestTimeoutMs_) {\n this.backChannelRequest_.setTimeout(this.backChannelRequestTimeoutMs_);\n }\n\n this.backChannelRequest_.xmlHttpGet(\n uri, true /* decodeChunks */, this.hostPrefix_);\n\n this.channelDebug_.debug('New Request created');\n};\n\n\n/**\n * Gives the handler a chance to return an error code and stop channel\n * execution. A handler might want to do this to check that the user is still\n * logged in, for example.\n * @private\n * @return {boolean} If it's OK to make a request.\n */\nWebChannelBase.prototype.okToMakeRequest_ = function() {\n 'use strict';\n if (this.handler_) {\n const result = this.handler_.okToMakeRequest(this);\n if (result != WebChannelBase.Error.OK) {\n this.channelDebug_.debug(\n 'Handler returned error code from okToMakeRequest');\n this.signalError_(result);\n return false;\n }\n }\n return true;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onFirstByteReceived = function(request, responseText) {\n 'use strict';\n if (this.backChannelRequest_ == request && this.detectBufferingProxy_) {\n if (!this.bpDetectionDone_) {\n this.channelDebug_.info(\n 'Great, no buffering proxy detected. Bytes received: ' +\n responseText.length);\n goog.asserts.assert(\n this.bpDetectionTimerId_, 'Timer should not have been cancelled.');\n this.clearBpDetectionTimer_();\n this.bpDetectionDone_ = true;\n requestStats.notifyStatEvent(requestStats.Stat.NOPROXY);\n }\n }\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onRequestData = function(request, responseText) {\n 'use strict';\n if (this.state_ == WebChannelBase.State.CLOSED ||\n (this.backChannelRequest_ != request &&\n !this.forwardChannelRequestPool_.hasRequest(request))) {\n // either CLOSED or a request we don't know about (perhaps an old request)\n return;\n }\n\n // first to check if request has been upgraded to backchannel\n if (!request.isInitialResponseDecoded() &&\n this.forwardChannelRequestPool_.hasRequest(request) &&\n this.state_ == WebChannelBase.State.OPENED) {\n let response;\n try {\n response = this.wireCodec_.decodeMessage(responseText);\n } catch (ex) {\n response = null;\n }\n if (Array.isArray(response) && response.length == 3) {\n this.handlePostResponse_(/** @type {!Array<?>} */ (response), request);\n this.onForwardChannelFlushed_();\n } else {\n this.channelDebug_.debug('Bad POST response data returned');\n this.signalError_(WebChannelBase.Error.BAD_RESPONSE);\n }\n } else {\n if (request.isInitialResponseDecoded() ||\n this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n }\n\n if (!goog.string.isEmptyOrWhitespace(responseText)) {\n let response = this.wireCodec_.decodeMessage(responseText);\n this.onInput_(/** @type {!Array<?>} */ (response), request);\n }\n }\n};\n\n\n/**\n * Checks if we need call the flush callback.\n *\n * @private\n */\nWebChannelBase.prototype.onForwardChannelFlushed_ = function() {\n 'use strict';\n if (this.forwardChannelRequestPool_.getRequestCount() <= 1) {\n if (this.forwardChannelFlushedCallback_) {\n try {\n this.forwardChannelFlushedCallback_();\n } catch (ex) {\n this.channelDebug_.dumpException(\n ex, 'Exception from forwardChannelFlushedCallback_ ');\n }\n // reset\n this.forwardChannelFlushedCallback_ = undefined;\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server.\n * @param {Array<number>} responseValues The key value pairs in\n * the POST response.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n */\nWebChannelBase.prototype.handlePostResponse_ = function(\n responseValues, forwardReq) {\n 'use strict';\n // The first response value is set to 0 if server is missing backchannel.\n if (responseValues[0] == 0) {\n this.handleBackchannelMissing_(forwardReq);\n return;\n }\n this.lastPostResponseArrayId_ = responseValues[1];\n const outstandingArrays = this.lastPostResponseArrayId_ - this.lastArrayId_;\n if (0 < outstandingArrays) {\n const numOutstandingBackchannelBytes = responseValues[2];\n this.channelDebug_.debug(\n numOutstandingBackchannelBytes + ' bytes (in ' + outstandingArrays +\n ' arrays) are outstanding on the BackChannel');\n if (!this.shouldRetryBackChannel_(numOutstandingBackchannelBytes)) {\n return;\n }\n if (!this.deadBackChannelTimerId_) {\n // We expect to receive data within 2 RTTs or we retry the backchannel.\n this.deadBackChannelTimerId_ = requestStats.setTimeout(\n goog.bind(this.onBackChannelDead_, this),\n 2 * WebChannelBase.RTT_ESTIMATE);\n }\n }\n};\n\n\n/**\n * Handles a POST response from the server telling us that it has detected that\n * we have no hanging GET connection.\n * @param {!ChannelRequest} forwardReq The forward channel request that\n * triggers this function call.\n * @private\n */\nWebChannelBase.prototype.handleBackchannelMissing_ = function(forwardReq) {\n 'use strict';\n // As long as the back channel was started before the POST was sent,\n // we should retry the backchannel. We give a slight buffer of RTT_ESTIMATE\n // so as not to excessively retry the backchannel\n this.channelDebug_.debug('Server claims our backchannel is missing.');\n if (this.backChannelTimerId_) {\n this.channelDebug_.debug('But we are currently starting the request.');\n return;\n } else if (!this.backChannelRequest_) {\n this.channelDebug_.warning('We do not have a BackChannel established');\n } else if (\n this.backChannelRequest_.getRequestStartTime() +\n WebChannelBase.RTT_ESTIMATE <\n forwardReq.getRequestStartTime()) {\n this.clearDeadBackchannelTimer_();\n this.cancelBackChannelRequest_();\n } else {\n return;\n }\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_MISSING);\n};\n\n\n/**\n * Determines whether we should start the process of retrying a possibly\n * dead backchannel.\n * @param {number} outstandingBytes The number of bytes for which the server has\n * not yet received acknowledgement.\n * @return {boolean} Whether to start the backchannel retry timer.\n * @private\n */\nWebChannelBase.prototype.shouldRetryBackChannel_ = function(outstandingBytes) {\n 'use strict';\n // Not too many outstanding bytes, not buffered and not after a retry.\n return outstandingBytes <\n WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF &&\n !this.isBuffered() && this.backChannelRetryCount_ == 0;\n};\n\n\n/**\n * Decides which host prefix should be used, if any. If there is a handler,\n * allows the handler to validate a host prefix provided by the server, and\n * optionally override it.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix to actually use, if any. Will return null\n * if the use of host prefixes was disabled via setAllowHostPrefix().\n * @override\n */\nWebChannelBase.prototype.correctHostPrefix = function(serverHostPrefix) {\n 'use strict';\n if (this.allowHostPrefix_) {\n if (this.handler_) {\n return this.handler_.correctHostPrefix(serverHostPrefix);\n }\n return serverHostPrefix;\n }\n return null;\n};\n\n\n/**\n * Handles the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.onBackChannelDead_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n this.deadBackChannelTimerId_ = null;\n this.cancelBackChannelRequest_();\n this.maybeRetryBackChannel_();\n requestStats.notifyStatEvent(requestStats.Stat.BACKCHANNEL_DEAD);\n }\n};\n\n\n/**\n * Clears the timer that indicates that our backchannel is no longer able to\n * successfully receive data from the server.\n * @private\n */\nWebChannelBase.prototype.clearDeadBackchannelTimer_ = function() {\n 'use strict';\n if (this.deadBackChannelTimerId_ != null) {\n goog.global.clearTimeout(this.deadBackChannelTimerId_);\n this.deadBackChannelTimerId_ = null;\n }\n};\n\n\n/**\n * Returns whether or not the given error/status combination is fatal or not.\n * On fatal errors we immediately close the session rather than retrying the\n * failed request.\n * @param {?ChannelRequest.Error} error The error code for the\n * failed request.\n * @param {number} statusCode The last HTTP status code.\n * @return {boolean} Whether or not the error is fatal.\n * @private\n */\nWebChannelBase.isFatalError_ = function(error, statusCode) {\n 'use strict';\n return error == ChannelRequest.Error.UNKNOWN_SESSION_ID ||\n (error == ChannelRequest.Error.STATUS && statusCode > 0);\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.onRequestComplete = function(request) {\n 'use strict';\n this.channelDebug_.debug('Request complete');\n let type;\n let pendingMessages = null;\n if (this.backChannelRequest_ == request) {\n this.clearDeadBackchannelTimer_();\n this.clearBpDetectionTimer_();\n this.backChannelRequest_ = null;\n type = WebChannelBase.ChannelType_.BACK_CHANNEL;\n } else if (this.forwardChannelRequestPool_.hasRequest(request)) {\n pendingMessages = request.getPendingMessages();\n this.forwardChannelRequestPool_.removeRequest(request);\n type = WebChannelBase.ChannelType_.FORWARD_CHANNEL;\n } else {\n // return if it was an old request from a previous session\n return;\n }\n\n if (this.state_ == WebChannelBase.State.CLOSED) {\n return;\n }\n\n this.lastStatusCode_ = request.getLastStatusCode();\n\n if (request.getSuccess()) {\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n const size = request.getPostData() ? request.getPostData().length : 0;\n requestStats.notifyTimingEvent(\n size, Date.now() - request.getRequestStartTime(),\n this.forwardChannelRetryCount_);\n this.ensureForwardChannel_();\n this.onSuccess_(request);\n } else { // i.e., back-channel\n this.ensureBackChannel_();\n }\n return;\n }\n // Else unsuccessful. Fall through.\n\n const lastError = request.getLastError();\n if (!WebChannelBase.isFatalError_(lastError, this.lastStatusCode_)) {\n // Maybe retry.\n const self = this;\n this.channelDebug_.debug(function() {\n 'use strict';\n return 'Maybe retrying, last error: ' +\n ChannelRequest.errorStringFromCode(lastError, self.lastStatusCode_);\n });\n if (type == WebChannelBase.ChannelType_.FORWARD_CHANNEL) {\n if (this.maybeRetryForwardChannel_(request)) {\n return;\n }\n }\n if (type == WebChannelBase.ChannelType_.BACK_CHANNEL) {\n if (this.maybeRetryBackChannel_()) {\n return;\n }\n }\n // Else exceeded max retries. Fall through.\n this.channelDebug_.debug('Exceeded max number of retries');\n } else {\n // Else fatal error. Fall through and mark the pending maps as failed.\n this.channelDebug_.debug('Not retrying due to error type');\n }\n\n\n // Abort the channel now\n\n // Record pending messages from the failed request\n if (pendingMessages && pendingMessages.length > 0) {\n this.forwardChannelRequestPool_.addPendingMessages(pendingMessages);\n }\n\n this.channelDebug_.debug('Error: HTTP request failed');\n switch (lastError) {\n case ChannelRequest.Error.NO_DATA:\n this.signalError_(WebChannelBase.Error.NO_DATA);\n break;\n case ChannelRequest.Error.BAD_DATA:\n this.signalError_(WebChannelBase.Error.BAD_DATA);\n break;\n case ChannelRequest.Error.UNKNOWN_SESSION_ID:\n this.signalError_(WebChannelBase.Error.UNKNOWN_SESSION_ID);\n break;\n default:\n this.signalError_(WebChannelBase.Error.REQUEST_FAILED);\n break;\n }\n};\n\n\n/**\n * @param {number} retryCount Number of retries so far.\n * @return {number} Time in ms before firing next retry request.\n * @private\n */\nWebChannelBase.prototype.getRetryTime_ = function(retryCount) {\n 'use strict';\n let retryTime = this.baseRetryDelayMs_ +\n Math.floor(Math.random() * this.retryDelaySeedMs_);\n if (!this.isActive()) {\n this.channelDebug_.debug('Inactive channel');\n retryTime = retryTime * WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR;\n }\n // Backoff for subsequent retries\n retryTime *= retryCount;\n return retryTime;\n};\n\n\n/**\n * @param {number} baseDelayMs The base part of the retry delay, in ms.\n * @param {number} delaySeedMs A random delay between 0 and this is added to\n * the base part.\n */\nWebChannelBase.prototype.setRetryDelay = function(baseDelayMs, delaySeedMs) {\n 'use strict';\n this.baseRetryDelayMs_ = baseDelayMs;\n this.retryDelaySeedMs_ = delaySeedMs;\n};\n\n\n/**\n * Apply any handshake control headers.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.applyControlHeaders_ = function(request) {\n 'use strict';\n const xhr = request.getXhr();\n if (xhr) {\n const clientProtocol =\n xhr.getStreamingResponseHeader(WebChannel.X_CLIENT_WIRE_PROTOCOL);\n if (clientProtocol) {\n this.forwardChannelRequestPool_.applyClientProtocol(clientProtocol);\n }\n\n if (this.getHttpSessionIdParam()) {\n const httpSessionIdHeader =\n xhr.getStreamingResponseHeader(WebChannel.X_HTTP_SESSION_ID);\n if (httpSessionIdHeader) {\n this.setHttpSessionId(httpSessionIdHeader);\n // update the cached uri\n const httpSessionIdParam = this.getHttpSessionIdParam();\n\n this.forwardChannelUri_.setParameterValue(\n /** @type {string} */ (httpSessionIdParam), // never null\n httpSessionIdHeader);\n } else {\n this.channelDebug_.warning(\n 'Missing X_HTTP_SESSION_ID in the handshake response');\n }\n }\n }\n};\n\n\n/**\n * Processes the data returned by the server.\n * @param {!Array<!Array<?>>} respArray The response array returned\n * by the server.\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.onInput_ = function(respArray, request) {\n 'use strict';\n const batch =\n this.handler_ && this.handler_.channelHandleMultipleArrays ? [] : null;\n for (let i = 0; i < respArray.length; i++) {\n let nextArray = respArray[i];\n this.lastArrayId_ = nextArray[0];\n nextArray = nextArray[1];\n if (this.state_ == WebChannelBase.State.OPENING) {\n if (nextArray[0] == 'c') {\n this.sid_ = nextArray[1];\n this.hostPrefix_ = this.correctHostPrefix(nextArray[2]);\n\n const negotiatedVersion = nextArray[3];\n if (negotiatedVersion != null) {\n this.channelVersion_ = negotiatedVersion;\n this.channelDebug_.info('VER=' + this.channelVersion_);\n }\n\n const negotiatedServerVersion = nextArray[4];\n if (negotiatedServerVersion != null) {\n this.serverVersion_ = negotiatedServerVersion;\n this.channelDebug_.info('SVER=' + this.serverVersion_);\n }\n\n // CVER=22\n const serverKeepaliveMs = nextArray[5];\n if (serverKeepaliveMs != null &&\n typeof serverKeepaliveMs === 'number' && serverKeepaliveMs > 0) {\n const timeout = 1.5 * serverKeepaliveMs;\n this.backChannelRequestTimeoutMs_ = timeout;\n this.channelDebug_.info('backChannelRequestTimeoutMs_=' + timeout);\n }\n\n this.applyControlHeaders_(request);\n\n this.state_ = WebChannelBase.State.OPENED;\n if (this.handler_) {\n this.handler_.channelOpened(this);\n }\n\n if (this.detectBufferingProxy_) {\n this.handshakeRttMs_ = Date.now() - request.getRequestStartTime();\n this.channelDebug_.info(\n 'Handshake RTT: ' + this.handshakeRttMs_ + 'ms');\n }\n\n this.startBackchannelAfterHandshake_(request);\n\n if (this.outgoingMaps_.length > 0) {\n this.ensureForwardChannel_();\n }\n } else if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n // treat close also as an abort\n this.signalError_(WebChannelBase.Error.STOP);\n }\n } else if (this.state_ == WebChannelBase.State.OPENED) {\n if (nextArray[0] == 'stop' || nextArray[0] == 'close') {\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n batch.length = 0;\n }\n if (nextArray[0] == 'stop') {\n this.signalError_(WebChannelBase.Error.STOP);\n } else {\n this.disconnect();\n }\n } else if (nextArray[0] == 'noop') {\n // ignore - noop to keep connection happy\n } else {\n if (batch) {\n batch.push(nextArray);\n } else if (this.handler_) {\n this.handler_.channelHandleArray(this, nextArray);\n }\n }\n // We have received useful data on the back-channel, so clear its retry\n // count. We do this because back-channels by design do not complete\n // quickly, so on a flaky connection we could have many fail to complete\n // fully but still deliver a lot of data before they fail. We don't want\n // to count such failures towards the retry limit, because we don't want\n // to give up on a session if we can still receive data.\n this.backChannelRetryCount_ = 0;\n }\n }\n if (batch && !(batch.length === 0)) {\n this.handler_.channelHandleMultipleArrays(this, batch);\n }\n};\n\n\n/**\n * Starts the backchannel after the handshake.\n *\n * @param {!ChannelRequest} request The underlying request object\n * @private\n */\nWebChannelBase.prototype.startBackchannelAfterHandshake_ = function(request) {\n 'use strict';\n this.backChannelUri_ = this.getBackChannelUri(\n this.hostPrefix_, /** @type {string} */ (this.path_));\n\n if (request.isInitialResponseDecoded()) {\n this.channelDebug_.debug('Upgrade the handshake request to a backchannel.');\n this.forwardChannelRequestPool_.removeRequest(request);\n request.resetTimeout(this.backChannelRequestTimeoutMs_);\n this.backChannelRequest_ = request;\n } else {\n this.ensureBackChannel_();\n }\n};\n\n\n/**\n * Helper to ensure the channel is in the expected state.\n * @param {...number} var_args The channel must be in one of the indicated\n * states.\n * @private\n */\nWebChannelBase.prototype.ensureInState_ = function(var_args) {\n 'use strict';\n goog.asserts.assert(\n goog.array.contains(arguments, this.state_),\n 'Unexpected channel state: %s', this.state_);\n};\n\n\n/**\n * Signals an error has occurred.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.signalError_ = function(error) {\n 'use strict';\n this.channelDebug_.info('Error code ' + error);\n if (error == WebChannelBase.Error.REQUEST_FAILED) {\n // Create a separate Internet connection to check\n // if it's a server error or user's network error.\n let imageUri = null;\n if (this.handler_) {\n imageUri = this.handler_.getNetworkTestImageUri(this);\n }\n netUtils.testNetwork(goog.bind(this.testNetworkCallback_, this), imageUri);\n } else {\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n }\n this.onError_(error);\n};\n\n\n/**\n * Callback for netUtils.testNetwork during error handling.\n * @param {boolean} networkUp Whether the network is up.\n * @private\n */\nWebChannelBase.prototype.testNetworkCallback_ = function(networkUp) {\n 'use strict';\n if (networkUp) {\n this.channelDebug_.info('Successfully pinged google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_OTHER);\n } else {\n this.channelDebug_.info('Failed to ping google.com');\n requestStats.notifyStatEvent(requestStats.Stat.ERROR_NETWORK);\n // Do not call onError_ again to eliminate duplicated Error events.\n }\n};\n\n\n/**\n * Called when messages have been successfully sent from the queue.\n * @param {!ChannelRequest} request The request object\n * @private\n */\nWebChannelBase.prototype.onSuccess_ = function(request) {\n 'use strict';\n if (this.handler_) {\n this.handler_.channelSuccess(this, request);\n }\n};\n\n\n/**\n * Called when we've determined the final error for a channel. It closes the\n * notifiers the handler of the error and closes the channel.\n * @param {WebChannelBase.Error} error The error code for the failure.\n * @private\n */\nWebChannelBase.prototype.onError_ = function(error) {\n 'use strict';\n this.channelDebug_.debug('HttpChannel: error - ' + error);\n this.state_ = WebChannelBase.State.CLOSED;\n if (this.handler_) {\n this.handler_.channelError(this, error);\n }\n this.onClose_();\n this.cancelRequests_();\n};\n\n\n/**\n * Called when the channel has been closed. It notifiers the handler of the\n * event, and reports any pending or undelivered maps.\n * @private\n */\nWebChannelBase.prototype.onClose_ = function() {\n 'use strict';\n this.state_ = WebChannelBase.State.CLOSED;\n this.nonAckedMapsAtChannelClose_ = [];\n if (this.handler_) {\n const pendingMessages =\n this.forwardChannelRequestPool_.getPendingMessages();\n\n if (pendingMessages.length == 0 && this.outgoingMaps_.length == 0) {\n this.handler_.channelClosed(this);\n } else {\n this.channelDebug_.debug(\n () => 'Number of undelivered maps' +\n ', pending: ' + pendingMessages.length +\n ', outgoing: ' + this.outgoingMaps_.length);\n\n goog.array.extend(this.nonAckedMapsAtChannelClose_, pendingMessages);\n goog.array.extend(this.nonAckedMapsAtChannelClose_, this.outgoingMaps_);\n\n this.forwardChannelRequestPool_.clearPendingMessages();\n\n const copyOfUndeliveredMaps = goog.array.clone(this.outgoingMaps_);\n this.outgoingMaps_.length = 0;\n\n this.handler_.channelClosed(this, pendingMessages, copyOfUndeliveredMaps);\n }\n }\n};\n\n/**\n * @return {!Array<!Wire.QueuedMap>} Returns the list of non-acked maps, both\n * during an active channel or after the channel is closed. Refer to the\n * `getNonAckedMessages()` API for definitions of non-acked messages.\n */\nWebChannelBase.prototype.getNonAckedMaps = function() {\n if (this.state_ == WebChannelBase.State.CLOSED) {\n goog.asserts.assert(\n this.nonAckedMapsAtChannelClose_ != null,\n 'nonAckedMapsAtChannelClose_ is not set after channel close.');\n return this.nonAckedMapsAtChannelClose_;\n }\n\n // The underlying message objects are not cloned and thus exposes a mutability\n // risk, but is chosen to make strict equality (i.e. ===) checks possible for\n // callers.\n let unAckedMaps = [];\n goog.array.extend(\n unAckedMaps, this.forwardChannelRequestPool_.getPendingMessages());\n goog.array.extend(unAckedMaps, this.outgoingMaps_);\n\n return unAckedMaps;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getForwardChannelUri = function(path) {\n 'use strict';\n const uri = this.createDataUri(null, path);\n this.channelDebug_.debug('GetForwardChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getConnectionState = function() {\n 'use strict';\n return this.connState_;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.getBackChannelUri = function(hostPrefix, path) {\n 'use strict';\n const uri = this.createDataUri(\n this.shouldUseSecondaryDomains() ? hostPrefix : null, path);\n this.channelDebug_.debug('GetBackChannelUri: ' + uri);\n return uri;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.createDataUri = function(\n hostPrefix, path, opt_overridePort) {\n 'use strict';\n let uri = goog.Uri.parse(path);\n const uriAbsolute = (uri.getDomain() != '');\n if (uriAbsolute) {\n if (hostPrefix) {\n uri.setDomain(hostPrefix + '.' + uri.getDomain());\n }\n\n uri.setPort(opt_overridePort || uri.getPort());\n } else {\n const locationPage = goog.global.location;\n let hostName;\n if (hostPrefix) {\n hostName = hostPrefix + '.' + locationPage.hostname;\n } else {\n hostName = locationPage.hostname;\n }\n\n const port = opt_overridePort || +locationPage.port;\n\n uri = goog.Uri.create(locationPage.protocol, null, hostName, port, path);\n }\n\n const param = this.getHttpSessionIdParam();\n const value = this.getHttpSessionId();\n if (param && value) {\n uri.setParameterValue(param, value);\n }\n\n // Add the protocol version to the URI.\n uri.setParameterValue('VER', this.channelVersion_);\n\n this.addAdditionalParams_(uri);\n\n return uri;\n};\n\n/**\n * @override\n * @param {?string} hostPrefix The host prefix, if we need an XhrIo object\n * capable of calling a secondary domain.\n * @param {boolean=} isStreaming Whether or not fetch/streams are enabled for\n * the underlying HTTP request.\n * @return {!goog.net.XhrIo} A new XhrIo object.\n */\nWebChannelBase.prototype.createXhrIo = function(hostPrefix, isStreaming) {\n 'use strict';\n if (hostPrefix && !this.supportsCrossDomainXhrs_) {\n throw new Error('Can\\'t create secondary domain capable XhrIo object.');\n }\n let xhr;\n if (isStreaming && this.usesFetchStreams_ && !this.xmlHttpFactory_) {\n xhr = new goog.net.XhrIo(\n new goog.net.FetchXmlHttpFactory({streamBinaryChunks: true}));\n } else {\n xhr = new goog.net.XhrIo(this.xmlHttpFactory_);\n }\n xhr.setWithCredentials(this.supportsCrossDomainXhrs_);\n return xhr;\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.isActive = function() {\n 'use strict';\n return !!this.handler_ && this.handler_.isActive(this);\n};\n\n\n/**\n * @override\n */\nWebChannelBase.prototype.shouldUseSecondaryDomains = function() {\n 'use strict';\n return this.supportsCrossDomainXhrs_;\n};\n\n\n/**\n * Sets (overwrites) the forward channel flush callback.\n *\n * @param {function()} callback The callback to be invoked.\n */\nWebChannelBase.prototype.setForwardChannelFlushCallback = function(callback) {\n 'use strict';\n this.forwardChannelFlushedCallback_ = callback;\n};\n\n\n/**\n * Abstract base class for the channel handler\n * @constructor\n * @struct\n */\nWebChannelBase.Handler = function() {};\n\n\n/**\n * Callback handler for when a batch of response arrays is received from the\n * server. When null, batched dispatching is disabled.\n * @type {?function(!WebChannelBase, !Array<!Array<?>>)}\n */\nWebChannelBase.Handler.prototype.channelHandleMultipleArrays = null;\n\n\n/**\n * Whether it's okay to make a request to the server. A handler can return\n * false if the channel should fail. For example, if the user has logged out,\n * the handler may want all requests to fail immediately.\n * @param {WebChannelBase} channel The channel.\n * @return {WebChannelBase.Error} An error code. The code should\n * return WebChannelBase.Error.OK to indicate it's okay. Any other\n * error code will cause a failure.\n */\nWebChannelBase.Handler.prototype.okToMakeRequest = function(channel) {\n 'use strict';\n return WebChannelBase.Error.OK;\n};\n\n\n/**\n * Indicates the WebChannel has successfully negotiated with the server\n * and can now send and receive data.\n * @param {WebChannelBase} channel The channel.\n */\nWebChannelBase.Handler.prototype.channelOpened = function(channel) {};\n\n\n/**\n * New input is available for the application to process.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {Array<?>} array The data array.\n */\nWebChannelBase.Handler.prototype.channelHandleArray = function(\n channel, array) {};\n\n\n/**\n * Indicates messages that have been successfully sent on the channel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {!ChannelRequest} request The request object that contains\n * the pending messages that have been successfully delivered to the server.\n */\nWebChannelBase.Handler.prototype.channelSuccess = function(channel, request) {};\n\n\n/**\n * Indicates an error occurred on the WebChannel.\n *\n * @param {WebChannelBase} channel The channel.\n * @param {WebChannelBase.Error} error The error code.\n */\nWebChannelBase.Handler.prototype.channelError = function(channel, error) {};\n\n\n/**\n * Indicates the WebChannel is closed. Also notifies about which maps,\n * if any, that may not have been delivered to the server.\n * @param {WebChannelBase} channel The channel.\n * @param {Array<Wire.QueuedMap>=} opt_pendingMaps The\n * array of pending maps, which may or may not have been delivered to the\n * server.\n * @param {Array<Wire.QueuedMap>=} opt_undeliveredMaps\n * The array of undelivered maps, which have definitely not been delivered\n * to the server.\n */\nWebChannelBase.Handler.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {};\n\n\n/**\n * Gets any parameters that should be added at the time another connection is\n * made to the server.\n * @param {WebChannelBase} channel The channel.\n * @return {!Object} Extra parameter keys and values to add to the requests.\n */\nWebChannelBase.Handler.prototype.getAdditionalParams = function(channel) {\n 'use strict';\n return {};\n};\n\n\n/**\n * Gets the URI of an image that can be used to test network connectivity.\n * @param {WebChannelBase} channel The channel.\n * @return {goog.Uri?} A custom URI to load for the network test.\n */\nWebChannelBase.Handler.prototype.getNetworkTestImageUri = function(channel) {\n 'use strict';\n return null;\n};\n\n\n/**\n * Gets whether this channel is currently active. This is used to determine the\n * length of time to wait before retrying.\n * @param {WebChannelBase} channel The channel.\n * @return {boolean} Whether the channel is currently active.\n */\nWebChannelBase.Handler.prototype.isActive = function(channel) {\n 'use strict';\n return true;\n};\n\n/**\n * Whether or not this channel uses WHATWG Fetch/streams.\n * @override\n * @return {boolean}\n */\nWebChannelBase.prototype.usesFetchStreams = function() {\n 'use strict';\n return this.usesFetchStreams_;\n};\n\n\n/**\n * Called by the channel if enumeration of the map throws an exception.\n * @param {WebChannelBase} channel The channel.\n * @param {Object} map The map that can't be enumerated.\n */\nWebChannelBase.Handler.prototype.badMapError = function(channel, map) {};\n\n\n/**\n * Allows the handler to override a host prefix provided by the server. Will\n * be called whenever the channel has received such a prefix and is considering\n * its use.\n * @param {?string} serverHostPrefix The host prefix provided by the server.\n * @return {?string} The host prefix the client should use.\n */\nWebChannelBase.Handler.prototype.correctHostPrefix = function(\n serverHostPrefix) {\n 'use strict';\n return serverHostPrefix;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Class for parsing and formatting URIs.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * Use goog.Uri(string) to parse a URI string. Use goog.Uri.create(...) to\n * create a new instance of the goog.Uri object from Uri parts.\n *\n * e.g: <code>var myUri = new goog.Uri(window.location);</code>\n *\n * Implements RFC 3986 for parsing/formatting URIs.\n * http://www.ietf.org/rfc/rfc3986.txt\n *\n * Some changes have been made to the interface (more like .NETs), though the\n * internal representation is now of un-encoded parts, this will change the\n * behavior slightly.\n */\n\ngoog.provide('goog.Uri');\ngoog.provide('goog.Uri.QueryData');\n\ngoog.require('goog.array');\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.string');\ngoog.require('goog.structs');\ngoog.require('goog.uri.utils');\ngoog.require('goog.uri.utils.ComponentIndex');\ngoog.require('goog.uri.utils.StandardQueryParam');\n\n\n\n/**\n * This class contains setters and getters for the parts of the URI.\n * The <code>getXyz</code>/<code>setXyz</code> methods return the decoded part\n * -- so<code>goog.Uri.parse('/foo%20bar').getPath()</code> will return the\n * decoded path, <code>/foo bar</code>.\n *\n * Reserved characters (see RFC 3986 section 2.2) can be present in\n * their percent-encoded form in scheme, domain, and path URI components and\n * will not be auto-decoded. For example:\n * <code>goog.Uri.parse('rel%61tive/path%2fto/resource').getPath()</code> will\n * return <code>relative/path%2fto/resource</code>.\n *\n * The constructor accepts an optional unparsed, raw URI string. The parser\n * is relaxed, so special characters that aren't escaped but don't cause\n * ambiguities will not cause parse failures.\n *\n * All setters return <code>this</code> and so may be chained, a la\n * <code>goog.Uri.parse('/foo').setFragment('part').toString()</code>.\n *\n * @param {*=} opt_uri Optional string URI to parse\n * (use goog.Uri.create() to create a URI from parts), or if\n * a goog.Uri is passed, a clone is created.\n * @param {boolean=} opt_ignoreCase If true, #getParameterValue will ignore\n * the case of the parameter name.\n *\n * @throws URIError If opt_uri is provided and URI is malformed (that is,\n * if decodeURIComponent fails on any of the URI components).\n * @constructor\n * @struct\n */\ngoog.Uri = function(opt_uri, opt_ignoreCase) {\n 'use strict';\n /**\n * Scheme such as \"http\".\n * @private {string}\n */\n this.scheme_ = '';\n\n /**\n * User credentials in the form \"username:password\".\n * @private {string}\n */\n this.userInfo_ = '';\n\n /**\n * Domain part, e.g. \"www.google.com\".\n * @private {string}\n */\n this.domain_ = '';\n\n /**\n * Port, e.g. 8080.\n * @private {?number}\n */\n this.port_ = null;\n\n /**\n * Path, e.g. \"/tests/img.png\".\n * @private {string}\n */\n this.path_ = '';\n\n /**\n * The fragment without the #.\n * @private {string}\n */\n this.fragment_ = '';\n\n /**\n * Whether or not this Uri should be treated as Read Only.\n * @private {boolean}\n */\n this.isReadOnly_ = false;\n\n /**\n * Whether or not to ignore case when comparing query params.\n * @private {boolean}\n */\n this.ignoreCase_ = false;\n\n /**\n * Object representing query data.\n * @private {!goog.Uri.QueryData}\n */\n this.queryData_;\n\n // Parse in the uri string\n var m;\n if (opt_uri instanceof goog.Uri) {\n this.ignoreCase_ = (opt_ignoreCase !== undefined) ? opt_ignoreCase :\n opt_uri.getIgnoreCase();\n this.setScheme(opt_uri.getScheme());\n this.setUserInfo(opt_uri.getUserInfo());\n this.setDomain(opt_uri.getDomain());\n this.setPort(opt_uri.getPort());\n this.setPath(opt_uri.getPath());\n this.setQueryData(opt_uri.getQueryData().clone());\n this.setFragment(opt_uri.getFragment());\n } else if (opt_uri && (m = goog.uri.utils.split(String(opt_uri)))) {\n this.ignoreCase_ = !!opt_ignoreCase;\n\n // Set the parts -- decoding as we do so.\n // COMPATIBILITY NOTE - In IE, unmatched fields may be empty strings,\n // whereas in other browsers they will be undefined.\n this.setScheme(m[goog.uri.utils.ComponentIndex.SCHEME] || '', true);\n this.setUserInfo(m[goog.uri.utils.ComponentIndex.USER_INFO] || '', true);\n this.setDomain(m[goog.uri.utils.ComponentIndex.DOMAIN] || '', true);\n this.setPort(m[goog.uri.utils.ComponentIndex.PORT]);\n this.setPath(m[goog.uri.utils.ComponentIndex.PATH] || '', true);\n this.setQueryData(m[goog.uri.utils.ComponentIndex.QUERY_DATA] || '', true);\n this.setFragment(m[goog.uri.utils.ComponentIndex.FRAGMENT] || '', true);\n\n } else {\n this.ignoreCase_ = !!opt_ignoreCase;\n this.queryData_ = new goog.Uri.QueryData(null, this.ignoreCase_);\n }\n};\n\n\n/**\n * Parameter name added to stop caching.\n * @type {string}\n */\ngoog.Uri.RANDOM_PARAM = goog.uri.utils.StandardQueryParam.RANDOM;\n\n\n/**\n * @return {string} The string form of the url.\n * @override\n */\ngoog.Uri.prototype.toString = function() {\n 'use strict';\n var out = [];\n\n var scheme = this.getScheme();\n if (scheme) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n scheme, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n ':');\n }\n\n var domain = this.getDomain();\n if (domain || scheme == 'file') {\n out.push('//');\n\n var userInfo = this.getUserInfo();\n if (userInfo) {\n out.push(\n goog.Uri.encodeSpecialChars_(\n userInfo, goog.Uri.reDisallowedInSchemeOrUserInfo_, true),\n '@');\n }\n\n out.push(goog.Uri.removeDoubleEncoding_(goog.string.urlEncode(domain)));\n\n var port = this.getPort();\n if (port != null) {\n out.push(':', String(port));\n }\n }\n\n var path = this.getPath();\n if (path) {\n if (this.hasDomain() && path.charAt(0) != '/') {\n out.push('/');\n }\n out.push(goog.Uri.encodeSpecialChars_(\n path,\n path.charAt(0) == '/' ? goog.Uri.reDisallowedInAbsolutePath_ :\n goog.Uri.reDisallowedInRelativePath_,\n true));\n }\n\n var query = this.getEncodedQuery();\n if (query) {\n out.push('?', query);\n }\n\n var fragment = this.getFragment();\n if (fragment) {\n out.push(\n '#',\n goog.Uri.encodeSpecialChars_(\n fragment, goog.Uri.reDisallowedInFragment_));\n }\n return out.join('');\n};\n\n\n/**\n * Resolves the given relative URI (a goog.Uri object), using the URI\n * represented by this instance as the base URI.\n *\n * There are several kinds of relative URIs:<br>\n * 1. foo - replaces the last part of the path, the whole query and fragment<br>\n * 2. /foo - replaces the path, the query and fragment<br>\n * 3. //foo - replaces everything from the domain on. foo is a domain name<br>\n * 4. ?foo - replace the query and fragment<br>\n * 5. #foo - replace the fragment only\n *\n * Additionally, if relative URI has a non-empty path, all \"..\" and \".\"\n * segments will be resolved, as described in RFC 3986.\n *\n * @param {!goog.Uri} relativeUri The relative URI to resolve.\n * @return {!goog.Uri} The resolved URI.\n */\ngoog.Uri.prototype.resolve = function(relativeUri) {\n 'use strict';\n var absoluteUri = this.clone();\n\n // we satisfy these conditions by looking for the first part of relativeUri\n // that is not blank and applying defaults to the rest\n\n var overridden = relativeUri.hasScheme();\n\n if (overridden) {\n absoluteUri.setScheme(relativeUri.getScheme());\n } else {\n overridden = relativeUri.hasUserInfo();\n }\n\n if (overridden) {\n absoluteUri.setUserInfo(relativeUri.getUserInfo());\n } else {\n overridden = relativeUri.hasDomain();\n }\n\n if (overridden) {\n absoluteUri.setDomain(relativeUri.getDomain());\n } else {\n overridden = relativeUri.hasPort();\n }\n\n var path = relativeUri.getPath();\n if (overridden) {\n absoluteUri.setPort(relativeUri.getPort());\n } else {\n overridden = relativeUri.hasPath();\n if (overridden) {\n // resolve path properly\n if (path.charAt(0) != '/') {\n // path is relative\n if (this.hasDomain() && !this.hasPath()) {\n // RFC 3986, section 5.2.3, case 1\n path = '/' + path;\n } else {\n // RFC 3986, section 5.2.3, case 2\n var lastSlashIndex = absoluteUri.getPath().lastIndexOf('/');\n if (lastSlashIndex != -1) {\n path = absoluteUri.getPath().substr(0, lastSlashIndex + 1) + path;\n }\n }\n }\n path = goog.Uri.removeDotSegments(path);\n }\n }\n\n if (overridden) {\n absoluteUri.setPath(path);\n } else {\n overridden = relativeUri.hasQuery();\n }\n\n if (overridden) {\n absoluteUri.setQueryData(relativeUri.getQueryData().clone());\n } else {\n overridden = relativeUri.hasFragment();\n }\n\n if (overridden) {\n absoluteUri.setFragment(relativeUri.getFragment());\n }\n\n return absoluteUri;\n};\n\n\n/**\n * Clones the URI instance.\n * @return {!goog.Uri} New instance of the URI object.\n */\ngoog.Uri.prototype.clone = function() {\n 'use strict';\n return new goog.Uri(this);\n};\n\n\n/**\n * @return {string} The encoded scheme/protocol for the URI.\n */\ngoog.Uri.prototype.getScheme = function() {\n 'use strict';\n return this.scheme_;\n};\n\n\n/**\n * Sets the scheme/protocol.\n * @throws URIError If opt_decode is true and newScheme is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newScheme New scheme value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setScheme = function(newScheme, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.scheme_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newScheme, true) : newScheme;\n\n // remove an : at the end of the scheme so somebody can pass in\n // window.location.protocol\n if (this.scheme_) {\n this.scheme_ = this.scheme_.replace(/:$/, '');\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the scheme has been set.\n */\ngoog.Uri.prototype.hasScheme = function() {\n 'use strict';\n return !!this.scheme_;\n};\n\n\n/**\n * @return {string} The decoded user info.\n */\ngoog.Uri.prototype.getUserInfo = function() {\n 'use strict';\n return this.userInfo_;\n};\n\n\n/**\n * Sets the userInfo.\n * @throws URIError If opt_decode is true and newUserInfo is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newUserInfo New userInfo value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setUserInfo = function(newUserInfo, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.userInfo_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newUserInfo) : newUserInfo;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the user info has been set.\n */\ngoog.Uri.prototype.hasUserInfo = function() {\n 'use strict';\n return !!this.userInfo_;\n};\n\n\n/**\n * @return {string} The decoded domain.\n */\ngoog.Uri.prototype.getDomain = function() {\n 'use strict';\n return this.domain_;\n};\n\n\n/**\n * Sets the domain.\n * @throws URIError If opt_decode is true and newDomain is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newDomain New domain value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setDomain = function(newDomain, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.domain_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newDomain, true) : newDomain;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the domain has been set.\n */\ngoog.Uri.prototype.hasDomain = function() {\n 'use strict';\n return !!this.domain_;\n};\n\n\n/**\n * @return {?number} The port number.\n */\ngoog.Uri.prototype.getPort = function() {\n 'use strict';\n return this.port_;\n};\n\n\n/**\n * Sets the port number.\n * @param {*} newPort Port number. Will be explicitly casted to a number.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPort = function(newPort) {\n 'use strict';\n this.enforceReadOnly();\n\n if (newPort) {\n newPort = Number(newPort);\n if (isNaN(newPort) || newPort < 0) {\n throw new Error('Bad port number ' + newPort);\n }\n this.port_ = newPort;\n } else {\n this.port_ = null;\n }\n\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the port has been set.\n */\ngoog.Uri.prototype.hasPort = function() {\n 'use strict';\n return this.port_ != null;\n};\n\n\n/**\n * @return {string} The decoded path.\n */\ngoog.Uri.prototype.getPath = function() {\n 'use strict';\n return this.path_;\n};\n\n\n/**\n * Sets the path.\n * @throws URIError If opt_decode is true and newPath is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newPath New path value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setPath = function(newPath, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.path_ = opt_decode ? goog.Uri.decodeOrEmpty_(newPath, true) : newPath;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the path has been set.\n */\ngoog.Uri.prototype.hasPath = function() {\n 'use strict';\n return !!this.path_;\n};\n\n\n/**\n * @return {boolean} Whether the query string has been set.\n */\ngoog.Uri.prototype.hasQuery = function() {\n 'use strict';\n return this.queryData_.toString() !== '';\n};\n\n\n/**\n * Sets the query data.\n * @param {goog.Uri.QueryData|string|undefined} queryData QueryData object.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * Applies only if queryData is a string.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQueryData = function(queryData, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n\n if (queryData instanceof goog.Uri.QueryData) {\n this.queryData_ = queryData;\n this.queryData_.setIgnoreCase(this.ignoreCase_);\n } else {\n if (!opt_decode) {\n // QueryData accepts encoded query string, so encode it if\n // opt_decode flag is not true.\n queryData = goog.Uri.encodeSpecialChars_(\n queryData, goog.Uri.reDisallowedInQuery_);\n }\n this.queryData_ = new goog.Uri.QueryData(queryData, this.ignoreCase_);\n }\n\n return this;\n};\n\n\n/**\n * Sets the URI query.\n * @param {string} newQuery New query value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setQuery = function(newQuery, opt_decode) {\n 'use strict';\n return this.setQueryData(newQuery, opt_decode);\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getEncodedQuery = function() {\n 'use strict';\n return this.queryData_.toString();\n};\n\n\n/**\n * @return {string} The decoded URI query, not including the ?.\n */\ngoog.Uri.prototype.getDecodedQuery = function() {\n 'use strict';\n return this.queryData_.toDecodedString();\n};\n\n\n/**\n * Returns the query data.\n * @return {!goog.Uri.QueryData} QueryData object.\n */\ngoog.Uri.prototype.getQueryData = function() {\n 'use strict';\n return this.queryData_;\n};\n\n\n/**\n * @return {string} The encoded URI query, not including the ?.\n *\n * Warning: This method, unlike other getter methods, returns encoded\n * value, instead of decoded one.\n */\ngoog.Uri.prototype.getQuery = function() {\n 'use strict';\n return this.getEncodedQuery();\n};\n\n\n/**\n * Sets the value of the named query parameters, clearing previous values for\n * that key.\n *\n * @param {string} key The parameter to set.\n * @param {*} value The new value. Value does not need to be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValue = function(key, value) {\n 'use strict';\n this.enforceReadOnly();\n this.queryData_.set(key, value);\n return this;\n};\n\n\n/**\n * Sets the values of the named query parameters, clearing previous values for\n * that key. Not new values will currently be moved to the end of the query\n * string.\n *\n * So, <code>goog.Uri.parse('foo?a=b&c=d&e=f').setParameterValues('c', ['new'])\n * </code> yields <tt>foo?a=b&e=f&c=new</tt>.</p>\n *\n * @param {string} key The parameter to set.\n * @param {*} values The new values. If values is a single\n * string then it will be treated as the sole value. Values do not need to\n * be encoded.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setParameterValues = function(key, values) {\n 'use strict';\n this.enforceReadOnly();\n\n if (!Array.isArray(values)) {\n values = [String(values)];\n }\n\n this.queryData_.setValues(key, values);\n\n return this;\n};\n\n\n/**\n * Returns the value<b>s</b> for a given cgi parameter as a list of decoded\n * query parameter values.\n * @param {string} name The parameter to get values for.\n * @return {!Array<?>} The values for a given cgi parameter as a list of\n * decoded query parameter values.\n */\ngoog.Uri.prototype.getParameterValues = function(name) {\n 'use strict';\n return this.queryData_.getValues(name);\n};\n\n\n/**\n * Returns the first value for a given cgi parameter or undefined if the given\n * parameter name does not appear in the query string.\n * @param {string} paramName Unescaped parameter name.\n * @return {string|undefined} The first value for a given cgi parameter or\n * undefined if the given parameter name does not appear in the query\n * string.\n */\ngoog.Uri.prototype.getParameterValue = function(paramName) {\n 'use strict';\n return /** @type {string|undefined} */ (this.queryData_.get(paramName));\n};\n\n\n/**\n * @return {string} The URI fragment, not including the #.\n */\ngoog.Uri.prototype.getFragment = function() {\n 'use strict';\n return this.fragment_;\n};\n\n\n/**\n * Sets the URI fragment.\n * @throws URIError If opt_decode is true and newFragment is malformed (that is,\n * if decodeURIComponent fails).\n * @param {string} newFragment New fragment value.\n * @param {boolean=} opt_decode Optional param for whether to decode new value.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.setFragment = function(newFragment, opt_decode) {\n 'use strict';\n this.enforceReadOnly();\n this.fragment_ =\n opt_decode ? goog.Uri.decodeOrEmpty_(newFragment) : newFragment;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI has a fragment set.\n */\ngoog.Uri.prototype.hasFragment = function() {\n 'use strict';\n return !!this.fragment_;\n};\n\n\n/**\n * Returns true if this has the same domain as that of uri2.\n * @param {!goog.Uri} uri2 The URI object to compare to.\n * @return {boolean} true if same domain; false otherwise.\n */\ngoog.Uri.prototype.hasSameDomainAs = function(uri2) {\n 'use strict';\n return ((!this.hasDomain() && !uri2.hasDomain()) ||\n this.getDomain() == uri2.getDomain()) &&\n ((!this.hasPort() && !uri2.hasPort()) ||\n this.getPort() == uri2.getPort());\n};\n\n\n/**\n * Adds a random parameter to the Uri.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.makeUnique = function() {\n 'use strict';\n this.enforceReadOnly();\n this.setParameterValue(goog.Uri.RANDOM_PARAM, goog.string.getRandomString());\n\n return this;\n};\n\n\n/**\n * Removes the named query parameter.\n *\n * @param {string} key The parameter to remove.\n * @return {!goog.Uri} Reference to this URI object.\n */\ngoog.Uri.prototype.removeParameter = function(key) {\n 'use strict';\n this.enforceReadOnly();\n this.queryData_.remove(key);\n return this;\n};\n\n\n/**\n * Sets whether Uri is read only. If this goog.Uri is read-only,\n * enforceReadOnly_ will be called at the start of any function that may modify\n * this Uri.\n * @param {boolean} isReadOnly whether this goog.Uri should be read only.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setReadOnly = function(isReadOnly) {\n 'use strict';\n this.isReadOnly_ = isReadOnly;\n return this;\n};\n\n\n/**\n * @return {boolean} Whether the URI is read only.\n */\ngoog.Uri.prototype.isReadOnly = function() {\n 'use strict';\n return this.isReadOnly_;\n};\n\n\n/**\n * Checks if this Uri has been marked as read only, and if so, throws an error.\n * This should be called whenever any modifying function is called.\n */\ngoog.Uri.prototype.enforceReadOnly = function() {\n 'use strict';\n if (this.isReadOnly_) {\n throw new Error('Tried to modify a read-only Uri');\n }\n};\n\n\n/**\n * Sets whether to ignore case.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n * @return {!goog.Uri} Reference to this Uri object.\n */\ngoog.Uri.prototype.setIgnoreCase = function(ignoreCase) {\n 'use strict';\n this.ignoreCase_ = ignoreCase;\n if (this.queryData_) {\n this.queryData_.setIgnoreCase(ignoreCase);\n }\n return this;\n};\n\n\n/**\n * @return {boolean} Whether to ignore case.\n */\ngoog.Uri.prototype.getIgnoreCase = function() {\n 'use strict';\n return this.ignoreCase_;\n};\n\n\n//==============================================================================\n// Static members\n//==============================================================================\n\n\n/**\n * Creates a uri from the string form. Basically an alias of new goog.Uri().\n * If a Uri object is passed to parse then it will return a clone of the object.\n *\n * @throws URIError If parsing the URI is malformed. The passed URI components\n * should all be parseable by decodeURIComponent.\n * @param {*} uri Raw URI string or instance of Uri\n * object.\n * @param {boolean=} opt_ignoreCase Whether to ignore the case of parameter\n * names in #getParameterValue.\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.parse = function(uri, opt_ignoreCase) {\n 'use strict';\n return uri instanceof goog.Uri ? uri.clone() :\n new goog.Uri(uri, opt_ignoreCase);\n};\n\n\n/**\n * Creates a new goog.Uri object from unencoded parts.\n *\n * @param {?string=} opt_scheme Scheme/protocol or full URI to parse.\n * @param {?string=} opt_userInfo username:password.\n * @param {?string=} opt_domain www.google.com.\n * @param {?number=} opt_port 9830.\n * @param {?string=} opt_path /some/path/to/a/file.html.\n * @param {string|goog.Uri.QueryData=} opt_query a=1&b=2.\n * @param {?string=} opt_fragment The fragment without the #.\n * @param {boolean=} opt_ignoreCase Whether to ignore parameter name case in\n * #getParameterValue.\n *\n * @return {!goog.Uri} The new URI object.\n */\ngoog.Uri.create = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_query,\n opt_fragment, opt_ignoreCase) {\n 'use strict';\n var uri = new goog.Uri(null, opt_ignoreCase);\n\n // Only set the parts if they are defined and not empty strings.\n opt_scheme && uri.setScheme(opt_scheme);\n opt_userInfo && uri.setUserInfo(opt_userInfo);\n opt_domain && uri.setDomain(opt_domain);\n opt_port && uri.setPort(opt_port);\n opt_path && uri.setPath(opt_path);\n opt_query && uri.setQueryData(opt_query);\n opt_fragment && uri.setFragment(opt_fragment);\n\n return uri;\n};\n\n\n/**\n * Resolves a relative Uri against a base Uri, accepting both strings and\n * Uri objects.\n *\n * @param {*} base Base Uri.\n * @param {*} rel Relative Uri.\n * @return {!goog.Uri} Resolved uri.\n */\ngoog.Uri.resolve = function(base, rel) {\n 'use strict';\n if (!(base instanceof goog.Uri)) {\n base = goog.Uri.parse(base);\n }\n\n if (!(rel instanceof goog.Uri)) {\n rel = goog.Uri.parse(rel);\n }\n\n return base.resolve(rel);\n};\n\n\n/**\n * Removes dot segments in given path component, as described in\n * RFC 3986, section 5.2.4.\n *\n * @param {string} path A non-empty path component.\n * @return {string} Path component with removed dot segments.\n */\ngoog.Uri.removeDotSegments = function(path) {\n 'use strict';\n if (path == '..' || path == '.') {\n return '';\n\n } else if (\n !goog.string.contains(path, './') && !goog.string.contains(path, '/.')) {\n // This optimization detects uris which do not contain dot-segments,\n // and as a consequence do not require any processing.\n return path;\n\n } else {\n var leadingSlash = goog.string.startsWith(path, '/');\n var segments = path.split('/');\n var out = [];\n\n for (var pos = 0; pos < segments.length;) {\n var segment = segments[pos++];\n\n if (segment == '.') {\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else if (segment == '..') {\n if (out.length > 1 || out.length == 1 && out[0] != '') {\n out.pop();\n }\n if (leadingSlash && pos == segments.length) {\n out.push('');\n }\n } else {\n out.push(segment);\n leadingSlash = true;\n }\n }\n\n return out.join('/');\n }\n};\n\n\n/**\n * Decodes a value or returns the empty string if it isn't defined or empty.\n * @throws URIError If decodeURIComponent fails to decode val.\n * @param {string|undefined} val Value to decode.\n * @param {boolean=} opt_preserveReserved If true, restricted characters will\n * not be decoded.\n * @return {string} Decoded value.\n * @private\n */\ngoog.Uri.decodeOrEmpty_ = function(val, opt_preserveReserved) {\n 'use strict';\n // Don't use UrlDecode() here because val is not a query parameter.\n if (!val) {\n return '';\n }\n\n // decodeURI has the same output for '%2f' and '%252f'. We double encode %25\n // so that we can distinguish between the 2 inputs. This is later undone by\n // removeDoubleEncoding_.\n return opt_preserveReserved ? decodeURI(val.replace(/%25/g, '%2525')) :\n decodeURIComponent(val);\n};\n\n\n/**\n * If unescapedPart is non null, then escapes any characters in it that aren't\n * valid characters in a url and also escapes any special characters that\n * appear in extra.\n *\n * @param {*} unescapedPart The string to encode.\n * @param {RegExp} extra A character set of characters in [\\01-\\177].\n * @param {boolean=} opt_removeDoubleEncoding If true, remove double percent\n * encoding.\n * @return {?string} null iff unescapedPart == null.\n * @private\n */\ngoog.Uri.encodeSpecialChars_ = function(\n unescapedPart, extra, opt_removeDoubleEncoding) {\n 'use strict';\n if (typeof unescapedPart === 'string') {\n var encoded = encodeURI(unescapedPart).replace(extra, goog.Uri.encodeChar_);\n if (opt_removeDoubleEncoding) {\n // encodeURI double-escapes %XX sequences used to represent restricted\n // characters in some URI components, remove the double escaping here.\n encoded = goog.Uri.removeDoubleEncoding_(encoded);\n }\n return encoded;\n }\n return null;\n};\n\n\n/**\n * Converts a character in [\\01-\\177] to its unicode character equivalent.\n * @param {string} ch One character string.\n * @return {string} Encoded string.\n * @private\n */\ngoog.Uri.encodeChar_ = function(ch) {\n 'use strict';\n var n = ch.charCodeAt(0);\n return '%' + ((n >> 4) & 0xf).toString(16) + (n & 0xf).toString(16);\n};\n\n\n/**\n * Removes double percent-encoding from a string.\n * @param {string} doubleEncodedString String\n * @return {string} String with double encoding removed.\n * @private\n */\ngoog.Uri.removeDoubleEncoding_ = function(doubleEncodedString) {\n 'use strict';\n return doubleEncodedString.replace(/%25([0-9a-fA-F]{2})/g, '%$1');\n};\n\n\n/**\n * Regular expression for characters that are disallowed in the scheme or\n * userInfo part of the URI.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInSchemeOrUserInfo_ = /[#\\/\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in a relative path.\n * Colon is included due to RFC 3986 3.3.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInRelativePath_ = /[\\#\\?:]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in an absolute path.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInAbsolutePath_ = /[\\#\\?]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the query.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInQuery_ = /[\\#\\?@]/g;\n\n\n/**\n * Regular expression for characters that are disallowed in the fragment.\n * @type {RegExp}\n * @private\n */\ngoog.Uri.reDisallowedInFragment_ = /#/g;\n\n\n/**\n * Checks whether two URIs have the same domain.\n * @param {string} uri1String First URI string.\n * @param {string} uri2String Second URI string.\n * @return {boolean} true if the two URIs have the same domain; false otherwise.\n */\ngoog.Uri.haveSameDomain = function(uri1String, uri2String) {\n 'use strict';\n // Differs from goog.uri.utils.haveSameDomain, since this ignores scheme.\n // TODO(gboyer): Have this just call goog.uri.util.haveSameDomain.\n var pieces1 = goog.uri.utils.split(uri1String);\n var pieces2 = goog.uri.utils.split(uri2String);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n\n/**\n * Class used to represent URI query parameters. It is essentially a hash of\n * name-value pairs, though a name can be present more than once.\n *\n * Has the same interface as the collections in goog.structs.\n *\n * @param {?string=} opt_query Optional encoded query string to parse into\n * the object.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @constructor\n * @struct\n * @final\n */\ngoog.Uri.QueryData = function(opt_query, opt_ignoreCase) {\n 'use strict';\n /**\n * The map containing name/value or name/array-of-values pairs.\n * May be null if it requires parsing from the query string.\n *\n * We need to use a Map because we cannot guarantee that the key names will\n * not be problematic for IE.\n *\n * @private {?Map<string, !Array<*>>}\n */\n this.keyMap_ = null;\n\n /**\n * The number of params, or null if it requires computing.\n * @private {?number}\n */\n this.count_ = null;\n\n /**\n * Encoded query string, or null if it requires computing from the key map.\n * @private {?string}\n */\n this.encodedQuery_ = opt_query || null;\n\n /**\n * If true, ignore the case of the parameter name in #get.\n * @private {boolean}\n */\n this.ignoreCase_ = !!opt_ignoreCase;\n};\n\n\n/**\n * If the underlying key map is not yet initialized, it parses the\n * query string and fills the map with parsed data.\n * @private\n */\ngoog.Uri.QueryData.prototype.ensureKeyMapInitialized_ = function() {\n 'use strict';\n if (!this.keyMap_) {\n this.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map());\n this.count_ = 0;\n if (this.encodedQuery_) {\n var self = this;\n goog.uri.utils.parseQueryData(this.encodedQuery_, function(name, value) {\n 'use strict';\n self.add(goog.string.urlDecode(name), value);\n });\n }\n }\n};\n\n\n/**\n * Creates a new query data instance from a map of names and values.\n *\n * @param {!goog.collections.maps.MapLike<string, ?>|!Object} map Map of string\n * parameter names to parameter value. If parameter value is an array, it is\n * treated as if the key maps to each individual value in the\n * array.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromMap = function(map, opt_ignoreCase) {\n 'use strict';\n var keys = goog.structs.getKeys(map);\n if (typeof keys == 'undefined') {\n throw new Error('Keys are undefined');\n }\n\n var queryData = new goog.Uri.QueryData(null, opt_ignoreCase);\n var values = goog.structs.getValues(map);\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n var value = values[i];\n if (!Array.isArray(value)) {\n queryData.add(key, value);\n } else {\n queryData.setValues(key, value);\n }\n }\n return queryData;\n};\n\n\n/**\n * Creates a new query data instance from parallel arrays of parameter names\n * and values. Allows for duplicate parameter names. Throws an error if the\n * lengths of the arrays differ.\n *\n * @param {!Array<string>} keys Parameter names.\n * @param {!Array<?>} values Parameter values.\n * @param {boolean=} opt_ignoreCase If true, ignore the case of the parameter\n * name in #get.\n * @return {!goog.Uri.QueryData} The populated query data instance.\n */\ngoog.Uri.QueryData.createFromKeysValues = function(\n keys, values, opt_ignoreCase) {\n 'use strict';\n if (keys.length != values.length) {\n throw new Error('Mismatched lengths for keys/values');\n }\n var queryData = new goog.Uri.QueryData(null, opt_ignoreCase);\n for (var i = 0; i < keys.length; i++) {\n queryData.add(keys[i], values[i]);\n }\n return queryData;\n};\n\n\n/**\n * @return {?number} The number of parameters.\n */\ngoog.Uri.QueryData.prototype.getCount = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n return this.count_;\n};\n\n\n/**\n * Adds a key value pair.\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.add = function(key, value) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n key = this.getKeyName_(key);\n var values = this.keyMap_.get(key);\n if (!values) {\n this.keyMap_.set(key, (values = []));\n }\n values.push(value);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Removes all the params with the given key.\n * @param {string} key Name.\n * @return {boolean} Whether any parameter was removed.\n */\ngoog.Uri.QueryData.prototype.remove = function(key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n\n key = this.getKeyName_(key);\n if (this.keyMap_.has(key)) {\n this.invalidateCache_();\n\n // Decrement parameter count.\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n return this.keyMap_.delete(key);\n }\n return false;\n};\n\n\n/**\n * Clears the parameters.\n */\ngoog.Uri.QueryData.prototype.clear = function() {\n 'use strict';\n this.invalidateCache_();\n this.keyMap_ = null;\n this.count_ = 0;\n};\n\n\n/**\n * @return {boolean} Whether we have any parameters.\n */\ngoog.Uri.QueryData.prototype.isEmpty = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n return this.count_ == 0;\n};\n\n\n/**\n * Whether there is a parameter with the given name\n * @param {string} key The parameter name to check for.\n * @return {boolean} Whether there is a parameter with the given name.\n */\ngoog.Uri.QueryData.prototype.containsKey = function(key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n key = this.getKeyName_(key);\n return this.keyMap_.has(key);\n};\n\n\n/**\n * Whether there is a parameter with the given value.\n * @param {*} value The value to check for.\n * @return {boolean} Whether there is a parameter with the given value.\n */\ngoog.Uri.QueryData.prototype.containsValue = function(value) {\n 'use strict';\n // NOTE(arv): This solution goes through all the params even if it was the\n // first param. We can get around this by not reusing code or by switching to\n // iterators.\n var vals = this.getValues();\n return goog.array.contains(vals, value);\n};\n\n\n/**\n * Runs a callback on every key-value pair in the map, including duplicate keys.\n * This won't maintain original order when duplicate keys are interspersed (like\n * getKeys() / getValues()).\n * @param {function(this:SCOPE, ?, string, !goog.Uri.QueryData)} f\n * @param {SCOPE=} opt_scope The value of \"this\" inside f.\n * @template SCOPE\n */\ngoog.Uri.QueryData.prototype.forEach = function(f, opt_scope) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(values, key) {\n 'use strict';\n values.forEach(function(value) {\n 'use strict';\n f.call(opt_scope, value, key, this);\n }, this);\n }, this);\n};\n\n\n/**\n * Returns all the keys of the parameters. If a key is used multiple times\n * it will be included multiple times in the returned array\n * @return {!Array<string>} All the keys of the parameters.\n */\ngoog.Uri.QueryData.prototype.getKeys = function() {\n 'use strict';\n this.ensureKeyMapInitialized_();\n // We need to get the values to know how many keys to add.\n const vals = Array.from(this.keyMap_.values());\n const keys = Array.from(this.keyMap_.keys());\n const rv = [];\n for (let i = 0; i < keys.length; i++) {\n const val = vals[i];\n for (let j = 0; j < val.length; j++) {\n rv.push(keys[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Returns all the values of the parameters with the given name. If the query\n * data has no such key this will return an empty array. If no key is given\n * all values wil be returned.\n * @param {string=} opt_key The name of the parameter to get the values for.\n * @return {!Array<?>} All the values of the parameters with the given name.\n */\ngoog.Uri.QueryData.prototype.getValues = function(opt_key) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n let rv = [];\n if (typeof opt_key === 'string') {\n if (this.containsKey(opt_key)) {\n rv = rv.concat(this.keyMap_.get(this.getKeyName_(opt_key)));\n }\n } else {\n // Return all values.\n const values = Array.from(this.keyMap_.values());\n for (let i = 0; i < values.length; i++) {\n rv = rv.concat(values[i]);\n }\n }\n return rv;\n};\n\n\n/**\n * Sets a key value pair and removes all other keys with the same value.\n *\n * @param {string} key Name.\n * @param {*} value Value.\n * @return {!goog.Uri.QueryData} Instance of this object.\n */\ngoog.Uri.QueryData.prototype.set = function(key, value) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n\n // TODO(chrishenry): This could be better written as\n // this.remove(key), this.add(key, value), but that would reorder\n // the key (since the key is first removed and then added at the\n // end) and we would have to fix unit tests that depend on key\n // ordering.\n key = this.getKeyName_(key);\n if (this.containsKey(key)) {\n this.count_ =\n goog.asserts.assertNumber(this.count_) - this.keyMap_.get(key).length;\n }\n this.keyMap_.set(key, [value]);\n this.count_ = goog.asserts.assertNumber(this.count_) + 1;\n return this;\n};\n\n\n/**\n * Returns the first value associated with the key. If the query data has no\n * such key this will return undefined or the optional default.\n * @param {string} key The name of the parameter to get the value for.\n * @param {*=} opt_default The default value to return if the query data\n * has no such key.\n * @return {*} The first string value associated with the key, or opt_default\n * if there's no value.\n */\ngoog.Uri.QueryData.prototype.get = function(key, opt_default) {\n 'use strict';\n if (!key) {\n return opt_default;\n }\n var values = this.getValues(key);\n return values.length > 0 ? String(values[0]) : opt_default;\n};\n\n\n/**\n * Sets the values for a key. If the key already exists, this will\n * override all of the existing values that correspond to the key.\n * @param {string} key The key to set values for.\n * @param {!Array<?>} values The values to set.\n */\ngoog.Uri.QueryData.prototype.setValues = function(key, values) {\n 'use strict';\n this.remove(key);\n\n if (values.length > 0) {\n this.invalidateCache_();\n this.keyMap_.set(this.getKeyName_(key), goog.array.clone(values));\n this.count_ = goog.asserts.assertNumber(this.count_) + values.length;\n }\n};\n\n\n/**\n * @return {string} Encoded query string.\n * @override\n */\ngoog.Uri.QueryData.prototype.toString = function() {\n 'use strict';\n if (this.encodedQuery_) {\n return this.encodedQuery_;\n }\n\n if (!this.keyMap_) {\n return '';\n }\n\n const sb = [];\n\n // In the past, we use this.getKeys() and this.getVals(), but that\n // generates a lot of allocations as compared to simply iterating\n // over the keys.\n const keys = Array.from(this.keyMap_.keys());\n for (var i = 0; i < keys.length; i++) {\n const key = keys[i];\n const encodedKey = goog.string.urlEncode(key);\n const val = this.getValues(key);\n for (var j = 0; j < val.length; j++) {\n var param = encodedKey;\n // Ensure that null and undefined are encoded into the url as\n // literal strings.\n if (val[j] !== '') {\n param += '=' + goog.string.urlEncode(val[j]);\n }\n sb.push(param);\n }\n }\n\n return this.encodedQuery_ = sb.join('&');\n};\n\n\n/**\n * @throws URIError If URI is malformed (that is, if decodeURIComponent fails on\n * any of the URI components).\n * @return {string} Decoded query string.\n */\ngoog.Uri.QueryData.prototype.toDecodedString = function() {\n 'use strict';\n return goog.Uri.decodeOrEmpty_(this.toString());\n};\n\n\n/**\n * Invalidate the cache.\n * @private\n */\ngoog.Uri.QueryData.prototype.invalidateCache_ = function() {\n 'use strict';\n this.encodedQuery_ = null;\n};\n\n\n/**\n * Removes all keys that are not in the provided list. (Modifies this object.)\n * @param {Array<string>} keys The desired keys.\n * @return {!goog.Uri.QueryData} a reference to this object.\n */\ngoog.Uri.QueryData.prototype.filterKeys = function(keys) {\n 'use strict';\n this.ensureKeyMapInitialized_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\n if (!goog.array.contains(keys, key)) {\n this.remove(key);\n }\n }, this);\n return this;\n};\n\n\n/**\n * Clone the query data instance.\n * @return {!goog.Uri.QueryData} New instance of the QueryData object.\n */\ngoog.Uri.QueryData.prototype.clone = function() {\n 'use strict';\n var rv = new goog.Uri.QueryData();\n rv.encodedQuery_ = this.encodedQuery_;\n if (this.keyMap_) {\n rv.keyMap_ = /** @type {!Map<string, !Array<*>>} */ (new Map(this.keyMap_));\n rv.count_ = this.count_;\n }\n return rv;\n};\n\n\n/**\n * Helper function to get the key name from a JavaScript object. Converts\n * the object to a string, and to lower case if necessary.\n * @private\n * @param {*} arg The object to get a key name from.\n * @return {string} valid key name which can be looked up in #keyMap_.\n */\ngoog.Uri.QueryData.prototype.getKeyName_ = function(arg) {\n 'use strict';\n var keyName = String(arg);\n if (this.ignoreCase_) {\n keyName = keyName.toLowerCase();\n }\n return keyName;\n};\n\n\n/**\n * Ignore case in parameter names.\n * NOTE: If there are already key/value pairs in the QueryData, and\n * ignoreCase_ is set to false, the keys will all be lower-cased.\n * @param {boolean} ignoreCase whether this goog.Uri should ignore case.\n */\ngoog.Uri.QueryData.prototype.setIgnoreCase = function(ignoreCase) {\n 'use strict';\n var resetKeys = ignoreCase && !this.ignoreCase_;\n if (resetKeys) {\n this.ensureKeyMapInitialized_();\n this.invalidateCache_();\n this.keyMap_.forEach(function(value, key) {\n 'use strict';\n var lowerCase = key.toLowerCase();\n if (key != lowerCase) {\n this.remove(key);\n this.setValues(lowerCase, value);\n }\n }, this);\n }\n this.ignoreCase_ = ignoreCase;\n};\n\n\n/**\n * Extends a query data object with another query data or map like object. This\n * operates 'in-place', it does not create a new QueryData object.\n *\n * @param {...(?goog.Uri.QueryData|?goog.collections.maps.MapLike<?,\n * ?>|?Object)} var_args The object from which key value pairs will be\n * copied. Note: does not accept null.\n * @suppress {deprecated} Use deprecated goog.structs.forEach to allow different\n * types of parameters.\n */\ngoog.Uri.QueryData.prototype.extend = function(var_args) {\n 'use strict';\n for (var i = 0; i < arguments.length; i++) {\n var data = arguments[i];\n goog.structs.forEach(data, function(value, key) {\n 'use strict';\n this.add(key, value);\n }, this);\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview The dispose method is used to clean up references and\n * resources.\n */\n\ngoog.module('goog.dispose');\ngoog.module.declareLegacyNamespace();\n\n/**\n * Calls `dispose` on the argument if it supports it. If obj is not an\n * object with a dispose() method, this is a no-op.\n * @param {*} obj The object to dispose of.\n */\nfunction dispose(obj) {\n if (obj && typeof obj.dispose == 'function') {\n obj.dispose();\n }\n}\nexports = dispose;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Codec functions of the v8 wire protocol. Eventually we'd want\n * to support pluggable wire-format to improve wire efficiency and to enable\n * binary encoding. Such support will require an interface class, which\n * will be added later.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.WireV8');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.json');\ngoog.require('goog.json.NativeJsonProcessor');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.structs');\ngoog.requireType('goog.string.Parser');\n\n\n\n/**\n * The v8 codec class.\n *\n * @constructor\n * @struct\n */\ngoog.labs.net.webChannel.WireV8 = function() {\n 'use strict';\n /**\n * Parser for a response payload. The parser should return an array.\n * @private {!goog.string.Parser}\n */\n this.parser_ = new goog.json.NativeJsonProcessor();\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WireV8 = goog.labs.net.webChannel.WireV8;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * Encodes a standalone message into the wire format.\n *\n * May throw exception if the message object contains any invalid elements.\n *\n * @param {!Object|!goog.collections.maps.MapLike} message The message data.\n * V8 only support JS objects (or Map).\n * @param {!Array<string>} buffer The text buffer to write the message to.\n * @param {string=} opt_prefix The prefix for each field of the object.\n */\nWireV8.prototype.encodeMessage = function(message, buffer, opt_prefix) {\n 'use strict';\n const prefix = opt_prefix || '';\n try {\n goog.structs.forEach(message, function(value, key) {\n 'use strict';\n let encodedValue = value;\n if (goog.isObject(value)) {\n encodedValue = goog.json.serialize(value);\n } // keep the fast-path for primitive types\n buffer.push(prefix + key + '=' + encodeURIComponent(encodedValue));\n });\n } catch (ex) {\n // We send a map here because lots of the retry logic relies on map IDs,\n // so we have to send something (possibly redundant).\n buffer.push(\n prefix + 'type' +\n '=' + encodeURIComponent('_badmap'));\n throw ex;\n }\n};\n\n\n/**\n * Encodes all the buffered messages of the forward channel.\n *\n * @param {!Array<Wire.QueuedMap>} messageQueue The message data.\n * V8 only support JS objects.\n * @param {number} count The number of messages to be encoded.\n * @param {?function(!Object)} badMapHandler Callback for bad messages.\n * @return {string} the encoded messages\n */\nWireV8.prototype.encodeMessageQueue = function(\n messageQueue, count, badMapHandler) {\n 'use strict';\n let offset = -1;\n while (true) {\n const sb = ['count=' + count];\n // To save a bit of bandwidth, specify the base mapId and the rest as\n // offsets from it.\n if (offset == -1) {\n if (count > 0) {\n offset = messageQueue[0].mapId;\n sb.push('ofs=' + offset);\n } else {\n offset = 0;\n }\n } else {\n sb.push('ofs=' + offset);\n }\n let done = true;\n for (let i = 0; i < count; i++) {\n let mapId = messageQueue[i].mapId;\n const map = messageQueue[i].map;\n mapId -= offset;\n if (mapId < 0) {\n // redo the encoding in case of retry/reordering, plus extra space\n offset = Math.max(0, messageQueue[i].mapId - 100);\n done = false;\n continue;\n }\n try {\n this.encodeMessage(map, sb, 'req' + mapId + '_');\n } catch (ex) {\n if (badMapHandler) {\n badMapHandler(map);\n }\n }\n }\n if (done) {\n return sb.join('&');\n }\n }\n};\n\n\n/**\n * Decodes a standalone message received from the wire. May throw exception\n * if text is ill-formatted.\n *\n * Must be valid JSON as it is insecure to use eval() to decode JS literals;\n * and eval() is disallowed in Chrome apps too.\n *\n * Invalid JS literals include null array elements, quotas etc.\n *\n * @param {string} messageText The string content as received from the wire.\n * @return {*} The decoded message object.\n */\nWireV8.prototype.decodeMessage = function(messageText) {\n 'use strict';\n const response = this.parser_.parse(messageText);\n goog.asserts.assert(Array.isArray(response)); // throw exception\n return response;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for string manipulation.\n */\n\n\n/**\n * Namespace for string utilities\n */\ngoog.provide('goog.string');\ngoog.provide('goog.string.Unicode');\n\ngoog.require('goog.dom.safe');\ngoog.require('goog.html.uncheckedconversions');\ngoog.require('goog.string.Const');\ngoog.require('goog.string.internal');\n\n\n/**\n * @define {boolean} Enables HTML escaping of lowercase letter \"e\" which helps\n * with detection of double-escaping as this letter is frequently used.\n */\ngoog.string.DETECT_DOUBLE_ESCAPING =\n goog.define('goog.string.DETECT_DOUBLE_ESCAPING', false);\n\n\n/**\n * @define {boolean} Whether to force non-dom html unescaping.\n */\ngoog.string.FORCE_NON_DOM_HTML_UNESCAPING =\n goog.define('goog.string.FORCE_NON_DOM_HTML_UNESCAPING', false);\n\n\n/**\n * Common Unicode string characters.\n * @enum {string}\n */\ngoog.string.Unicode = {\n NBSP: '\\xa0'\n};\n\n\n/**\n * Fast prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the start of `str`.\n * @return {boolean} True if `str` begins with `prefix`.\n */\ngoog.string.startsWith = goog.string.internal.startsWith;\n\n\n/**\n * Fast suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix`.\n */\ngoog.string.endsWith = goog.string.internal.endsWith;\n\n\n/**\n * Case-insensitive prefix-checker.\n * @param {string} str The string to check.\n * @param {string} prefix A string to look for at the end of `str`.\n * @return {boolean} True if `str` begins with `prefix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveStartsWith =\n goog.string.internal.caseInsensitiveStartsWith;\n\n\n/**\n * Case-insensitive suffix-checker.\n * @param {string} str The string to check.\n * @param {string} suffix A string to look for at the end of `str`.\n * @return {boolean} True if `str` ends with `suffix` (ignoring\n * case).\n */\ngoog.string.caseInsensitiveEndsWith =\n goog.string.internal.caseInsensitiveEndsWith;\n\n\n/**\n * Case-insensitive equality checker.\n * @param {string} str1 First string to check.\n * @param {string} str2 Second string to check.\n * @return {boolean} True if `str1` and `str2` are the same string,\n * ignoring case.\n */\ngoog.string.caseInsensitiveEquals = goog.string.internal.caseInsensitiveEquals;\n\n\n/**\n * Does simple python-style string substitution.\n * subs(\"foo%s hot%s\", \"bar\", \"dog\") becomes \"foobar hotdog\".\n * @param {string} str The string containing the pattern.\n * @param {...*} var_args The items to substitute into the pattern.\n * @return {string} A copy of `str` in which each occurrence of\n * {@code %s} has been replaced an argument from `var_args`.\n */\ngoog.string.subs = function(str, var_args) {\n 'use strict';\n const splitParts = str.split('%s');\n let returnString = '';\n\n const subsArguments = Array.prototype.slice.call(arguments, 1);\n while (subsArguments.length &&\n // Replace up to the last split part. We are inserting in the\n // positions between split parts.\n splitParts.length > 1) {\n returnString += splitParts.shift() + subsArguments.shift();\n }\n\n return returnString + splitParts.join('%s'); // Join unused '%s'\n};\n\n\n/**\n * Converts multiple whitespace chars (spaces, non-breaking-spaces, new lines\n * and tabs) to a single space, and strips leading and trailing whitespace.\n * @param {string} str Input string.\n * @return {string} A copy of `str` with collapsed whitespace.\n */\ngoog.string.collapseWhitespace = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+/g, ' ').replace(/^\\s+|\\s+$/g, '');\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n */\ngoog.string.isEmptyOrWhitespace = goog.string.internal.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is empty.\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty.\n */\ngoog.string.isEmptyString = function(str) {\n 'use strict';\n return str.length == 0;\n};\n\n\n/**\n * Checks if a string is empty or contains only whitespaces.\n *\n * @param {string} str The string to check.\n * @return {boolean} Whether `str` is empty or whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmpty = goog.string.isEmptyOrWhitespace;\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str))\n * instead.\n */\ngoog.string.isEmptyOrWhitespaceSafe = function(str) {\n 'use strict';\n return goog.string.isEmptyOrWhitespace(goog.string.makeSafe(str));\n};\n\n\n/**\n * Checks if a string is null, undefined, empty or contains only whitespaces.\n *\n * @param {*} str The string to check.\n * @return {boolean} Whether `str` is null, undefined, empty, or\n * whitespace only.\n * @deprecated Use goog.string.isEmptyOrWhitespace instead.\n */\ngoog.string.isEmptySafe = goog.string.isEmptyOrWhitespaceSafe;\n\n\n/**\n * Checks if a string is all breaking whitespace.\n * @param {string} str The string to check.\n * @return {boolean} Whether the string is all breaking whitespace.\n */\ngoog.string.isBreakingWhitespace = function(str) {\n 'use strict';\n return !/[^\\t\\n\\r ]/.test(str);\n};\n\n\n/**\n * Checks if a string contains all letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` consists entirely of letters.\n */\ngoog.string.isAlpha = function(str) {\n 'use strict';\n return !/[^a-zA-Z]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers.\n * @param {*} str string to check. If not a string, it will be\n * casted to one.\n * @return {boolean} True if `str` is numeric.\n */\ngoog.string.isNumeric = function(str) {\n 'use strict';\n return !/[^0-9]/.test(str);\n};\n\n\n/**\n * Checks if a string contains only numbers or letters.\n * @param {string} str string to check.\n * @return {boolean} True if `str` is alphanumeric.\n */\ngoog.string.isAlphaNumeric = function(str) {\n 'use strict';\n return !/[^a-zA-Z0-9]/.test(str);\n};\n\n\n/**\n * Checks if a character is a space character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a space.\n */\ngoog.string.isSpace = function(ch) {\n 'use strict';\n return ch == ' ';\n};\n\n\n/**\n * Checks if a character is a valid unicode character.\n * @param {string} ch Character to check.\n * @return {boolean} True if `ch` is a valid unicode character.\n */\ngoog.string.isUnicodeChar = function(ch) {\n 'use strict';\n return ch.length == 1 && ch >= ' ' && ch <= '~' ||\n ch >= '\\u0080' && ch <= '\\uFFFD';\n};\n\n\n/**\n * Takes a string and replaces newlines with a space. Multiple lines are\n * replaced with a single space.\n * @param {string} str The string from which to strip newlines.\n * @return {string} A copy of `str` stripped of newlines.\n */\ngoog.string.stripNewlines = function(str) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)+/g, ' ');\n};\n\n\n/**\n * Replaces Windows and Mac new lines with unix style: \\r or \\r\\n with \\n.\n * @param {string} str The string to in which to canonicalize newlines.\n * @return {string} `str` A copy of {@code} with canonicalized newlines.\n */\ngoog.string.canonicalizeNewlines = function(str) {\n 'use strict';\n return str.replace(/(\\r\\n|\\r|\\n)/g, '\\n');\n};\n\n\n/**\n * Normalizes whitespace in a string, replacing all whitespace chars with\n * a space.\n * @param {string} str The string in which to normalize whitespace.\n * @return {string} A copy of `str` with all whitespace normalized.\n */\ngoog.string.normalizeWhitespace = function(str) {\n 'use strict';\n return str.replace(/\\xa0|\\s/g, ' ');\n};\n\n\n/**\n * Normalizes spaces in a string, replacing all consecutive spaces and tabs\n * with a single space. Replaces non-breaking space with a space.\n * @param {string} str The string in which to normalize spaces.\n * @return {string} A copy of `str` with all consecutive spaces and tabs\n * replaced with a single space.\n */\ngoog.string.normalizeSpaces = function(str) {\n 'use strict';\n return str.replace(/\\xa0|[ \\t]+/g, ' ');\n};\n\n\n/**\n * Removes the breaking spaces from the left and right of the string and\n * collapses the sequences of breaking spaces in the middle into single spaces.\n * The original and the result strings render the same way in HTML.\n * @param {string} str A string in which to collapse spaces.\n * @return {string} Copy of the string with normalized breaking spaces.\n */\ngoog.string.collapseBreakingSpaces = function(str) {\n 'use strict';\n return str.replace(/[\\t\\r\\n ]+/g, ' ')\n .replace(/^[\\t\\r\\n ]+|[\\t\\r\\n ]+$/g, '');\n};\n\n\n/**\n * Trims white spaces to the left and right of a string.\n * @param {string} str The string to trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trim = goog.string.internal.trim;\n\n\n/**\n * Trims whitespaces at the left end of a string.\n * @param {string} str The string to left trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimLeft = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/^[\\s\\xa0]+/, '');\n};\n\n\n/**\n * Trims whitespaces at the right end of a string.\n * @param {string} str The string to right trim.\n * @return {string} A trimmed copy of `str`.\n */\ngoog.string.trimRight = function(str) {\n 'use strict';\n // Since IE doesn't include non-breaking-space (0xa0) in their \\s character\n // class (as required by section 7.2 of the ECMAScript spec), we explicitly\n // include it in the regexp to enforce consistent cross-browser behavior.\n return str.replace(/[\\s\\xa0]+$/, '');\n};\n\n\n/**\n * A string comparator that ignores case.\n * -1 = str1 less than str2\n * 0 = str1 equals str2\n * 1 = str1 greater than str2\n *\n * @param {string} str1 The string to compare.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} The comparator result, as described above.\n */\ngoog.string.caseInsensitiveCompare =\n goog.string.internal.caseInsensitiveCompare;\n\n\n/**\n * Compares two strings interpreting their numeric substrings as numbers.\n *\n * @param {string} str1 First string.\n * @param {string} str2 Second string.\n * @param {!RegExp} tokenizerRegExp Splits a string into substrings of\n * non-negative integers, non-numeric characters and optionally fractional\n * numbers starting with a decimal point.\n * @return {number} Negative if str1 < str2, 0 is str1 == str2, positive if\n * str1 > str2.\n * @private\n */\ngoog.string.numberAwareCompare_ = function(str1, str2, tokenizerRegExp) {\n 'use strict';\n if (str1 == str2) {\n return 0;\n }\n if (!str1) {\n return -1;\n }\n if (!str2) {\n return 1;\n }\n\n // Using match to split the entire string ahead of time turns out to be faster\n // for most inputs than using RegExp.exec or iterating over each character.\n const tokens1 = str1.toLowerCase().match(tokenizerRegExp);\n const tokens2 = str2.toLowerCase().match(tokenizerRegExp);\n\n const count = Math.min(tokens1.length, tokens2.length);\n\n for (let i = 0; i < count; i++) {\n const a = tokens1[i];\n const b = tokens2[i];\n\n // Compare pairs of tokens, returning if one token sorts before the other.\n if (a != b) {\n // Only if both tokens are integers is a special comparison required.\n // Decimal numbers are sorted as strings (e.g., '.09' < '.1').\n const num1 = parseInt(a, 10);\n if (!isNaN(num1)) {\n const num2 = parseInt(b, 10);\n if (!isNaN(num2) && num1 - num2) {\n return num1 - num2;\n }\n }\n return a < b ? -1 : 1;\n }\n }\n\n // If one string is a substring of the other, the shorter string sorts first.\n if (tokens1.length != tokens2.length) {\n return tokens1.length - tokens2.length;\n }\n\n // The two strings must be equivalent except for case (perfect equality is\n // tested at the head of the function.) Revert to default ASCII string\n // comparison to stabilize the sort.\n return str1 < str2 ? -1 : 1;\n};\n\n\n/**\n * String comparison function that handles non-negative integer numbers in a\n * way humans might expect. Using this function, the string 'File 2.jpg' sorts\n * before 'File 10.jpg', and 'Version 1.9' before 'Version 1.10'. The comparison\n * is mostly case-insensitive, though strings that are identical except for case\n * are sorted with the upper-case strings before lower-case.\n *\n * This comparison function is up to 50x slower than either the default or the\n * case-insensitive compare. It should not be used in time-critical code, but\n * should be fast enough to sort several hundred short strings (like filenames)\n * with a reasonable delay.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.intAwareCompare = function(str1, str2) {\n 'use strict';\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\D+/g);\n};\n\n\n/**\n * String comparison function that handles non-negative integer and fractional\n * numbers in a way humans might expect. Using this function, the string\n * 'File 2.jpg' sorts before 'File 10.jpg', and '3.14' before '3.2'. Equivalent\n * to {@link goog.string.intAwareCompare} apart from the way how it interprets\n * dots.\n *\n * @param {string} str1 The string to compare in a numerically sensitive way.\n * @param {string} str2 The string to compare `str1` to.\n * @return {number} less than 0 if str1 < str2, 0 if str1 == str2, greater than\n * 0 if str1 > str2.\n */\ngoog.string.floatAwareCompare = function(str1, str2) {\n 'use strict';\n return goog.string.numberAwareCompare_(str1, str2, /\\d+|\\.\\d+|\\D+/g);\n};\n\n\n/**\n * Alias for {@link goog.string.floatAwareCompare}.\n *\n * @param {string} str1\n * @param {string} str2\n * @return {number}\n */\ngoog.string.numerateCompare = goog.string.floatAwareCompare;\n\n\n/**\n * URL-encodes a string\n * @param {*} str The string to url-encode.\n * @return {string} An encoded copy of `str` that is safe for urls.\n * Note that '#', ':', and other characters used to delimit portions\n * of URLs *will* be encoded.\n */\ngoog.string.urlEncode = function(str) {\n 'use strict';\n return encodeURIComponent(String(str));\n};\n\n\n/**\n * URL-decodes the string. We need to specially handle '+'s because\n * the javascript library doesn't convert them to spaces.\n * @param {string} str The string to url decode.\n * @return {string} The decoded `str`.\n */\ngoog.string.urlDecode = function(str) {\n 'use strict';\n return decodeURIComponent(str.replace(/\\+/g, ' '));\n};\n\n\n/**\n * Converts \\n to <br>s or <br />s.\n * @param {string} str The string in which to convert newlines.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} A copy of `str` with converted newlines.\n */\ngoog.string.newLineToBr = goog.string.internal.newLineToBr;\n\n\n/**\n * Escapes double quote '\"' and single quote '\\'' characters in addition to\n * '&', '<', and '>' so that a string can be included in an HTML tag attribute\n * value within double or single quotes.\n *\n * It should be noted that > doesn't need to be escaped for the HTML or XML to\n * be valid, but it has been decided to escape it for consistency with other\n * implementations.\n *\n * With goog.string.DETECT_DOUBLE_ESCAPING, this function escapes also the\n * lowercase letter \"e\".\n *\n * NOTE(user):\n * HtmlEscape is often called during the generation of large blocks of HTML.\n * Using statics for the regular expressions and strings is an optimization\n * that can more than half the amount of time IE spends in this function for\n * large apps, since strings and regexes both contribute to GC allocations.\n *\n * Testing for the presence of a character before escaping increases the number\n * of function calls, but actually provides a speed increase for the average\n * case -- since the average case often doesn't require the escaping of all 4\n * characters and indexOf() is much cheaper than replace().\n * The worst case does suffer slightly from the additional calls, therefore the\n * opt_isLikelyToContainHtmlChars option has been included for situations\n * where all 4 HTML entities are very likely to be present and need escaping.\n *\n * Some benchmarks (times tended to fluctuate +-0.05ms):\n * FireFox IE6\n * (no chars / average (mix of cases) / all 4 chars)\n * no checks 0.13 / 0.22 / 0.22 0.23 / 0.53 / 0.80\n * indexOf 0.08 / 0.17 / 0.26 0.22 / 0.54 / 0.84\n * indexOf + re test 0.07 / 0.17 / 0.28 0.19 / 0.50 / 0.85\n *\n * An additional advantage of checking if replace actually needs to be called\n * is a reduction in the number of object allocations, so as the size of the\n * application grows the difference between the various methods would increase.\n *\n * @param {string} str string to be escaped.\n * @param {boolean=} opt_isLikelyToContainHtmlChars Don't perform a check to see\n * if the character needs replacing - use this option if you expect each of\n * the characters to appear often. Leave false if you expect few html\n * characters to occur in your strings, such as if you are escaping HTML.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.htmlEscape = function(str, opt_isLikelyToContainHtmlChars) {\n 'use strict';\n str = goog.string.internal.htmlEscape(str, opt_isLikelyToContainHtmlChars);\n if (goog.string.DETECT_DOUBLE_ESCAPING) {\n str = str.replace(goog.string.E_RE_, '&#101;');\n }\n return str;\n};\n\n\n/**\n * Regular expression that matches a lowercase letter \"e\", for use in escaping.\n * @const {!RegExp}\n * @private\n */\ngoog.string.E_RE_ = /e/g;\n\n\n/**\n * Unescapes an HTML string.\n *\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntities = function(str) {\n 'use strict';\n if (goog.string.contains(str, '&')) {\n // We are careful not to use a DOM if we do not have one or we explicitly\n // requested non-DOM html unescaping.\n if (!goog.string.FORCE_NON_DOM_HTML_UNESCAPING &&\n 'document' in goog.global) {\n return goog.string.unescapeEntitiesUsingDom_(str);\n } else {\n // Fall back on pure XML entities\n return goog.string.unescapePureXmlEntities_(str);\n }\n }\n return str;\n};\n\n\n/**\n * Unescapes a HTML string using the provided document.\n *\n * @param {string} str The string to unescape.\n * @param {!Document} document A document to use in escaping the string.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapeEntitiesWithDocument = function(str, document) {\n 'use strict';\n if (goog.string.contains(str, '&')) {\n return goog.string.unescapeEntitiesUsingDom_(str, document);\n }\n return str;\n};\n\n\n/**\n * Unescapes an HTML string using a DOM to resolve non-XML, non-numeric\n * entities. This function is XSS-safe and whitespace-preserving.\n * @private\n * @param {string} str The string to unescape.\n * @param {Document=} opt_document An optional document to use for creating\n * elements. If this is not specified then the default window.document\n * will be used.\n * @return {string} The unescaped `str` string.\n */\ngoog.string.unescapeEntitiesUsingDom_ = function(str, opt_document) {\n 'use strict';\n /** @type {!Object<string, string>} */\n const seen = {'&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '\"'};\n /** @type {!Element} */\n let div;\n if (opt_document) {\n div = opt_document.createElement('div');\n } else {\n div = goog.global.document.createElement('div');\n }\n // Match as many valid entity characters as possible. If the actual entity\n // happens to be shorter, it will still work as innerHTML will return the\n // trailing characters unchanged. Since the entity characters do not include\n // open angle bracket, there is no chance of XSS from the innerHTML use.\n // Since no whitespace is passed to innerHTML, whitespace is preserved.\n return str.replace(goog.string.HTML_ENTITY_PATTERN_, function(s, entity) {\n 'use strict';\n // Check for cached entity.\n let value = seen[s];\n if (value) {\n return value;\n }\n // Check for numeric entity.\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex numbers.\n const n = Number('0' + entity.substr(1));\n if (!isNaN(n)) {\n value = String.fromCharCode(n);\n }\n }\n // Fall back to innerHTML otherwise.\n if (!value) {\n // Append a non-entity character to avoid a bug in Webkit that parses\n // an invalid entity at the end of innerHTML text as the empty string.\n goog.dom.safe.setInnerHtml(\n div,\n goog.html.uncheckedconversions\n .safeHtmlFromStringKnownToSatisfyTypeContract(\n goog.string.Const.from('Single HTML entity.'), s + ' '));\n // Then remove the trailing character from the result.\n value = div.firstChild.nodeValue.slice(0, -1);\n }\n // Cache and return.\n return seen[s] = value;\n });\n};\n\n\n/**\n * Unescapes XML entities.\n * @private\n * @param {string} str The string to unescape.\n * @return {string} An unescaped copy of `str`.\n */\ngoog.string.unescapePureXmlEntities_ = function(str) {\n 'use strict';\n return str.replace(/&([^;]+);/g, function(s, entity) {\n 'use strict';\n switch (entity) {\n case 'amp':\n return '&';\n case 'lt':\n return '<';\n case 'gt':\n return '>';\n case 'quot':\n return '\"';\n default:\n if (entity.charAt(0) == '#') {\n // Prefix with 0 so that hex entities (e.g. &#x10) parse as hex.\n const n = Number('0' + entity.substr(1));\n if (!isNaN(n)) {\n return String.fromCharCode(n);\n }\n }\n // For invalid entities we just return the entity\n return s;\n }\n });\n};\n\n\n/**\n * Regular expression that matches an HTML entity.\n * See also HTML5: Tokenization / Tokenizing character references.\n * @private\n * @type {!RegExp}\n */\ngoog.string.HTML_ENTITY_PATTERN_ = /&([^;\\s<&]+);?/g;\n\n\n/**\n * Do escaping of whitespace to preserve spatial formatting. We use character\n * entity #160 to make it safer for xml.\n * @param {string} str The string in which to escape whitespace.\n * @param {boolean=} opt_xml Whether to use XML compatible tags.\n * @return {string} An escaped copy of `str`.\n */\ngoog.string.whitespaceEscape = function(str, opt_xml) {\n 'use strict';\n // This doesn't use goog.string.preserveSpaces for backwards compatibility.\n return goog.string.newLineToBr(str.replace(/ /g, ' &#160;'), opt_xml);\n};\n\n\n/**\n * Preserve spaces that would be otherwise collapsed in HTML by replacing them\n * with non-breaking space Unicode characters.\n * @param {string} str The string in which to preserve whitespace.\n * @return {string} A copy of `str` with preserved whitespace.\n */\ngoog.string.preserveSpaces = function(str) {\n 'use strict';\n return str.replace(/(^|[\\n ]) /g, '$1' + goog.string.Unicode.NBSP);\n};\n\n\n/**\n * Strip quote characters around a string. The second argument is a string of\n * characters to treat as quotes. This can be a single character or a string of\n * multiple character and in that case each of those are treated as possible\n * quote characters. For example:\n *\n * <pre>\n * goog.string.stripQuotes('\"abc\"', '\"`') --> 'abc'\n * goog.string.stripQuotes('`abc`', '\"`') --> 'abc'\n * </pre>\n *\n * @param {string} str The string to strip.\n * @param {string} quoteChars The quote characters to strip.\n * @return {string} A copy of `str` without the quotes.\n */\ngoog.string.stripQuotes = function(str, quoteChars) {\n 'use strict';\n const length = quoteChars.length;\n for (let i = 0; i < length; i++) {\n const quoteChar = length == 1 ? quoteChars : quoteChars.charAt(i);\n if (str.charAt(0) == quoteChar && str.charAt(str.length - 1) == quoteChar) {\n return str.substring(1, str.length - 1);\n }\n }\n return str;\n};\n\n\n/**\n * Truncates a string to a certain length and adds '...' if necessary. The\n * length also accounts for the ellipsis, so a maximum length of 10 and a string\n * 'Hello World!' produces 'Hello W...'.\n * @param {string} str The string to truncate.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cut off in the middle.\n * @return {string} The truncated `str` string.\n */\ngoog.string.truncate = function(str, chars, opt_protectEscapedCharacters) {\n 'use strict';\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (str.length > chars) {\n str = str.substring(0, chars - 3) + '...';\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Truncate a string in the middle, adding \"...\" if necessary,\n * and favoring the beginning of the string.\n * @param {string} str The string to truncate the middle of.\n * @param {number} chars Max number of characters.\n * @param {boolean=} opt_protectEscapedCharacters Whether to protect escaped\n * characters from being cutoff in the middle.\n * @param {number=} opt_trailingChars Optional number of trailing characters to\n * leave at the end of the string, instead of truncating as close to the\n * middle as possible.\n * @return {string} A truncated copy of `str`.\n */\ngoog.string.truncateMiddle = function(\n str, chars, opt_protectEscapedCharacters, opt_trailingChars) {\n 'use strict';\n if (opt_protectEscapedCharacters) {\n str = goog.string.unescapeEntities(str);\n }\n\n if (opt_trailingChars && str.length > chars) {\n if (opt_trailingChars > chars) {\n opt_trailingChars = chars;\n }\n const endPoint = str.length - opt_trailingChars;\n const startPoint = chars - opt_trailingChars;\n str = str.substring(0, startPoint) + '...' + str.substring(endPoint);\n } else if (str.length > chars) {\n // Favor the beginning of the string:\n let half = Math.floor(chars / 2);\n const endPos = str.length - half;\n half += chars % 2;\n str = str.substring(0, half) + '...' + str.substring(endPos);\n }\n\n if (opt_protectEscapedCharacters) {\n str = goog.string.htmlEscape(str);\n }\n\n return str;\n};\n\n\n/**\n * Special chars that need to be escaped for goog.string.quote.\n * @private {!Object<string, string>}\n */\ngoog.string.specialEscapeChars_ = {\n '\\0': '\\\\0',\n '\\b': '\\\\b',\n '\\f': '\\\\f',\n '\\n': '\\\\n',\n '\\r': '\\\\r',\n '\\t': '\\\\t',\n '\\x0B': '\\\\x0B', // '\\v' is not supported in JScript\n '\"': '\\\\\"',\n '\\\\': '\\\\\\\\',\n // To support the use case of embedding quoted strings inside of script\n // tags, we have to make sure HTML comments and opening/closing script tags do\n // not appear in the resulting string. The specific strings that must be\n // escaped are documented at:\n // https://html.spec.whatwg.org/multipage/scripting.html#restrictions-for-contents-of-script-elements\n '<': '\\\\u003C' // NOTE: JSON.parse crashes on '\\\\x3c'.\n};\n\n\n/**\n * Character mappings used internally for goog.string.escapeChar.\n * @private {!Object<string, string>}\n */\ngoog.string.jsEscapeCache_ = {\n '\\'': '\\\\\\''\n};\n\n\n/**\n * Encloses a string in double quotes and escapes characters so that the\n * string is a valid JS string. The resulting string is safe to embed in\n * `<script>` tags as \"<\" is escaped.\n * @param {string} s The string to quote.\n * @return {string} A copy of `s` surrounded by double quotes.\n */\ngoog.string.quote = function(s) {\n 'use strict';\n s = String(s);\n const sb = ['\"'];\n for (let i = 0; i < s.length; i++) {\n const ch = s.charAt(i);\n const cc = ch.charCodeAt(0);\n sb[i + 1] = goog.string.specialEscapeChars_[ch] ||\n ((cc > 31 && cc < 127) ? ch : goog.string.escapeChar(ch));\n }\n sb.push('\"');\n return sb.join('');\n};\n\n\n/**\n * Takes a string and returns the escaped string for that input string.\n * @param {string} str The string to escape.\n * @return {string} An escaped string representing `str`.\n */\ngoog.string.escapeString = function(str) {\n 'use strict';\n const sb = [];\n for (let i = 0; i < str.length; i++) {\n sb[i] = goog.string.escapeChar(str.charAt(i));\n }\n return sb.join('');\n};\n\n\n/**\n * Takes a character and returns the escaped string for that character. For\n * example escapeChar(String.fromCharCode(15)) -> \"\\\\x0E\".\n * @param {string} c The character to escape.\n * @return {string} An escaped string representing `c`.\n */\ngoog.string.escapeChar = function(c) {\n 'use strict';\n if (c in goog.string.jsEscapeCache_) {\n return goog.string.jsEscapeCache_[c];\n }\n\n if (c in goog.string.specialEscapeChars_) {\n return goog.string.jsEscapeCache_[c] = goog.string.specialEscapeChars_[c];\n }\n\n let rv = c;\n const cc = c.charCodeAt(0);\n if (cc > 31 && cc < 127) {\n rv = c;\n } else {\n // tab is 9 but handled above\n if (cc < 256) {\n rv = '\\\\x';\n if (cc < 16 || cc > 256) {\n rv += '0';\n }\n } else {\n rv = '\\\\u';\n if (cc < 4096) { // \\u1000\n rv += '0';\n }\n }\n rv += cc.toString(16).toUpperCase();\n }\n\n return goog.string.jsEscapeCache_[c] = rv;\n};\n\n\n/**\n * Determines whether a string contains a substring.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.contains = goog.string.internal.contains;\n\n\n/**\n * Determines whether a string contains a substring, ignoring case.\n * @param {string} str The string to search.\n * @param {string} subString The substring to search for.\n * @return {boolean} Whether `str` contains `subString`.\n */\ngoog.string.caseInsensitiveContains =\n goog.string.internal.caseInsensitiveContains;\n\n\n/**\n * Returns the non-overlapping occurrences of ss in s.\n * If either s or ss evalutes to false, then returns zero.\n * @param {string} s The string to look in.\n * @param {string} ss The string to look for.\n * @return {number} Number of occurrences of ss in s.\n */\ngoog.string.countOf = function(s, ss) {\n 'use strict';\n return s && ss ? s.split(ss).length - 1 : 0;\n};\n\n\n/**\n * Removes a substring of a specified length at a specific\n * index in a string.\n * @param {string} s The base string from which to remove.\n * @param {number} index The index at which to remove the substring.\n * @param {number} stringLength The length of the substring to remove.\n * @return {string} A copy of `s` with the substring removed or the full\n * string if nothing is removed or the input is invalid.\n */\ngoog.string.removeAt = function(s, index, stringLength) {\n 'use strict';\n let resultStr = s;\n // If the index is greater or equal to 0 then remove substring\n if (index >= 0 && index < s.length && stringLength > 0) {\n resultStr = s.substr(0, index) +\n s.substr(index + stringLength, s.length - index - stringLength);\n }\n return resultStr;\n};\n\n\n/**\n * Removes the first occurrence of a substring from a string.\n * @param {string} str The base string from which to remove.\n * @param {string} substr The string to remove.\n * @return {string} A copy of `str` with `substr` removed or the\n * full string if nothing is removed.\n */\ngoog.string.remove = function(str, substr) {\n 'use strict';\n return str.replace(substr, '');\n};\n\n\n/**\n * Removes all occurrences of a substring from a string.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to remove.\n * @return {string} A copy of `s` with `ss` removed or the full\n * string if nothing is removed.\n */\ngoog.string.removeAll = function(s, ss) {\n 'use strict';\n const re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, '');\n};\n\n\n/**\n * Replaces all occurrences of a substring of a string with a new substring.\n * @param {string} s The base string from which to remove.\n * @param {string} ss The string to replace.\n * @param {string} replacement The replacement string.\n * @return {string} A copy of `s` with `ss` replaced by\n * `replacement` or the original string if nothing is replaced.\n */\ngoog.string.replaceAll = function(s, ss, replacement) {\n 'use strict';\n const re = new RegExp(goog.string.regExpEscape(ss), 'g');\n return s.replace(re, replacement.replace(/\\$/g, '$$$$'));\n};\n\n\n/**\n * Escapes characters in the string that are not safe to use in a RegExp.\n * @param {*} s The string to escape. If not a string, it will be casted\n * to one.\n * @return {string} A RegExp safe, escaped copy of `s`.\n */\ngoog.string.regExpEscape = function(s) {\n 'use strict';\n return String(s)\n .replace(/([-()\\[\\]{}+?*.$\\^|,:#<!\\\\])/g, '\\\\$1')\n .replace(/\\x08/g, '\\\\x08');\n};\n\n\n/**\n * Repeats a string n times.\n * @param {string} string The string to repeat.\n * @param {number} length The number of times to repeat.\n * @return {string} A string containing `length` repetitions of\n * `string`.\n */\ngoog.string.repeat = (String.prototype.repeat) ? function(string, length) {\n 'use strict';\n // The native method is over 100 times faster than the alternative.\n return string.repeat(length);\n} : function(string, length) {\n 'use strict';\n return new Array(length + 1).join(string);\n};\n\n\n/**\n * Pads number to given length and optionally rounds it to a given precision.\n * For example:\n * <pre>padNumber(1.25, 2, 3) -> '01.250'\n * padNumber(1.25, 2) -> '01.25'\n * padNumber(1.25, 2, 1) -> '01.3'\n * padNumber(1.25, 0) -> '1.25'</pre>\n *\n * @param {number} num The number to pad.\n * @param {number} length The desired length.\n * @param {number=} opt_precision The desired precision.\n * @return {string} `num` as a string with the given options.\n */\ngoog.string.padNumber = function(num, length, opt_precision) {\n 'use strict';\n if (!Number.isFinite(num)) return String(num);\n let s =\n (opt_precision !== undefined) ? num.toFixed(opt_precision) : String(num);\n let index = s.indexOf('.');\n if (index === -1) {\n index = s.length;\n }\n const sign = s[0] === '-' ? '-' : '';\n if (sign) {\n s = s.substring(1);\n }\n return sign + goog.string.repeat('0', Math.max(0, length - index)) + s;\n};\n\n\n/**\n * Returns a string representation of the given object, with\n * null and undefined being returned as the empty string.\n *\n * @param {*} obj The object to convert.\n * @return {string} A string representation of the `obj`.\n */\ngoog.string.makeSafe = function(obj) {\n 'use strict';\n return obj == null ? '' : String(obj);\n};\n\n/**\n * Returns a string with at least 64-bits of randomness.\n *\n * Doesn't trust JavaScript's random function entirely. Uses a combination of\n * random and current timestamp, and then encodes the string in base-36 to\n * make it shorter.\n *\n * @return {string} A random string, e.g. sn1s7vb4gcic.\n */\ngoog.string.getRandomString = function() {\n 'use strict';\n const x = 2147483648;\n return Math.floor(Math.random() * x).toString(36) +\n Math.abs(Math.floor(Math.random() * x) ^ goog.now()).toString(36);\n};\n\n\n/**\n * Compares two version numbers.\n *\n * @param {string|number} version1 Version of first item.\n * @param {string|number} version2 Version of second item.\n *\n * @return {number} 1 if `version1` is higher.\n * 0 if arguments are equal.\n * -1 if `version2` is higher.\n */\ngoog.string.compareVersions = goog.string.internal.compareVersions;\n\n\n/**\n * String hash function similar to java.lang.String.hashCode().\n * The hash code for a string is computed as\n * s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],\n * where s[i] is the ith character of the string and n is the length of\n * the string. We mod the result to make it between 0 (inclusive) and 2^32\n * (exclusive).\n * @param {string} str A string.\n * @return {number} Hash value for `str`, between 0 (inclusive) and 2^32\n * (exclusive). The empty string returns 0.\n */\ngoog.string.hashCode = function(str) {\n 'use strict';\n let result = 0;\n for (let i = 0; i < str.length; ++i) {\n // Normalize to 4 byte range, 0 ... 2^32.\n result = (31 * result + str.charCodeAt(i)) >>> 0;\n }\n return result;\n};\n\n\n/**\n * The most recent unique ID. |0 is equivalent to Math.floor in this case.\n * @type {number}\n * @private\n */\ngoog.string.uniqueStringCounter_ = Math.random() * 0x80000000 | 0;\n\n\n/**\n * Generates and returns a string which is unique in the current document.\n * This is useful, for example, to create unique IDs for DOM elements.\n * @return {string} A unique id.\n */\ngoog.string.createUniqueString = function() {\n 'use strict';\n return 'goog_' + goog.string.uniqueStringCounter_++;\n};\n\n\n/**\n * Converts the supplied string to a number, which may be Infinity or NaN.\n * This function strips whitespace: (toNumber(' 123') === 123)\n * This function accepts scientific notation: (toNumber('1e1') === 10)\n *\n * This is better than JavaScript's built-in conversions because, sadly:\n * (Number(' ') === 0) and (parseFloat('123a') === 123)\n *\n * @param {string} str The string to convert.\n * @return {number} The number the supplied string represents, or NaN.\n */\ngoog.string.toNumber = function(str) {\n 'use strict';\n const num = Number(str);\n if (num == 0 && goog.string.isEmptyOrWhitespace(str)) {\n return NaN;\n }\n return num;\n};\n\n\n/**\n * Returns whether the given string is lower camel case (e.g. \"isFooBar\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is lower camel case.\n */\ngoog.string.isLowerCamelCase = function(str) {\n 'use strict';\n return /^[a-z]+([A-Z][a-z]*)*$/.test(str);\n};\n\n\n/**\n * Returns whether the given string is upper camel case (e.g. \"FooBarBaz\").\n *\n * Note that this assumes the string is entirely letters.\n * @see http://en.wikipedia.org/wiki/CamelCase#Variations_and_synonyms\n *\n * @param {string} str String to test.\n * @return {boolean} Whether the string is upper camel case.\n */\ngoog.string.isUpperCamelCase = function(str) {\n 'use strict';\n return /^([A-Z][a-z]*)+$/.test(str);\n};\n\n\n/**\n * Converts a string from selector-case to camelCase (e.g. from\n * \"multi-part-string\" to \"multiPartString\"), useful for converting\n * CSS selectors and HTML dataset keys to their equivalent JS properties.\n * @param {string} str The string in selector-case form.\n * @return {string} The string in camelCase form.\n */\ngoog.string.toCamelCase = function(str) {\n 'use strict';\n return String(str).replace(/\\-([a-z])/g, function(all, match) {\n 'use strict';\n return match.toUpperCase();\n });\n};\n\n\n/**\n * Converts a string from camelCase to selector-case (e.g. from\n * \"multiPartString\" to \"multi-part-string\"), useful for converting JS\n * style and dataset properties to equivalent CSS selectors and HTML keys.\n * @param {string} str The string in camelCase form.\n * @return {string} The string in selector-case form.\n */\ngoog.string.toSelectorCase = function(str) {\n 'use strict';\n return String(str).replace(/([A-Z])/g, '-$1').toLowerCase();\n};\n\n\n/**\n * Converts a string into TitleCase. First character of the string is always\n * capitalized in addition to the first letter of every subsequent word.\n * Words are delimited by one or more whitespaces by default. Custom delimiters\n * can optionally be specified to replace the default, which doesn't preserve\n * whitespace delimiters and instead must be explicitly included if needed.\n *\n * Default delimiter => \" \":\n * goog.string.toTitleCase('oneTwoThree') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three') => 'One Two Three'\n * goog.string.toTitleCase(' one two ') => ' One Two '\n * goog.string.toTitleCase('one_two_three') => 'One_two_three'\n * goog.string.toTitleCase('one-two-three') => 'One-two-three'\n *\n * Custom delimiter => \"_-.\":\n * goog.string.toTitleCase('oneTwoThree', '_-.') => 'OneTwoThree'\n * goog.string.toTitleCase('one two three', '_-.') => 'One two three'\n * goog.string.toTitleCase(' one two ', '_-.') => ' one two '\n * goog.string.toTitleCase('one_two_three', '_-.') => 'One_Two_Three'\n * goog.string.toTitleCase('one-two-three', '_-.') => 'One-Two-Three'\n * goog.string.toTitleCase('one...two...three', '_-.') => 'One...Two...Three'\n * goog.string.toTitleCase('one. two. three', '_-.') => 'One. two. three'\n * goog.string.toTitleCase('one-two.three', '_-.') => 'One-Two.Three'\n *\n * @param {string} str String value in camelCase form.\n * @param {string=} opt_delimiters Custom delimiter character set used to\n * distinguish words in the string value. Each character represents a\n * single delimiter. When provided, default whitespace delimiter is\n * overridden and must be explicitly included if needed.\n * @return {string} String value in TitleCase form.\n */\ngoog.string.toTitleCase = function(str, opt_delimiters) {\n 'use strict';\n let delimiters = (typeof opt_delimiters === 'string') ?\n goog.string.regExpEscape(opt_delimiters) :\n '\\\\s';\n\n // For IE8, we need to prevent using an empty character set. Otherwise,\n // incorrect matching will occur.\n delimiters = delimiters ? '|[' + delimiters + ']+' : '';\n\n const regexp = new RegExp('(^' + delimiters + ')([a-z])', 'g');\n return str.replace(regexp, function(all, p1, p2) {\n 'use strict';\n return p1 + p2.toUpperCase();\n });\n};\n\n\n/**\n * Capitalizes a string, i.e. converts the first letter to uppercase\n * and all other letters to lowercase, e.g.:\n *\n * goog.string.capitalize('one') => 'One'\n * goog.string.capitalize('ONE') => 'One'\n * goog.string.capitalize('one two') => 'One two'\n *\n * Note that this function does not trim initial whitespace.\n *\n * @param {string} str String value to capitalize.\n * @return {string} String value with first letter in uppercase.\n */\ngoog.string.capitalize = function(str) {\n 'use strict';\n return String(str.charAt(0)).toUpperCase() +\n String(str.substr(1)).toLowerCase();\n};\n\n\n/**\n * Parse a string in decimal or hexidecimal ('0xFFFF') form.\n *\n * To parse a particular radix, please use parseInt(string, radix) directly. See\n * https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt\n *\n * This is a wrapper for the built-in parseInt function that will only parse\n * numbers as base 10 or base 16. Some JS implementations assume strings\n * starting with \"0\" are intended to be octal. ES3 allowed but discouraged\n * this behavior. ES5 forbids it. This function emulates the ES5 behavior.\n *\n * For more information, see Mozilla JS Reference: http://goo.gl/8RiFj\n *\n * @param {string|number|null|undefined} value The value to be parsed.\n * @return {number} The number, parsed. If the string failed to parse, this\n * will be NaN.\n */\ngoog.string.parseInt = function(value) {\n 'use strict';\n // Force finite numbers to strings.\n if (isFinite(value)) {\n value = String(value);\n }\n\n if (typeof value === 'string') {\n // If the string starts with '0x' or '-0x', parse as hex.\n return /^\\s*-?0x/i.test(value) ? parseInt(value, 16) : parseInt(value, 10);\n }\n\n return NaN;\n};\n\n\n/**\n * Splits a string on a separator a limited number of times.\n *\n * This implementation is more similar to Python or Java, where the limit\n * parameter specifies the maximum number of splits rather than truncating\n * the number of results.\n *\n * See http://docs.python.org/2/library/stdtypes.html#str.split\n * See JavaDoc: http://goo.gl/F2AsY\n * See Mozilla reference: http://goo.gl/dZdZs\n *\n * @param {string} str String to split.\n * @param {string} separator The separator.\n * @param {number} limit The limit to the number of splits. The resulting array\n * will have a maximum length of limit+1. Negative numbers are the same\n * as zero.\n * @return {!Array<string>} The string, split.\n */\ngoog.string.splitLimit = function(str, separator, limit) {\n 'use strict';\n const parts = str.split(separator);\n const returnVal = [];\n\n // Only continue doing this while we haven't hit the limit and we have\n // parts left.\n while (limit > 0 && parts.length) {\n returnVal.push(parts.shift());\n limit--;\n }\n\n // If there are remaining parts, append them to the end.\n if (parts.length) {\n returnVal.push(parts.join(separator));\n }\n\n return returnVal;\n};\n\n\n/**\n * Finds the characters to the right of the last instance of any separator\n *\n * This function is similar to goog.string.path.baseName, except it can take a\n * list of characters to split the string on. It will return the rightmost\n * grouping of characters to the right of any separator as a left-to-right\n * oriented string.\n *\n * @see goog.string.path.baseName\n * @param {string} str The string\n * @param {string|!Array<string>} separators A list of separator characters\n * @return {string} The last part of the string with respect to the separators\n */\ngoog.string.lastComponent = function(str, separators) {\n 'use strict';\n if (!separators) {\n return str;\n } else if (typeof separators == 'string') {\n separators = [separators];\n }\n\n let lastSeparatorIndex = -1;\n for (let i = 0; i < separators.length; i++) {\n if (separators[i] == '') {\n continue;\n }\n const currentSeparatorIndex = str.lastIndexOf(separators[i]);\n if (currentSeparatorIndex > lastSeparatorIndex) {\n lastSeparatorIndex = currentSeparatorIndex;\n }\n }\n if (lastSeparatorIndex == -1) {\n return str;\n }\n return str.slice(lastSeparatorIndex + 1);\n};\n\n\n/**\n * Computes the Levenshtein edit distance between two strings.\n * @param {string} a\n * @param {string} b\n * @return {number} The edit distance between the two strings.\n */\ngoog.string.editDistance = function(a, b) {\n 'use strict';\n const v0 = [];\n const v1 = [];\n\n if (a == b) {\n return 0;\n }\n\n if (!a.length || !b.length) {\n return Math.max(a.length, b.length);\n }\n\n for (let i = 0; i < b.length + 1; i++) {\n v0[i] = i;\n }\n\n for (let i = 0; i < a.length; i++) {\n v1[0] = i + 1;\n\n for (let j = 0; j < b.length; j++) {\n const cost = Number(a[i] != b[j]);\n // Cost for the substring is the minimum of adding one character, removing\n // one character, or a swap.\n v1[j + 1] = Math.min(v1[j] + 1, v0[j + 1] + 1, v0[j] + cost);\n }\n\n for (let j = 0; j < v0.length; j++) {\n v0[j] = v1[j];\n }\n }\n\n return v1[b.length];\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview A pool of forward channel requests to enable real-time\n * messaging from the client to server.\n *\n */\n\ngoog.module('goog.labs.net.webChannel.ForwardChannelRequestPool');\n\ngoog.module.declareLegacyNamespace();\n\nconst ChannelRequest = goog.require('goog.labs.net.webChannel.ChannelRequest');\nconst Wire = goog.require('goog.labs.net.webChannel.Wire');\nconst array = goog.require('goog.array');\nconst googString = goog.require('goog.string');\n\n\n/**\n * This class represents the state of all forward channel requests.\n *\n * @param {number=} opt_maxPoolSize The maximum pool size.\n *\n * @struct @constructor @final\n */\nconst ForwardChannelRequestPool = function(opt_maxPoolSize) {\n /**\n * The max pool size as configured.\n *\n * @private {number}\n */\n this.maxPoolSizeConfigured_ =\n opt_maxPoolSize || ForwardChannelRequestPool.MAX_POOL_SIZE_;\n\n /**\n * The current size limit of the request pool. This limit is meant to be\n * read-only after the channel is fully opened.\n *\n * If SPDY or HTTP2 is enabled, set it to the max pool size, which is also\n * configurable.\n *\n * @private {number}\n */\n this.maxSize_ = ForwardChannelRequestPool.isSpdyOrHttp2Enabled_() ?\n this.maxPoolSizeConfigured_ :\n 1;\n\n /**\n * The container for all the pending request objects.\n *\n * @private {?Set<?ChannelRequest>}\n */\n this.requestPool_ = null;\n\n if (this.maxSize_ > 1) {\n this.requestPool_ = new Set();\n }\n\n /**\n * The single request object when the pool size is limited to one.\n *\n * @private {?ChannelRequest}\n */\n this.request_ = null;\n\n /**\n * Saved pending messages when the pool is cancelled.\n *\n * @private {!Array<Wire.QueuedMap>}\n */\n this.pendingMessages_ = [];\n};\n\n\n/**\n * The default size limit of the request pool.\n *\n * @private {number}\n */\nForwardChannelRequestPool.MAX_POOL_SIZE_ = 10;\n\n\n/**\n * @return {boolean} True if SPDY or HTTP2 is enabled. Uses chrome-specific APIs\n * as a fallback and will always return false for other browsers where\n * PerformanceNavigationTiming is not available.\n * @private\n */\nForwardChannelRequestPool.isSpdyOrHttp2Enabled_ = function() {\n if (goog.global.PerformanceNavigationTiming) {\n const entrys = /** @type {!Array<!PerformanceNavigationTiming>} */ (\n goog.global.performance.getEntriesByType('navigation'));\n return entrys.length > 0 &&\n (entrys[0].nextHopProtocol == 'hq' ||\n entrys[0].nextHopProtocol == 'h2');\n }\n return !!(\n goog.global.chrome && goog.global.chrome.loadTimes &&\n goog.global.chrome.loadTimes() &&\n goog.global.chrome.loadTimes().wasFetchedViaSpdy);\n};\n\n\n/**\n * Once we know the client protocol (from the handshake), check if we need\n * enable the request pool accordingly. This is more robust than using\n * browser-internal APIs (specific to Chrome).\n *\n * @param {string} clientProtocol The client protocol\n */\nForwardChannelRequestPool.prototype.applyClientProtocol = function(\n clientProtocol) {\n if (this.requestPool_) {\n return;\n }\n\n if (googString.contains(clientProtocol, 'spdy') ||\n googString.contains(clientProtocol, 'quic') ||\n googString.contains(clientProtocol, 'h2')) {\n this.maxSize_ = this.maxPoolSizeConfigured_;\n this.requestPool_ = new Set();\n if (this.request_) {\n this.addRequest(this.request_);\n this.request_ = null;\n }\n }\n};\n\n\n/**\n * @return {boolean} True if the pool is full.\n */\nForwardChannelRequestPool.prototype.isFull = function() {\n if (this.request_) {\n return true;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size >= this.maxSize_;\n }\n\n return false;\n};\n\n\n/**\n * @return {number} The current size limit.\n */\nForwardChannelRequestPool.prototype.getMaxSize = function() {\n return this.maxSize_;\n};\n\n\n/**\n * @return {number} The number of pending requests in the pool.\n */\nForwardChannelRequestPool.prototype.getRequestCount = function() {\n if (this.request_) {\n return 1;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.size;\n }\n\n return 0;\n};\n\n\n/**\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} True if the request is a included inside the pool.\n */\nForwardChannelRequestPool.prototype.hasRequest = function(req) {\n if (this.request_) {\n return this.request_ == req;\n }\n\n if (this.requestPool_) {\n return this.requestPool_.has(req);\n }\n\n return false;\n};\n\n\n/**\n * Adds a new request to the pool.\n *\n * @param {!ChannelRequest} req The new channel request.\n */\nForwardChannelRequestPool.prototype.addRequest = function(req) {\n if (this.requestPool_) {\n this.requestPool_.add(req);\n } else {\n this.request_ = req;\n }\n};\n\n\n/**\n * Removes the given request from the pool.\n *\n * @param {ChannelRequest} req The channel request.\n * @return {boolean} Whether the request has been removed from the pool.\n */\nForwardChannelRequestPool.prototype.removeRequest = function(req) {\n if (this.request_ && this.request_ == req) {\n this.request_ = null;\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.has(req)) {\n this.requestPool_.delete(req);\n return true;\n }\n\n return false;\n};\n\n\n/**\n * Clears the pool and cancel all the pending requests.\n */\nForwardChannelRequestPool.prototype.cancel = function() {\n // save any pending messages\n this.pendingMessages_ = this.getPendingMessages();\n\n if (this.request_) {\n this.request_.cancel();\n this.request_ = null;\n return;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n }\n this.requestPool_.clear();\n }\n};\n\n\n/**\n * @return {boolean} Whether there are any pending requests.\n */\nForwardChannelRequestPool.prototype.hasPendingRequest = function() {\n return (this.request_ != null) ||\n (this.requestPool_ != null && this.requestPool_.size !== 0);\n};\n\n\n/**\n * @return {!Array<Wire.QueuedMap>} All the pending messages from the pool,\n * as a new array.\n */\nForwardChannelRequestPool.prototype.getPendingMessages = function() {\n if (this.request_ != null) {\n return this.pendingMessages_.concat(this.request_.getPendingMessages());\n }\n\n if (this.requestPool_ != null && this.requestPool_.size !== 0) {\n let result = this.pendingMessages_;\n for (const val of this.requestPool_.values()) {\n result = result.concat(val.getPendingMessages());\n }\n return result;\n }\n\n return array.clone(this.pendingMessages_);\n};\n\n\n/**\n * Records pending messages, e.g. when a request receives a failed response.\n *\n * @param {!Array<Wire.QueuedMap>} messages Pending messages.\n */\nForwardChannelRequestPool.prototype.addPendingMessages = function(messages) {\n this.pendingMessages_ = this.pendingMessages_.concat(messages);\n};\n\n\n/**\n * Clears any recorded pending messages.\n */\nForwardChannelRequestPool.prototype.clearPendingMessages = function() {\n this.pendingMessages_.length = 0;\n};\n\n\n/**\n * Cancels all pending requests and force the completion of channel requests.\n *\n * Need go through the standard onRequestComplete logic to expose the max-retry\n * failure in the standard way.\n *\n * @param {function(!ChannelRequest)} onComplete The completion callback.\n * @return {boolean} true if any request has been forced to complete.\n */\nForwardChannelRequestPool.prototype.forceComplete = function(onComplete) {\n if (this.request_ != null) {\n this.request_.cancel();\n onComplete(this.request_);\n return true;\n }\n\n if (this.requestPool_ && this.requestPool_.size !== 0) {\n for (const val of this.requestPool_.values()) {\n val.cancel();\n onComplete(val);\n }\n return true;\n }\n\n return false;\n};\n\nexports = ForwardChannelRequestPool;\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Generics method for collection-like classes and objects.\n *\n *\n * This file contains functions to work with collections. It supports using\n * Map, Set, Array and Object and other classes that implement collection-like\n * methods.\n * @suppress {strictMissingProperties}\n */\n\n\ngoog.provide('goog.structs');\n\ngoog.require('goog.array');\ngoog.require('goog.object');\n\n\n// We treat an object as a dictionary if it has getKeys or it is an object that\n// isn't arrayLike.\n\n\n/**\n * Returns the number of values in the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {number} The number of values in the collection-like object.\n */\ngoog.structs.getCount = function(col) {\n 'use strict';\n if (col.getCount && typeof col.getCount == 'function') {\n return col.getCount();\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return col.length;\n }\n return goog.object.getCount(col);\n};\n\n\n/**\n * Returns the values of the collection-like object.\n * @param {Object} col The collection-like object.\n * @return {!Array<?>} The values in the collection-like object.\n */\ngoog.structs.getValues = function(col) {\n 'use strict';\n if (col.getValues && typeof col.getValues == 'function') {\n return col.getValues();\n }\n // ES6 Map and Set both define a values function that returns an iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if ((typeof Map !== 'undefined' && col instanceof Map) ||\n (typeof Set !== 'undefined' && col instanceof Set)) {\n return Array.from(col.values());\n }\n if (typeof col === 'string') {\n return col.split('');\n }\n if (goog.isArrayLike(col)) {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(col[i]);\n }\n return rv;\n }\n return goog.object.getValues(col);\n};\n\n\n/**\n * Returns the keys of the collection. Some collections have no notion of\n * keys/indexes and this function will return undefined in those cases.\n * @param {Object} col The collection-like object.\n * @return {!Array|undefined} The keys in the collection.\n */\ngoog.structs.getKeys = function(col) {\n 'use strict';\n if (col.getKeys && typeof col.getKeys == 'function') {\n return col.getKeys();\n }\n // if we have getValues but no getKeys we know this is a key-less collection\n if (col.getValues && typeof col.getValues == 'function') {\n return undefined;\n }\n // ES6 Map and Set both define a keys function that returns an iterator. For\n // Sets this iterates over the same values as the values iterator.\n // The typeof check allows the compiler to remove the Map and Set polyfills\n // if they are otherwise unused throughout the entire binary.\n if (typeof Map !== 'undefined' && col instanceof Map) {\n return Array.from(col.keys());\n }\n // Unlike the native Set, goog.structs.Set does not expose keys as the values.\n if (typeof Set !== 'undefined' && col instanceof Set) {\n return undefined;\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n var rv = [];\n var l = col.length;\n for (var i = 0; i < l; i++) {\n rv.push(i);\n }\n return rv;\n }\n\n return goog.object.getKeys(col);\n};\n\n\n/**\n * Whether the collection contains the given value. This is O(n) and uses\n * equals (==) to test the existence.\n * @param {Object} col The collection-like object.\n * @param {*} val The value to check for.\n * @return {boolean} True if the map contains the value.\n */\ngoog.structs.contains = function(col, val) {\n 'use strict';\n if (col.contains && typeof col.contains == 'function') {\n return col.contains(val);\n }\n if (col.containsValue && typeof col.containsValue == 'function') {\n return col.containsValue(val);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return goog.array.contains(/** @type {!Array<?>} */ (col), val);\n }\n return goog.object.containsValue(col, val);\n};\n\n\n/**\n * Whether the collection is empty.\n * @param {Object} col The collection-like object.\n * @return {boolean} True if empty.\n */\ngoog.structs.isEmpty = function(col) {\n 'use strict';\n if (col.isEmpty && typeof col.isEmpty == 'function') {\n return col.isEmpty();\n }\n\n // We do not use goog.string.isEmptyOrWhitespace because here we treat the\n // string as\n // collection and as such even whitespace matters\n\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return /** @type {!Array<?>} */ (col).length === 0;\n }\n return goog.object.isEmpty(col);\n};\n\n\n/**\n * Removes all the elements from the collection.\n * @param {Object} col The collection-like object.\n * @return {void}\n */\ngoog.structs.clear = function(col) {\n 'use strict';\n // NOTE(arv): This should not contain strings because strings are immutable\n if (col.clear && typeof col.clear == 'function') {\n col.clear();\n } else if (goog.isArrayLike(col)) {\n goog.array.clear(/** @type {IArrayLike<?>} */ (col));\n } else {\n goog.object.clear(col);\n }\n};\n\n\n/**\n * Calls a function for each value in a collection. The function takes\n * three arguments; the value, the key and the collection.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):?} f The function to call for every value.\n * This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and the return value is irrelevant.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {void}\n * @template T,S\n * @deprecated Use a more specific method, e.g. native Array.prototype.forEach,\n * or for-of.\n */\ngoog.structs.forEach = function(col, f, opt_obj) {\n 'use strict';\n if (col.forEach && typeof col.forEach == 'function') {\n col.forEach(f, opt_obj);\n } else if (goog.isArrayLike(col) || typeof col === 'string') {\n Array.prototype.forEach.call(/** @type {!Array<?>} */ (col), f, opt_obj);\n } else {\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col);\n }\n }\n};\n\n\n/**\n * Calls a function for every value in the collection. When a call returns true,\n * adds the value to a new collection (Array is returned by default).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes\n * 3 arguments (the value, the key or undefined if the collection has no\n * notion of keys, and the collection) and should return a Boolean. If the\n * return value is true the value is added to the result collection. If it\n * is false the value is not included.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object|!Array<?>} A new collection where the passed values are\n * present. If col is a key-less collection an array is returned. If col\n * has keys and values a plain old JS object is returned.\n * @template T,S\n */\ngoog.structs.filter = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.filter == 'function') {\n return col.filter(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.filter.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col)) {\n rv[keys[i]] = values[i];\n }\n }\n } else {\n // We should not use Array#filter here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n if (f.call(opt_obj, values[i], undefined, col)) {\n rv.push(values[i]);\n }\n }\n }\n return rv;\n};\n\n\n/**\n * Calls a function for every value in the collection and adds the result into a\n * new collection (defaults to creating a new Array).\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):V} f The function to call for every value.\n * This function takes 3 arguments (the value, the key or undefined if the\n * collection has no notion of keys, and the collection) and should return\n * something. The result will be used as the value in the new collection.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {!Object<V>|!Array<V>} A new collection with the new values. If\n * col is a key-less collection an array is returned. If col has keys and\n * values a plain old JS object is returned.\n * @template T,S,V\n */\ngoog.structs.map = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.map == 'function') {\n return col.map(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.map.call(/** @type {!Array<?>} */ (col), f, opt_obj);\n }\n\n var rv;\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n if (keys) {\n rv = {};\n for (var i = 0; i < l; i++) {\n rv[keys[i]] = f.call(/** @type {?} */ (opt_obj), values[i], keys[i], col);\n }\n } else {\n // We should not use Array#map here since we want to make sure that\n // the index is undefined as well as make sure that col is passed to the\n // function.\n rv = [];\n for (var i = 0; i < l; i++) {\n rv[i] = f.call(/** @type {?} */ (opt_obj), values[i], undefined, col);\n }\n }\n return rv;\n};\n\n\n/**\n * Calls f for each value in a collection. If any call returns true this returns\n * true (without checking the rest). If all returns false this returns false.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or undefined\n * if the collection has no notion of keys, and the collection) and should\n * return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if any value passes the test.\n * @template T,S\n */\ngoog.structs.some = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.some == 'function') {\n return col.some(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.some.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return true;\n }\n }\n return false;\n};\n\n\n/**\n * Calls f for each value in a collection. If all calls return true this return\n * true this returns true. If any returns false this returns false at this point\n * and does not continue to check the remaining values.\n *\n * @param {S} col The collection-like object.\n * @param {function(this:T,?,?,S):boolean} f The function to call for every\n * value. This function takes 3 arguments (the value, the key or\n * undefined if the collection has no notion of keys, and the collection)\n * and should return a boolean.\n * @param {T=} opt_obj The object to be used as the value of 'this'\n * within `f`.\n * @return {boolean} True if all key-value pairs pass the test.\n * @template T,S\n */\ngoog.structs.every = function(col, f, opt_obj) {\n 'use strict';\n if (typeof col.every == 'function') {\n return col.every(f, opt_obj);\n }\n if (goog.isArrayLike(col) || typeof col === 'string') {\n return Array.prototype.every.call(\n /** @type {!Array<?>} */ (col), f, opt_obj);\n }\n var keys = goog.structs.getKeys(col);\n var values = goog.structs.getValues(col);\n var l = values.length;\n for (var i = 0; i < l; i++) {\n if (!f.call(/** @type {?} */ (opt_obj), values[i], keys && keys[i], col)) {\n return false;\n }\n }\n return true;\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Simple utilities for dealing with URI strings.\n *\n * This package is deprecated in favour of the Closure URL package (goog.url)\n * when manipulating URIs for use by a browser. This package uses regular\n * expressions to parse a potential URI which can fall out of sync with how a\n * browser will actually interpret the URI. See\n * `goog.uri.utils.setUrlPackageSupportLoggingHandler` for one way to identify\n * URIs that should instead be parsed using the URL package.\n *\n * This is intended to be a lightweight alternative to constructing goog.Uri\n * objects. Whereas goog.Uri adds several kilobytes to the binary regardless\n * of how much of its functionality you use, this is designed to be a set of\n * mostly-independent utilities so that the compiler includes only what is\n * necessary for the task. Estimated savings of porting is 5k pre-gzip and\n * 1.5k post-gzip. To ensure the savings remain, future developers should\n * avoid adding new functionality to existing functions, but instead create\n * new ones and factor out shared code.\n *\n * Many of these utilities have limited functionality, tailored to common\n * cases. The query parameter utilities assume that the parameter keys are\n * already encoded, since most keys are compile-time alphanumeric strings. The\n * query parameter mutation utilities also do not tolerate fragment identifiers.\n *\n * By design, these functions can be slower than goog.Uri equivalents.\n * Repeated calls to some of functions may be quadratic in behavior for IE,\n * although the effect is somewhat limited given the 2kb limit.\n *\n * One advantage of the limited functionality here is that this approach is\n * less sensitive to differences in URI encodings than goog.Uri, since these\n * functions operate on strings directly, rather than decoding them and\n * then re-encoding.\n *\n * Uses features of RFC 3986 for parsing/formatting URIs:\n * http://www.ietf.org/rfc/rfc3986.txt\n */\n\ngoog.provide('goog.uri.utils');\ngoog.provide('goog.uri.utils.ComponentIndex');\ngoog.provide('goog.uri.utils.QueryArray');\ngoog.provide('goog.uri.utils.QueryValue');\ngoog.provide('goog.uri.utils.StandardQueryParam');\n\ngoog.require('goog.asserts');\ngoog.require('goog.string');\n\n\n/**\n * Character codes inlined to avoid object allocations due to charCode.\n * @enum {number}\n * @private\n */\ngoog.uri.utils.CharCode_ = {\n AMPERSAND: 38,\n EQUAL: 61,\n HASH: 35,\n QUESTION: 63\n};\n\n\n/**\n * Builds a URI string from already-encoded parts.\n *\n * No encoding is performed. Any component may be omitted as either null or\n * undefined.\n *\n * @param {?string=} opt_scheme The scheme such as 'http'.\n * @param {?string=} opt_userInfo The user name before the '@'.\n * @param {?string=} opt_domain The domain such as 'www.google.com', already\n * URI-encoded.\n * @param {(string|number|null)=} opt_port The port number.\n * @param {?string=} opt_path The path, already URI-encoded. If it is not\n * empty, it must begin with a slash.\n * @param {?string=} opt_queryData The URI-encoded query data.\n * @param {?string=} opt_fragment The URI-encoded fragment identifier.\n * @return {string} The fully combined URI.\n */\ngoog.uri.utils.buildFromEncodedParts = function(\n opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData,\n opt_fragment) {\n 'use strict';\n var out = '';\n\n if (opt_scheme) {\n out += opt_scheme + ':';\n }\n\n if (opt_domain) {\n out += '//';\n\n if (opt_userInfo) {\n out += opt_userInfo + '@';\n }\n\n out += opt_domain;\n\n if (opt_port) {\n out += ':' + opt_port;\n }\n }\n\n if (opt_path) {\n out += opt_path;\n }\n\n if (opt_queryData) {\n out += '?' + opt_queryData;\n }\n\n if (opt_fragment) {\n out += '#' + opt_fragment;\n }\n\n return out;\n};\n\n\n/**\n * A regular expression for breaking a URI into its component parts.\n *\n * {@link http://www.ietf.org/rfc/rfc3986.txt} says in Appendix B\n * As the \"first-match-wins\" algorithm is identical to the \"greedy\"\n * disambiguation method used by POSIX regular expressions, it is natural and\n * commonplace to use a regular expression for parsing the potential five\n * components of a URI reference.\n *\n * The following line is the regular expression for breaking-down a\n * well-formed URI reference into its components.\n *\n * <pre>\n * ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?\n * 12 3 4 5 6 7 8 9\n * </pre>\n *\n * The numbers in the second line above are only to assist readability; they\n * indicate the reference points for each subexpression (i.e., each paired\n * parenthesis). We refer to the value matched for subexpression <n> as $<n>.\n * For example, matching the above expression to\n * <pre>\n * http://www.ics.uci.edu/pub/ietf/uri/#Related\n * </pre>\n * results in the following subexpression matches:\n * <pre>\n * $1 = http:\n * $2 = http\n * $3 = //www.ics.uci.edu\n * $4 = www.ics.uci.edu\n * $5 = /pub/ietf/uri/\n * $6 = <undefined>\n * $7 = <undefined>\n * $8 = #Related\n * $9 = Related\n * </pre>\n * where <undefined> indicates that the component is not present, as is the\n * case for the query component in the above example. Therefore, we can\n * determine the value of the five components as\n * <pre>\n * scheme = $2\n * authority = $4\n * path = $5\n * query = $7\n * fragment = $9\n * </pre>\n *\n * The regular expression has been modified slightly to expose the\n * userInfo, domain, and port separately from the authority.\n * The modified version yields\n * <pre>\n * $1 = http scheme\n * $2 = <undefined> userInfo -\\\n * $3 = www.ics.uci.edu domain | authority\n * $4 = <undefined> port -/\n * $5 = /pub/ietf/uri/ path\n * $6 = <undefined> query without ?\n * $7 = Related fragment without #\n * </pre>\n *\n * TODO(user): separate out the authority terminating characters once this\n * file is moved to ES6.\n * @type {!RegExp}\n * @private\n */\ngoog.uri.utils.splitRe_ = new RegExp(\n '^' + // Anchor against the entire string.\n '(?:' +\n '([^:/?#.]+)' + // scheme - ignore special characters\n // used by other URL parts such as :,\n // ?, /, #, and .\n ':)?' +\n '(?://' +\n '(?:([^\\\\\\\\/?#]*)@)?' + // userInfo\n '([^\\\\\\\\/?#]*?)' + // domain\n '(?::([0-9]+))?' + // port\n '(?=[\\\\\\\\/?#]|$)' + // authority-terminating character.\n ')?' +\n '([^?#]+)?' + // path\n '(?:\\\\?([^#]*))?' + // query\n '(?:#([\\\\s\\\\S]*))?' + // fragment. Can't use '.*' with 's' flag as Firefox\n // doesn't support the flag, and can't use an\n // \"everything set\" ([^]) as IE10 doesn't match any\n // characters with it.\n '$');\n\n\n/**\n * The index of each URI component in the return value of goog.uri.utils.split.\n * @enum {number}\n */\ngoog.uri.utils.ComponentIndex = {\n SCHEME: 1,\n USER_INFO: 2,\n DOMAIN: 3,\n PORT: 4,\n PATH: 5,\n QUERY_DATA: 6,\n FRAGMENT: 7\n};\n\n/**\n * @type {?function(string)}\n * @private\n */\ngoog.uri.utils.urlPackageSupportLoggingHandler_ = null;\n\n/**\n * @param {?function(string)} handler The handler function to call when a URI\n * with a protocol that is better supported by the Closure URL package is\n * detected.\n */\ngoog.uri.utils.setUrlPackageSupportLoggingHandler = function(handler) {\n 'use strict';\n goog.uri.utils.urlPackageSupportLoggingHandler_ = handler;\n};\n\n/**\n * Splits a URI into its component parts.\n *\n * Each component can be accessed via the component indices; for example:\n * <pre>\n * goog.uri.utils.split(someStr)[goog.uri.utils.ComponentIndex.QUERY_DATA];\n * </pre>\n *\n * @param {string} uri The URI string to examine.\n * @return {!Array<string|undefined>} Each component still URI-encoded.\n * Each component that is present will contain the encoded value, whereas\n * components that are not present will be undefined or empty, depending\n * on the browser's regular expression implementation. Never null, since\n * arbitrary strings may still look like path names.\n */\ngoog.uri.utils.split = function(uri) {\n 'use strict';\n // See @return comment -- never null.\n var result = /** @type {!Array<string|undefined>} */ (\n uri.match(goog.uri.utils.splitRe_));\n if (goog.uri.utils.urlPackageSupportLoggingHandler_ &&\n ['http', 'https', 'ws', 'wss',\n 'ftp'].indexOf(result[goog.uri.utils.ComponentIndex.SCHEME]) >= 0) {\n goog.uri.utils.urlPackageSupportLoggingHandler_(uri);\n }\n return result;\n};\n\n\n/**\n * @param {?string} uri A possibly null string.\n * @param {boolean=} opt_preserveReserved If true, percent-encoding of RFC-3986\n * reserved characters will not be removed.\n * @return {?string} The string URI-decoded, or null if uri is null.\n * @private\n */\ngoog.uri.utils.decodeIfPossible_ = function(uri, opt_preserveReserved) {\n 'use strict';\n if (!uri) {\n return uri;\n }\n\n return opt_preserveReserved ? decodeURI(uri) : decodeURIComponent(uri);\n};\n\n\n/**\n * Gets a URI component by index.\n *\n * It is preferred to use the getPathEncoded() variety of functions ahead,\n * since they are more readable.\n *\n * @param {goog.uri.utils.ComponentIndex} componentIndex The component index.\n * @param {string} uri The URI to examine.\n * @return {?string} The still-encoded component, or null if the component\n * is not present.\n * @private\n */\ngoog.uri.utils.getComponentByIndex_ = function(componentIndex, uri) {\n 'use strict';\n // Convert undefined, null, and empty string into null.\n return goog.uri.utils.split(uri)[componentIndex] || null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The protocol or scheme, or null if none. Does not\n * include trailing colons or slashes.\n */\ngoog.uri.utils.getScheme = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.SCHEME, uri);\n};\n\n\n/**\n * Gets the effective scheme for the URL. If the URL is relative then the\n * scheme is derived from the page's location.\n * @param {string} uri The URI to examine.\n * @return {string} The protocol or scheme, always lower case.\n */\ngoog.uri.utils.getEffectiveScheme = function(uri) {\n 'use strict';\n var scheme = goog.uri.utils.getScheme(uri);\n if (!scheme && goog.global.self && goog.global.self.location) {\n var protocol = goog.global.self.location.protocol;\n scheme = protocol.substr(0, protocol.length - 1);\n }\n // NOTE: When called from a web worker in Firefox 3.5, location may be null.\n // All other browsers with web workers support self.location from the worker.\n return scheme ? scheme.toLowerCase() : '';\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The user name still encoded, or null if none.\n */\ngoog.uri.utils.getUserInfoEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.USER_INFO, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded user info, or null if none.\n */\ngoog.uri.utils.getUserInfo = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getUserInfoEncoded(uri));\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The domain name still encoded, or null if none.\n */\ngoog.uri.utils.getDomainEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.DOMAIN, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded domain, or null if none.\n */\ngoog.uri.utils.getDomain = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getDomainEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?number} The port number, or null if none.\n */\ngoog.uri.utils.getPort = function(uri) {\n 'use strict';\n // Coerce to a number. If the result of getComponentByIndex_ is null or\n // non-numeric, the number coersion yields NaN. This will then return\n // null for all non-numeric cases (though also zero, which isn't a relevant\n // port number).\n return Number(\n goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PORT, uri)) ||\n null;\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The path still encoded, or null if none. Includes the\n * leading slash, if any.\n */\ngoog.uri.utils.getPathEncoded = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.PATH, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded path, or null if none. Includes the leading\n * slash, if any.\n */\ngoog.uri.utils.getPath = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getPathEncoded(uri), true /* opt_preserveReserved */);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The query data still encoded, or null if none. Does not\n * include the question mark itself.\n */\ngoog.uri.utils.getQueryData = function(uri) {\n 'use strict';\n return goog.uri.utils.getComponentByIndex_(\n goog.uri.utils.ComponentIndex.QUERY_DATA, uri);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The fragment identifier, or null if none. Does not\n * include the hash mark itself.\n */\ngoog.uri.utils.getFragmentEncoded = function(uri) {\n 'use strict';\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? null : uri.substr(hashIndex + 1);\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @param {?string} fragment The encoded fragment identifier, or null if none.\n * Does not include the hash mark itself.\n * @return {string} The URI with the fragment set.\n */\ngoog.uri.utils.setFragmentEncoded = function(uri, fragment) {\n 'use strict';\n return goog.uri.utils.removeFragment(uri) + (fragment ? '#' + fragment : '');\n};\n\n\n/**\n * @param {string} uri The URI to examine.\n * @return {?string} The decoded fragment identifier, or null if none. Does\n * not include the hash mark.\n */\ngoog.uri.utils.getFragment = function(uri) {\n 'use strict';\n return goog.uri.utils.decodeIfPossible_(\n goog.uri.utils.getFragmentEncoded(uri));\n};\n\n\n/**\n * Extracts everything up to the port of the URI.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getHost = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME],\n pieces[goog.uri.utils.ComponentIndex.USER_INFO],\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Returns the origin for a given URL.\n * @param {string} uri The URI string.\n * @return {string} Everything up to and including the port.\n */\ngoog.uri.utils.getOrigin = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n pieces[goog.uri.utils.ComponentIndex.SCHEME], null /* opt_userInfo */,\n pieces[goog.uri.utils.ComponentIndex.DOMAIN],\n pieces[goog.uri.utils.ComponentIndex.PORT]);\n};\n\n\n/**\n * Extracts the path of the URL and everything after.\n * @param {string} uri The URI string.\n * @return {string} The URI, starting at the path and including the query\n * parameters and fragment identifier.\n */\ngoog.uri.utils.getPathAndAfter = function(uri) {\n 'use strict';\n var pieces = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n null, null, null, null, pieces[goog.uri.utils.ComponentIndex.PATH],\n pieces[goog.uri.utils.ComponentIndex.QUERY_DATA],\n pieces[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Gets the URI with the fragment identifier removed.\n * @param {string} uri The URI to examine.\n * @return {string} Everything preceding the hash mark.\n */\ngoog.uri.utils.removeFragment = function(uri) {\n 'use strict';\n // The hash mark may not appear in any other part of the URL.\n var hashIndex = uri.indexOf('#');\n return hashIndex < 0 ? uri : uri.substr(0, hashIndex);\n};\n\n\n/**\n * Ensures that two URI's have the exact same domain, scheme, and port.\n *\n * Unlike the version in goog.Uri, this checks protocol, and therefore is\n * suitable for checking against the browser's same-origin policy.\n *\n * @param {string} uri1 The first URI.\n * @param {string} uri2 The second URI.\n * @return {boolean} Whether they have the same scheme, domain and port.\n */\ngoog.uri.utils.haveSameDomain = function(uri1, uri2) {\n 'use strict';\n var pieces1 = goog.uri.utils.split(uri1);\n var pieces2 = goog.uri.utils.split(uri2);\n return pieces1[goog.uri.utils.ComponentIndex.DOMAIN] ==\n pieces2[goog.uri.utils.ComponentIndex.DOMAIN] &&\n pieces1[goog.uri.utils.ComponentIndex.SCHEME] ==\n pieces2[goog.uri.utils.ComponentIndex.SCHEME] &&\n pieces1[goog.uri.utils.ComponentIndex.PORT] ==\n pieces2[goog.uri.utils.ComponentIndex.PORT];\n};\n\n\n/**\n * Asserts that there are no fragment or query identifiers, only in uncompiled\n * mode.\n * @param {string} uri The URI to examine.\n * @private\n */\ngoog.uri.utils.assertNoFragmentsOrQueries_ = function(uri) {\n 'use strict';\n goog.asserts.assert(\n uri.indexOf('#') < 0 && uri.indexOf('?') < 0,\n 'goog.uri.utils: Fragment or query identifiers are not supported: [%s]',\n uri);\n};\n\n\n/**\n * Supported query parameter values by the parameter serializing utilities.\n *\n * If a value is null or undefined, the key-value pair is skipped, as an easy\n * way to omit parameters conditionally. Non-array parameters are converted\n * to a string and URI encoded. Array values are expanded into multiple\n * &key=value pairs, with each element stringized and URI-encoded.\n *\n * @typedef {*}\n */\ngoog.uri.utils.QueryValue;\n\n\n/**\n * An array representing a set of query parameters with alternating keys\n * and values.\n *\n * Keys are assumed to be URI encoded already and live at even indices. See\n * goog.uri.utils.QueryValue for details on how parameter values are encoded.\n *\n * Example:\n * <pre>\n * var data = [\n * // Simple param: ?name=BobBarker\n * 'name', 'BobBarker',\n * // Conditional param -- may be omitted entirely.\n * 'specialDietaryNeeds', hasDietaryNeeds() ? getDietaryNeeds() : null,\n * // Multi-valued param: &house=LosAngeles&house=NewYork&house=null\n * 'house', ['LosAngeles', 'NewYork', null]\n * ];\n * </pre>\n *\n * @typedef {!Array<string|goog.uri.utils.QueryValue>}\n */\ngoog.uri.utils.QueryArray;\n\n\n/**\n * Parses encoded query parameters and calls callback function for every\n * parameter found in the string.\n *\n * Missing value of parameter (e.g. “…&key&…”) is treated as if the value was an\n * empty string. Keys may be empty strings (e.g. “…&=value&…”) which also means\n * that “…&=&…” and “…&&…” will result in an empty key and value.\n *\n * @param {string} encodedQuery Encoded query string excluding question mark at\n * the beginning.\n * @param {function(string, string)} callback Function called for every\n * parameter found in query string. The first argument (name) will not be\n * urldecoded (so the function is consistent with buildQueryData), but the\n * second will. If the parameter has no value (i.e. “=” was not present)\n * the second argument (value) will be an empty string.\n */\ngoog.uri.utils.parseQueryData = function(encodedQuery, callback) {\n 'use strict';\n if (!encodedQuery) {\n return;\n }\n var pairs = encodedQuery.split('&');\n for (var i = 0; i < pairs.length; i++) {\n var indexOfEquals = pairs[i].indexOf('=');\n var name = null;\n var value = null;\n if (indexOfEquals >= 0) {\n name = pairs[i].substring(0, indexOfEquals);\n value = pairs[i].substring(indexOfEquals + 1);\n } else {\n name = pairs[i];\n }\n callback(name, value ? goog.string.urlDecode(value) : '');\n }\n};\n\n\n/**\n * Split the URI into 3 parts where the [1] is the queryData without a leading\n * '?'. For example, the URI http://foo.com/bar?a=b#abc returns\n * ['http://foo.com/bar','a=b','#abc'].\n * @param {string} uri The URI to parse.\n * @return {!Array<string>} An array representation of uri of length 3 where the\n * middle value is the queryData without a leading '?'.\n * @private\n */\ngoog.uri.utils.splitQueryData_ = function(uri) {\n 'use strict';\n // Find the query data and hash.\n var hashIndex = uri.indexOf('#');\n if (hashIndex < 0) {\n hashIndex = uri.length;\n }\n var questionIndex = uri.indexOf('?');\n var queryData;\n if (questionIndex < 0 || questionIndex > hashIndex) {\n questionIndex = hashIndex;\n queryData = '';\n } else {\n queryData = uri.substring(questionIndex + 1, hashIndex);\n }\n return [uri.substr(0, questionIndex), queryData, uri.substr(hashIndex)];\n};\n\n\n/**\n * Join an array created by splitQueryData_ back into a URI.\n * @param {!Array<string>} parts A URI in the form generated by splitQueryData_.\n * @return {string} The joined URI.\n * @private\n */\ngoog.uri.utils.joinQueryData_ = function(parts) {\n 'use strict';\n return parts[0] + (parts[1] ? '?' + parts[1] : '') + parts[2];\n};\n\n\n/**\n * @param {string} queryData\n * @param {string} newData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryData_ = function(queryData, newData) {\n 'use strict';\n if (!newData) {\n return queryData;\n }\n return queryData ? queryData + '&' + newData : newData;\n};\n\n\n/**\n * @param {string} uri\n * @param {string} queryData\n * @return {string}\n * @private\n */\ngoog.uri.utils.appendQueryDataToUri_ = function(uri, queryData) {\n 'use strict';\n if (!queryData) {\n return uri;\n }\n var parts = goog.uri.utils.splitQueryData_(uri);\n parts[1] = goog.uri.utils.appendQueryData_(parts[1], queryData);\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Appends key=value pairs to an array, supporting multi-valued objects.\n * @param {*} key The key prefix.\n * @param {goog.uri.utils.QueryValue} value The value to serialize.\n * @param {!Array<string>} pairs The array to which the 'key=value' strings\n * should be appended.\n * @private\n */\ngoog.uri.utils.appendKeyValuePairs_ = function(key, value, pairs) {\n 'use strict';\n goog.asserts.assertString(key);\n if (Array.isArray(value)) {\n // Convince the compiler it's an array.\n goog.asserts.assertArray(value);\n for (var j = 0; j < value.length; j++) {\n // Convert to string explicitly, to short circuit the null and array\n // logic in this function -- this ensures that null and undefined get\n // written as literal 'null' and 'undefined', and arrays don't get\n // expanded out but instead encoded in the default way.\n goog.uri.utils.appendKeyValuePairs_(key, String(value[j]), pairs);\n }\n } else if (value != null) {\n // Skip a top-level null or undefined entirely.\n pairs.push(\n key +\n // Check for empty string. Zero gets encoded into the url as literal\n // strings. For empty string, skip the equal sign, to be consistent\n // with UriBuilder.java.\n (value === '' ? '' : '=' + goog.string.urlEncode(value)));\n }\n};\n\n\n/**\n * Builds a query data string from a sequence of alternating keys and values.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!IArrayLike<string|goog.uri.utils.QueryValue>} keysAndValues\n * Alternating keys and values. See the QueryArray typedef.\n * @param {number=} opt_startIndex A start offset into the arary, defaults to 0.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryData = function(keysAndValues, opt_startIndex) {\n 'use strict';\n goog.asserts.assert(\n Math.max(keysAndValues.length - (opt_startIndex || 0), 0) % 2 == 0,\n 'goog.uri.utils: Key/value lists must be even in length.');\n\n var params = [];\n for (var i = opt_startIndex || 0; i < keysAndValues.length; i += 2) {\n var key = /** @type {string} */ (keysAndValues[i]);\n goog.uri.utils.appendKeyValuePairs_(key, keysAndValues[i + 1], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Builds a query data string from a map.\n * Currently generates \"&key&\" for empty args.\n *\n * @param {!Object<string, goog.uri.utils.QueryValue>} map An object where keys\n * are URI-encoded parameter keys, and the values are arbitrary types\n * or arrays. Keys with a null value are dropped.\n * @return {string} The encoded query string, in the form 'a=1&b=2'.\n */\ngoog.uri.utils.buildQueryDataFromMap = function(map) {\n 'use strict';\n var params = [];\n for (var key in map) {\n goog.uri.utils.appendKeyValuePairs_(key, map[key], params);\n }\n return params.join('&');\n};\n\n\n/**\n * Appends URI parameters to an existing URI.\n *\n * The variable arguments may contain alternating keys and values. Keys are\n * assumed to be already URI encoded. The values should not be URI-encoded,\n * and will instead be encoded by this function.\n * <pre>\n * appendParams('http://www.foo.com?existing=true',\n * 'key1', 'value1',\n * 'key2', 'value?willBeEncoded',\n * 'key3', ['valueA', 'valueB', 'valueC'],\n * 'key4', null);\n * result: 'http://www.foo.com?existing=true&' +\n * 'key1=value1&' +\n * 'key2=value%3FwillBeEncoded&' +\n * 'key3=valueA&key3=valueB&key3=valueC'\n * </pre>\n *\n * A single call to this function will not exhibit quadratic behavior in IE,\n * whereas multiple repeated calls may, although the effect is limited by\n * fact that URL's generally can't exceed 2kb.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {...(goog.uri.utils.QueryArray|goog.uri.utils.QueryValue)}\n * var_args\n * An array or argument list conforming to goog.uri.utils.QueryArray.\n * @return {string} The URI with all query parameters added.\n */\ngoog.uri.utils.appendParams = function(uri, var_args) {\n 'use strict';\n var queryData = arguments.length == 2 ?\n goog.uri.utils.buildQueryData(arguments[1], 0) :\n goog.uri.utils.buildQueryData(arguments, 1);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends query parameters from a map.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {!Object<goog.uri.utils.QueryValue>} map An object where keys are\n * URI-encoded parameter keys, and the values are arbitrary types or arrays.\n * Keys with a null value are dropped.\n * @return {string} The new parameters.\n */\ngoog.uri.utils.appendParamsFromMap = function(uri, map) {\n 'use strict';\n var queryData = goog.uri.utils.buildQueryDataFromMap(map);\n return goog.uri.utils.appendQueryDataToUri_(uri, queryData);\n};\n\n\n/**\n * Appends a single URI parameter.\n *\n * Repeated calls to this can exhibit quadratic behavior in IE6 due to the\n * way string append works, though it should be limited given the 2kb limit.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} key The key, which must already be URI encoded.\n * @param {*=} opt_value The value, which will be stringized and encoded\n * (assumed not already to be encoded). If omitted, undefined, or null, the\n * key will be added as a valueless parameter.\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.appendParam = function(uri, key, opt_value) {\n 'use strict';\n var value = (opt_value != null) ? '=' + goog.string.urlEncode(opt_value) : '';\n return goog.uri.utils.appendQueryDataToUri_(uri, key + value);\n};\n\n\n/**\n * Finds the next instance of a query parameter with the specified name.\n *\n * Does not instantiate any objects.\n *\n * @param {string} uri The URI to search. May contain a fragment identifier\n * if opt_hashIndex is specified.\n * @param {number} startIndex The index to begin searching for the key at. A\n * match may be found even if this is one character after the ampersand.\n * @param {string} keyEncoded The URI-encoded key.\n * @param {number} hashOrEndIndex Index to stop looking at. If a hash\n * mark is present, it should be its index, otherwise it should be the\n * length of the string.\n * @return {number} The position of the first character in the key's name,\n * immediately after either a question mark or a dot.\n * @private\n */\ngoog.uri.utils.findParam_ = function(\n uri, startIndex, keyEncoded, hashOrEndIndex) {\n 'use strict';\n var index = startIndex;\n var keyLength = keyEncoded.length;\n\n // Search for the key itself and post-filter for surronuding punctuation,\n // rather than expensively building a regexp.\n while ((index = uri.indexOf(keyEncoded, index)) >= 0 &&\n index < hashOrEndIndex) {\n var precedingChar = uri.charCodeAt(index - 1);\n // Ensure that the preceding character is '&' or '?'.\n if (precedingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n precedingChar == goog.uri.utils.CharCode_.QUESTION) {\n // Ensure the following character is '&', '=', '#', or NaN\n // (end of string).\n var followingChar = uri.charCodeAt(index + keyLength);\n if (!followingChar || followingChar == goog.uri.utils.CharCode_.EQUAL ||\n followingChar == goog.uri.utils.CharCode_.AMPERSAND ||\n followingChar == goog.uri.utils.CharCode_.HASH) {\n return index;\n }\n }\n index += keyLength + 1;\n }\n\n return -1;\n};\n\n\n/**\n * Regular expression for finding a hash mark or end of string.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.hashOrEndRe_ = /#|$/;\n\n\n/**\n * Determines if the URI contains a specific key.\n *\n * Performs no object instantiations.\n *\n * @param {string} uri The URI to process. May contain a fragment\n * identifier.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {boolean} Whether the key is present.\n */\ngoog.uri.utils.hasParam = function(uri, keyEncoded) {\n 'use strict';\n return goog.uri.utils.findParam_(\n uri, 0, keyEncoded, uri.search(goog.uri.utils.hashOrEndRe_)) >= 0;\n};\n\n\n/**\n * Gets the first value of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {?string} The first value of the parameter (URI-decoded), or null\n * if the parameter is not found.\n */\ngoog.uri.utils.getParamValue = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var foundIndex =\n goog.uri.utils.findParam_(uri, 0, keyEncoded, hashOrEndIndex);\n\n if (foundIndex < 0) {\n return null;\n } else {\n var endPosition = uri.indexOf('&', foundIndex);\n if (endPosition < 0 || endPosition > hashOrEndIndex) {\n endPosition = hashOrEndIndex;\n }\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n // Use substr, because it (unlike substring) will return empty string\n // if foundIndex > endPosition.\n return goog.string.urlDecode(\n uri.substr(foundIndex, endPosition - foundIndex));\n }\n};\n\n\n/**\n * Gets all values of a query parameter.\n * @param {string} uri The URI to process. May contain a fragment.\n * @param {string} keyEncoded The URI-encoded key. Case-sensitive.\n * @return {!Array<string>} All URI-decoded values with the given key.\n * If the key is not found, this will have length 0, but never be null.\n */\ngoog.uri.utils.getParamValues = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var result = [];\n\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Find where this parameter ends, either the '&' or the end of the\n // query parameters.\n position = uri.indexOf('&', foundIndex);\n if (position < 0 || position > hashOrEndIndex) {\n position = hashOrEndIndex;\n }\n\n // Progress forth to the end of the \"key=\" or \"key&\" substring.\n foundIndex += keyEncoded.length + 1;\n // Use substr, because it (unlike substring) will return empty string\n // if foundIndex > position.\n result.push(\n goog.string.urlDecode(uri.substr(foundIndex, position - foundIndex)));\n }\n\n return result;\n};\n\n\n/**\n * Regexp to find trailing question marks and ampersands.\n * @type {RegExp}\n * @private\n */\ngoog.uri.utils.trailingQueryPunctuationRe_ = /[?&]($|#)/;\n\n\n/**\n * Removes all instances of a query parameter.\n * @param {string} uri The URI to process. Must not contain a fragment.\n * @param {string} keyEncoded The URI-encoded key.\n * @return {string} The URI with all instances of the parameter removed.\n */\ngoog.uri.utils.removeParam = function(uri, keyEncoded) {\n 'use strict';\n var hashOrEndIndex = uri.search(goog.uri.utils.hashOrEndRe_);\n var position = 0;\n var foundIndex;\n var buffer = [];\n\n // Look for a query parameter.\n while ((foundIndex = goog.uri.utils.findParam_(\n uri, position, keyEncoded, hashOrEndIndex)) >= 0) {\n // Get the portion of the query string up to, but not including, the ?\n // or & starting the parameter.\n buffer.push(uri.substring(position, foundIndex));\n // Progress to immediately after the '&'. If not found, go to the end.\n // Avoid including the hash mark.\n position = Math.min(\n (uri.indexOf('&', foundIndex) + 1) || hashOrEndIndex, hashOrEndIndex);\n }\n\n // Append everything that is remaining.\n buffer.push(uri.substr(position));\n\n // Join the buffer, and remove trailing punctuation that remains.\n return buffer.join('').replace(\n goog.uri.utils.trailingQueryPunctuationRe_, '$1');\n};\n\n\n/**\n * Replaces all existing definitions of a parameter with a single definition.\n *\n * Repeated calls to this can exhibit quadratic behavior due to the need to\n * find existing instances and reconstruct the string, though it should be\n * limited given the 2kb limit. Consider using appendParams or setParamsFromMap\n * to update multiple parameters in bulk.\n *\n * @param {string} uri The original URI, which may already have query data.\n * @param {string} keyEncoded The key, which must already be URI encoded.\n * @param {*} value The value, which will be stringized and encoded (assumed\n * not already to be encoded).\n * @return {string} The URI with the query parameter added.\n */\ngoog.uri.utils.setParam = function(uri, keyEncoded, value) {\n 'use strict';\n return goog.uri.utils.appendParam(\n goog.uri.utils.removeParam(uri, keyEncoded), keyEncoded, value);\n};\n\n\n/**\n * Effeciently set or remove multiple query parameters in a URI. Order of\n * unchanged parameters will not be modified, all updated parameters will be\n * appended to the end of the query. Params with values of null or undefined are\n * removed.\n *\n * @param {string} uri The URI to process.\n * @param {!Object<string, goog.uri.utils.QueryValue>} params A list of\n * parameters to update. If null or undefined, the param will be removed.\n * @return {string} An updated URI where the query data has been updated with\n * the params.\n */\ngoog.uri.utils.setParamsFromMap = function(uri, params) {\n 'use strict';\n var parts = goog.uri.utils.splitQueryData_(uri);\n var queryData = parts[1];\n var buffer = [];\n if (queryData) {\n queryData.split('&').forEach(function(pair) {\n 'use strict';\n var indexOfEquals = pair.indexOf('=');\n var name = indexOfEquals >= 0 ? pair.substr(0, indexOfEquals) : pair;\n if (!params.hasOwnProperty(name)) {\n buffer.push(pair);\n }\n });\n }\n parts[1] = goog.uri.utils.appendQueryData_(\n buffer.join('&'), goog.uri.utils.buildQueryDataFromMap(params));\n return goog.uri.utils.joinQueryData_(parts);\n};\n\n\n/**\n * Generates a URI path using a given URI and a path with checks to\n * prevent consecutive \"//\". The baseUri passed in must not contain\n * query or fragment identifiers. The path to append may not contain query or\n * fragment identifiers.\n *\n * @param {string} baseUri URI to use as the base.\n * @param {string} path Path to append.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.appendPath = function(baseUri, path) {\n 'use strict';\n goog.uri.utils.assertNoFragmentsOrQueries_(baseUri);\n\n // Remove any trailing '/'\n if (goog.string.endsWith(baseUri, '/')) {\n baseUri = baseUri.substr(0, baseUri.length - 1);\n }\n // Remove any leading '/'\n if (goog.string.startsWith(path, '/')) {\n path = path.substr(1);\n }\n return '' + baseUri + '/' + path;\n};\n\n\n/**\n * Replaces the path.\n * @param {string} uri URI to use as the base.\n * @param {string} path New path.\n * @return {string} Updated URI.\n */\ngoog.uri.utils.setPath = function(uri, path) {\n 'use strict';\n // Add any missing '/'.\n if (!goog.string.startsWith(path, '/')) {\n path = '/' + path;\n }\n var parts = goog.uri.utils.split(uri);\n return goog.uri.utils.buildFromEncodedParts(\n parts[goog.uri.utils.ComponentIndex.SCHEME],\n parts[goog.uri.utils.ComponentIndex.USER_INFO],\n parts[goog.uri.utils.ComponentIndex.DOMAIN],\n parts[goog.uri.utils.ComponentIndex.PORT], path,\n parts[goog.uri.utils.ComponentIndex.QUERY_DATA],\n parts[goog.uri.utils.ComponentIndex.FRAGMENT]);\n};\n\n\n/**\n * Standard supported query parameters.\n * @enum {string}\n */\ngoog.uri.utils.StandardQueryParam = {\n\n /** Unused parameter for unique-ifying. */\n RANDOM: 'zx'\n};\n\n\n/**\n * Sets the zx parameter of a URI to a random value.\n * @param {string} uri Any URI.\n * @return {string} That URI with the \"zx\" parameter added or replaced to\n * contain a random string.\n */\ngoog.uri.utils.makeUnique = function(uri) {\n 'use strict';\n return goog.uri.utils.setParam(\n uri, goog.uri.utils.StandardQueryParam.RANDOM,\n goog.string.getRandomString());\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Interface and shared data structures for implementing\n * different wire protocol versions.\n */\ngoog.provide('goog.labs.net.webChannel.Wire');\ngoog.provide('goog.labs.net.webChannel.Wire.QueuedMap');\n\n\n\ngoog.require('goog.collections.maps');\n\n\n\n/**\n * The interface class.\n * @interface\n */\ngoog.labs.net.webChannel.Wire = class {\n constructor() {}\n};\n\n\n/**\n * The latest protocol version that this class supports. We request this version\n * from the server when opening the connection. Should match\n * LATEST_CHANNEL_VERSION on the server code.\n * @type {number}\n */\ngoog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION = 8;\n\n\n/**\n * The JSON field key for the raw data wrapper object.\n * @type {string}\n */\ngoog.labs.net.webChannel.Wire.RAW_DATA_KEY = '__data__';\n\n\n\n/**\n * Simple container class for a (mapId, map) pair.\n */\ngoog.labs.net.webChannel.Wire.QueuedMap = class {\n /**\n * @param {number} mapId The id for this map.\n * @param {!Object|!goog.collections.maps.MapLike} map The map itself.\n * @param {!Object=} opt_context The context associated with the map.\n */\n constructor(mapId, map, opt_context) {\n 'use strict';\n /**\n * The id for this map.\n * @type {number}\n */\n this.mapId = mapId;\n\n /**\n * The map itself.\n * @type {!Object|!goog.collections.maps.MapLike}\n */\n this.map = map;\n\n /**\n * The context for the map.\n * @type {Object}\n */\n this.context = opt_context || null;\n }\n\n /**\n * @return {number|undefined} the size of the raw JSON message or\n * undefined if the message is not encoded as a raw JSON message\n */\n getRawDataSize() {\n 'use strict';\n if (goog.labs.net.webChannel.Wire.RAW_DATA_KEY in this.map) {\n const data = this.map[goog.labs.net.webChannel.Wire.RAW_DATA_KEY];\n if (typeof data === 'string') {\n return data.length;\n }\n }\n\n return undefined;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utilities for creating functions. Loosely inspired by these\n * java classes from the Guava library:\n * com.google.common.base.Functions\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Functions.html\n *\n * com.google.common.base.Predicates\n * https://google.github.io/guava/releases/snapshot-jre/api/docs/index.html?com/google/common/base/Predicates.html\n *\n * More about these can be found at\n * https://github.com/google/guava/wiki/FunctionalExplained\n */\n\n\ngoog.provide('goog.functions');\n\n\n/**\n * Creates a function that always returns the same value.\n * @param {T} retValue The value to return.\n * @return {function():T} The new function.\n * @template T\n */\ngoog.functions.constant = function(retValue) {\n 'use strict';\n return function() {\n 'use strict';\n return retValue;\n };\n};\n\n\n/**\n * Always returns false.\n * @type {function(...): boolean}\n */\ngoog.functions.FALSE = function() {\n 'use strict';\n return false;\n};\n\n\n/**\n * Always returns true.\n * @type {function(...): boolean}\n */\ngoog.functions.TRUE = function() {\n 'use strict';\n return true;\n};\n\n\n/**\n * Always returns `null`.\n * @type {function(...): null}\n */\ngoog.functions.NULL = function() {\n 'use strict';\n return null;\n};\n\n\n/**\n * Always returns `undefined`.\n * @type {function(...): undefined}\n */\ngoog.functions.UNDEFINED = function() {\n return undefined;\n};\n\n/**\n * Always returns `undefined` (loosely-typed version).\n * @type {!Function}\n */\ngoog.functions.EMPTY = /** @type {?} */ (goog.functions.UNDEFINED);\n\n\n/**\n * A simple function that returns the first argument of whatever is passed\n * into it.\n * @param {T=} opt_returnValue The single value that will be returned.\n * @param {...*} var_args Optional trailing arguments. These are ignored.\n * @return {T} The first argument passed in, or undefined if nothing was passed.\n * @template T\n */\ngoog.functions.identity = function(opt_returnValue, var_args) {\n 'use strict';\n return opt_returnValue;\n};\n\n\n/**\n * Creates a function that always throws an error with the given message.\n * @param {string} message The error message.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.error = function(message) {\n 'use strict';\n return function() {\n 'use strict';\n throw new Error(message);\n };\n};\n\n\n/**\n * Creates a function that throws the given object.\n * @param {*} err An object to be thrown.\n * @return {!Function} The error-throwing function.\n */\ngoog.functions.fail = function(err) {\n 'use strict';\n return function() {\n 'use strict';\n throw err;\n };\n};\n\n\n/**\n * Given a function, create a function that keeps opt_numArgs arguments and\n * silently discards all additional arguments.\n * @param {Function} f The original function.\n * @param {number=} opt_numArgs The number of arguments to keep. Defaults to 0.\n * @return {!Function} A version of f that only keeps the first opt_numArgs\n * arguments.\n */\ngoog.functions.lock = function(f, opt_numArgs) {\n 'use strict';\n opt_numArgs = opt_numArgs || 0;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return f.apply(self, Array.prototype.slice.call(arguments, 0, opt_numArgs));\n };\n};\n\n\n/**\n * Creates a function that returns its nth argument.\n * @param {number} n The position of the return argument.\n * @return {!Function} A new function.\n */\ngoog.functions.nth = function(n) {\n 'use strict';\n return function() {\n 'use strict';\n return arguments[n];\n };\n};\n\n\n/**\n * Like goog.partial(), except that arguments are added after arguments to the\n * returned function.\n *\n * Usage:\n * function f(arg1, arg2, arg3, arg4) { ... }\n * var g = goog.functions.partialRight(f, arg3, arg4);\n * g(arg1, arg2);\n *\n * @param {!Function} fn A function to partially apply.\n * @param {...*} var_args Additional arguments that are partially applied to fn\n * at the end.\n * @return {!Function} A partially-applied form of the function goog.partial()\n * was invoked as a method of.\n */\ngoog.functions.partialRight = function(fn, var_args) {\n 'use strict';\n const rightArgs = Array.prototype.slice.call(arguments, 1);\n return function() {\n 'use strict';\n // Even in strict mode, IE10/11 and Edge (non-Chromium) use global context\n // when free-calling functions. To catch cases where people were using this\n // erroneously, we explicitly change the context to undefined to match\n // strict mode specifications.\n let self = /** @type {*} */ (this);\n if (self === goog.global) {\n self = undefined;\n }\n const newArgs = Array.prototype.slice.call(arguments);\n newArgs.push.apply(newArgs, rightArgs);\n return fn.apply(self, newArgs);\n };\n};\n\n\n/**\n * Given a function, create a new function that swallows its return value\n * and replaces it with a new one.\n * @param {Function} f A function.\n * @param {T} retValue A new return value.\n * @return {function(...?):T} A new function.\n * @template T\n */\ngoog.functions.withReturnValue = function(f, retValue) {\n 'use strict';\n return goog.functions.sequence(f, goog.functions.constant(retValue));\n};\n\n\n/**\n * Creates a function that returns whether its argument equals the given value.\n *\n * Example:\n * var key = goog.object.findKey(obj, goog.functions.equalTo('needle'));\n *\n * @param {*} value The value to compare to.\n * @param {boolean=} opt_useLooseComparison Whether to use a loose (==)\n * comparison rather than a strict (===) one. Defaults to false.\n * @return {function(*):boolean} The new function.\n */\ngoog.functions.equalTo = function(value, opt_useLooseComparison) {\n 'use strict';\n return function(other) {\n 'use strict';\n return opt_useLooseComparison ? (value == other) : (value === other);\n };\n};\n\n\n/**\n * Creates the composition of the functions passed in.\n * For example, (goog.functions.compose(f, g))(a) is equivalent to f(g(a)).\n * @param {function(...?):T} fn The final function.\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):T} The composition of all inputs.\n * @template T\n */\ngoog.functions.compose = function(fn, var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n if (length) {\n result = functions[length - 1].apply(self, arguments);\n }\n\n for (let i = length - 2; i >= 0; i--) {\n result = functions[i].call(self, result);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that calls the functions passed in in sequence, and\n * returns the value of the last function. For example,\n * (goog.functions.sequence(f, g))(x) is equivalent to f(x),g(x).\n * @param {...Function} var_args A list of functions.\n * @return {!Function} A function that calls all inputs in sequence.\n */\ngoog.functions.sequence = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n let result;\n for (let i = 0; i < length; i++) {\n result = functions[i].apply(self, arguments);\n }\n return result;\n };\n};\n\n\n/**\n * Creates a function that returns true if each of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns false.\n * For example, (goog.functions.and(f, g))(x) is equivalent to f(x) && g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ANDs its component\n * functions.\n */\ngoog.functions.and = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (!functions[i].apply(self, arguments)) {\n return false;\n }\n }\n return true;\n };\n};\n\n\n/**\n * Creates a function that returns true if any of its components evaluates\n * to true. The components are evaluated in order, and the evaluation will be\n * short-circuited as soon as a function returns true.\n * For example, (goog.functions.or(f, g))(x) is equivalent to f(x) || g(x).\n * @param {...Function} var_args A list of functions.\n * @return {function(...?):boolean} A function that ORs its component\n * functions.\n */\ngoog.functions.or = function(var_args) {\n 'use strict';\n const functions = arguments;\n const length = functions.length;\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n for (let i = 0; i < length; i++) {\n if (functions[i].apply(self, arguments)) {\n return true;\n }\n }\n return false;\n };\n};\n\n\n/**\n * Creates a function that returns the Boolean opposite of a provided function.\n * For example, (goog.functions.not(f))(x) is equivalent to !f(x).\n * @param {!Function} f The original function.\n * @return {function(...?):boolean} A function that delegates to f and returns\n * opposite.\n */\ngoog.functions.not = function(f) {\n 'use strict';\n return function() {\n 'use strict';\n const self = /** @type {*} */ (this);\n return !f.apply(self, arguments);\n };\n};\n\n\n/**\n * Generic factory function to construct an object given the constructor\n * and the arguments. Intended to be bound to create object factories.\n *\n * Example:\n *\n * var factory = goog.partial(goog.functions.create, Class);\n *\n * @param {function(new:T, ...)} constructor The constructor for the Object.\n * @param {...*} var_args The arguments to be passed to the constructor.\n * @return {T} A new instance of the class given in `constructor`.\n * @template T\n * @deprecated This function does not work with ES6 class constructors. Use\n * arrow functions + spread args instead.\n */\ngoog.functions.create = function(constructor, var_args) {\n 'use strict';\n /**\n * @constructor\n * @final\n */\n const temp = function() {};\n temp.prototype = constructor.prototype;\n\n // obj will have constructor's prototype in its chain and\n // 'obj instanceof constructor' will be true.\n const obj = new temp();\n\n // obj is initialized by constructor.\n // arguments is only array-like so lacks shift(), but can be used with\n // the Array prototype function.\n constructor.apply(obj, Array.prototype.slice.call(arguments, 1));\n return obj;\n};\n\n\n/**\n * @define {boolean} Whether the return value cache should be used.\n * This should only be used to disable caches when testing.\n */\ngoog.functions.CACHE_RETURN_VALUE =\n goog.define('goog.functions.CACHE_RETURN_VALUE', true);\n\n\n/**\n * Gives a wrapper function that caches the return value of a parameterless\n * function when first called.\n *\n * When called for the first time, the given function is called and its\n * return value is cached (thus this is only appropriate for idempotent\n * functions). Subsequent calls will return the cached return value. This\n * allows the evaluation of expensive functions to be delayed until first used.\n *\n * To cache the return values of functions with parameters, see goog.memoize.\n *\n * @param {function():T} fn A function to lazily evaluate.\n * @return {function():T} A wrapped version the function.\n * @template T\n */\ngoog.functions.cacheReturnValue = function(fn) {\n 'use strict';\n let called = false;\n let value;\n\n return function() {\n 'use strict';\n if (!goog.functions.CACHE_RETURN_VALUE) {\n return fn();\n }\n\n if (!called) {\n value = fn();\n called = true;\n }\n\n return value;\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once. All\n * additional calls are no-ops.\n *\n * This is particularly useful for initialization functions\n * that should be called, at most, once.\n *\n * @param {function():*} f Function to call.\n * @return {function():undefined} Wrapped function.\n */\ngoog.functions.once = function(f) {\n 'use strict';\n // Keep a reference to the function that we null out when we're done with\n // it -- that way, the function can be GC'd when we're done with it.\n let inner = f;\n return function() {\n 'use strict';\n if (inner) {\n const tmp = inner;\n inner = null;\n tmp();\n }\n };\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the Nth call will go through.\n *\n * This is particularly useful for batching up repeated actions where the\n * last action should win. This can be used, for example, for refreshing an\n * autocomplete pop-up every so often rather than updating with every keystroke,\n * since the final text typed by the user is the one that should produce the\n * final autocomplete results. For more stateful debouncing with support for\n * pausing, resuming, and canceling debounced actions, use\n * `goog.async.Debouncer`.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to debounce. The function will\n * only be called after the full interval has elapsed since the last call.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.debounce = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n goog.global.clearTimeout(timeout);\n const args = arguments;\n timeout = goog.global.setTimeout(function() {\n 'use strict';\n f.apply(opt_scope, args);\n }, interval);\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times in\n * that interval, both the 1st and the Nth calls will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * the last action should win, but you also don't want to wait until the end of\n * the interval before sending a request out, as it leads to a perception of\n * slowness for the user.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to throttle. The function can\n * only be called once per interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.throttle = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n let shouldFire = false;\n let storedArgs = [];\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n if (shouldFire) {\n shouldFire = false;\n fire();\n }\n };\n\n const fire = function() {\n 'use strict';\n timeout = goog.global.setTimeout(handleTimeout, interval);\n let args = storedArgs;\n storedArgs = []; // Avoid a space leak by clearing stored arguments.\n f.apply(opt_scope, args);\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n storedArgs = arguments;\n if (!timeout) {\n fire();\n } else {\n shouldFire = true;\n }\n });\n};\n\n\n/**\n * Wraps a function to allow it to be called, at most, once per interval\n * (specified in milliseconds). If the wrapper function is called N times within\n * that interval, only the 1st call will go through.\n *\n * This is particularly useful for limiting repeated user requests where the\n * first request is guaranteed to have all the data required to perform the\n * final action, so there's no need to wait until the end of the interval before\n * sending the request out.\n *\n * @param {function(this:SCOPE, ...?)} f Function to call.\n * @param {number} interval Interval over which to rate-limit. The function will\n * only be called once per interval, and ignored for the remainer of the\n * interval.\n * @param {SCOPE=} opt_scope Object in whose scope to call the function.\n * @return {function(...?): undefined} Wrapped function.\n * @template SCOPE\n */\ngoog.functions.rateLimit = function(f, interval, opt_scope) {\n 'use strict';\n let timeout = 0;\n\n const handleTimeout = function() {\n 'use strict';\n timeout = 0;\n };\n\n return /** @type {function(...?)} */ (function(var_args) {\n 'use strict';\n if (!timeout) {\n timeout = goog.global.setTimeout(handleTimeout, interval);\n f.apply(opt_scope, arguments);\n }\n });\n};\n\n/**\n * Returns true if the specified value is a function.\n * @param {*} val Variable to test.\n * @return {boolean} Whether variable is a function.\n */\ngoog.functions.isFunction = (val) => {\n return typeof val === 'function';\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Defines a class for parsing JSON using the browser's built in\n * JSON library.\n */\n\ngoog.provide('goog.json.NativeJsonProcessor');\n\ngoog.require('goog.asserts');\ngoog.require('goog.json.Processor');\n\n\n\n/**\n * A class that parses and stringifies JSON using the browser's built-in JSON\n * library, if it is available.\n *\n * Note that the native JSON api has subtle differences across browsers, so\n * use this implementation with care. See json_test#assertSerialize\n * for details on the differences from goog.json.\n *\n * This implementation is signficantly faster than goog.json, at least on\n * Chrome. See json_perf.html for a perf test showing the difference.\n *\n * @param {?goog.json.Replacer=} opt_replacer An optional replacer to use during\n * serialization.\n * @param {?goog.json.Reviver=} opt_reviver An optional reviver to use during\n * parsing.\n * @constructor\n * @implements {goog.json.Processor}\n * @final\n */\ngoog.json.NativeJsonProcessor = function(opt_replacer, opt_reviver) {\n 'use strict';\n goog.asserts.assert(goog.global['JSON'] !== undefined, 'JSON not defined');\n\n /**\n * @type {goog.json.Replacer|null|undefined}\n * @private\n */\n this.replacer_ = opt_replacer;\n\n /**\n * @type {goog.json.Reviver|null|undefined}\n * @private\n */\n this.reviver_ = opt_reviver;\n};\n\n\n/** @override */\ngoog.json.NativeJsonProcessor.prototype.stringify = function(object) {\n 'use strict';\n return goog.global['JSON'].stringify(object, this.replacer_);\n};\n\n\n/** @override */\ngoog.json.NativeJsonProcessor.prototype.parse = function(s) {\n 'use strict';\n return goog.global['JSON'].parse(s, this.reviver_);\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Utility functions for managing networking, such as\n * testing network connectivity.\n *\n */\n\n\ngoog.provide('goog.labs.net.webChannel.netUtils');\n\ngoog.require('goog.Uri');\ngoog.require('goog.labs.net.webChannel.WebChannelDebug');\n\ngoog.scope(function() {\n'use strict';\nconst netUtils = goog.labs.net.webChannel.netUtils;\nconst WebChannelDebug = goog.labs.net.webChannel.WebChannelDebug;\n\n\n/**\n * Default timeout to allow for URI pings.\n * @type {number}\n */\nnetUtils.NETWORK_TIMEOUT = 10000;\n\n\n/**\n * Pings the network with an image URI to check if an error is a server error\n * or user's network error.\n *\n * The caller needs to add a 'rand' parameter to make sure the response is\n * not fulfilled by browser cache.\n *\n * @param {function(boolean)} callback The function to call back with results.\n * @param {goog.Uri=} opt_imageUri The URI (of an image) to use for the network\n * test.\n */\nnetUtils.testNetwork = function(callback, opt_imageUri) {\n 'use strict';\n let uri = opt_imageUri;\n if (!uri) {\n // default google.com image\n uri = new goog.Uri('//www.google.com/images/cleardot.gif');\n\n if (!(goog.global.location && goog.global.location.protocol == 'http')) {\n uri.setScheme('https'); // e.g. chrome-extension\n }\n uri.makeUnique();\n }\n\n netUtils.testLoadImage(uri.toString(), netUtils.NETWORK_TIMEOUT, callback);\n};\n\n\n/**\n * Test loading the given image, retrying if necessary.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @param {number} retries The number of times to retry.\n * @param {!WebChannelDebug} channelDebug The debug object\n * @param {number=} opt_pauseBetweenRetriesMS Optional number of milliseconds\n * between retries - defaults to 0.\n */\nnetUtils.testLoadImageWithRetries = function(\n url, timeout, callback, retries, channelDebug, opt_pauseBetweenRetriesMS) {\n 'use strict';\n channelDebug.debug('TestLoadImageWithRetries: ' + opt_pauseBetweenRetriesMS);\n if (retries == 0) {\n // no more retries, give up\n callback(false);\n return;\n }\n\n const pauseBetweenRetries = opt_pauseBetweenRetriesMS || 0;\n retries--;\n netUtils.testLoadImage(url, timeout, function(succeeded) {\n 'use strict';\n if (succeeded) {\n callback(true);\n } else {\n // try again\n goog.global.setTimeout(function() {\n 'use strict';\n netUtils.testLoadImageWithRetries(\n url, timeout, callback, retries, channelDebug, pauseBetweenRetries);\n }, pauseBetweenRetries);\n }\n });\n};\n\n\n/**\n * Test loading the given image.\n * @param {string} url URL to the image.\n * @param {number} timeout Milliseconds before giving up.\n * @param {function(boolean)} callback Function to call with results.\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.testLoadImage = function(url, timeout, callback) {\n 'use strict';\n const channelDebug = new WebChannelDebug();\n channelDebug.debug('TestLoadImage: loading ' + url);\n if (goog.global.Image) {\n const img = new Image();\n img.onload = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: loaded',\n true, callback);\n img.onerror = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: error',\n false, callback);\n img.onabort = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: abort',\n false, callback);\n img.ontimeout = goog.partial(\n netUtils.imageCallback_, channelDebug, img, 'TestLoadImage: timeout',\n false, callback);\n\n goog.global.setTimeout(function() {\n 'use strict';\n if (img.ontimeout) {\n img.ontimeout();\n }\n }, timeout);\n img.src = url;\n } else {\n // log ERROR_OTHER from environements where Image is not supported\n callback(false);\n }\n};\n\n\n/**\n * Wrap the image callback with debug and cleanup logic.\n * @param {!WebChannelDebug} channelDebug The WebChannelDebug object.\n * @param {!Image} img The image element.\n * @param {string} debugText The debug text.\n * @param {boolean} result The result of image loading.\n * @param {function(boolean)} callback The image callback.\n * @private\n */\nnetUtils.imageCallback_ = function(\n channelDebug, img, debugText, result, callback) {\n 'use strict';\n try {\n channelDebug.debug(debugText);\n netUtils.clearImageCallbacks_(img);\n callback(result);\n } catch (e) {\n channelDebug.dumpException(e);\n }\n};\n\n\n/**\n * Clears handlers to avoid memory leaks.\n * @param {Image} img The image to clear handlers from.\n * @private\n * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration\n */\nnetUtils.clearImageCallbacks_ = function(img) {\n 'use strict';\n img.onload = null;\n img.onerror = null;\n img.onabort = null;\n img.ontimeout = null;\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\ngoog.provide('goog.net.FetchXmlHttp');\ngoog.provide('goog.net.FetchXmlHttpFactory');\n\ngoog.require('goog.asserts');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.functions');\ngoog.require('goog.log');\ngoog.require('goog.net.XhrLike');\ngoog.require('goog.net.XmlHttpFactory');\n\n\n\n/**\n * @record\n */\ngoog.net.FetchXmlHttpFactoryOptions = function() {\n /**\n * @type {!WorkerGlobalScope|undefined} The Service Worker global scope.\n */\n this.worker;\n\n /**\n * @type {boolean|undefined} Whether to store the FetchXmlHttp response as an\n * array of Uint8Arrays. If this is true then the 'responseType' attribute\n * must be empty.\n */\n this.streamBinaryChunks;\n};\n\n\n\n/**\n * Factory for creating Xhr objects that uses the native fetch() method.\n * https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API\n * @param {!goog.net.FetchXmlHttpFactoryOptions} opts\n * @extends {goog.net.XmlHttpFactory}\n * @struct\n * @constructor\n */\ngoog.net.FetchXmlHttpFactory = function(opts) {\n 'use strict';\n goog.net.FetchXmlHttpFactory.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = opts.worker || null;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = opts.streamBinaryChunks || false;\n\n /** @private {!RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {!RequestCache|undefined} */\n this.cacheMode_ = undefined;\n};\ngoog.inherits(goog.net.FetchXmlHttpFactory, goog.net.XmlHttpFactory);\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.createInstance = function() {\n 'use strict';\n const instance =\n new goog.net.FetchXmlHttp(this.worker_, this.streamBinaryChunks_);\n if (this.credentialsMode_) {\n instance.setCredentialsMode(this.credentialsMode_);\n }\n if (this.cacheMode_) {\n instance.setCacheMode(this.cacheMode_);\n }\n return instance;\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttpFactory.prototype.internalGetOptions =\n goog.functions.constant({});\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCredentialsMode = function(\n credentialsMode) {\n 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttpFactory.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n\n/**\n * FetchXmlHttp object constructor.\n * @param {?WorkerGlobalScope} worker\n * @param {boolean} streamBinaryChunks\n * @extends {goog.events.EventTarget}\n * @implements {goog.net.XhrLike}\n * @constructor\n * @struct\n */\ngoog.net.FetchXmlHttp = function(worker, streamBinaryChunks) {\n 'use strict';\n goog.net.FetchXmlHttp.base(this, 'constructor');\n\n /** @private @final {?WorkerGlobalScope} */\n this.worker_ = worker;\n\n /** @private @final {boolean} */\n this.streamBinaryChunks_ = streamBinaryChunks;\n\n /** @private {RequestCredentials|undefined} */\n this.credentialsMode_ = undefined;\n\n /** @private {RequestCache|undefined} */\n this.cacheMode_ = undefined;\n\n /**\n * Request state.\n * @type {goog.net.FetchXmlHttp.RequestState}\n */\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n\n /**\n * HTTP status.\n * @type {number}\n */\n this.status = 0;\n\n /**\n * HTTP status string.\n * @type {string}\n */\n this.statusText = '';\n\n /**\n * Content of the response.\n * @type {string|!ArrayBuffer|!Array<!Uint8Array>}\n */\n this.response = '';\n\n /**\n * Content of the response.\n * @type {string}\n */\n this.responseText = '';\n\n /**\n * The type of the response. If this is set to 'arraybuffer' the request will\n * be discrete, streaming is only supported for text encoded requests.\n * @type {string}\n */\n this.responseType = '';\n\n /**\n * Document response entity body.\n * NOTE: This is always null and not supported by this class.\n * @final {null}\n */\n this.responseXML = null;\n\n /**\n * Method to call when the state changes.\n * @type {?function()}\n */\n this.onreadystatechange = null;\n\n /** @private {!Headers} */\n this.requestHeaders_ = new Headers();\n\n /** @private {?Headers} */\n this.responseHeaders_ = null;\n\n /**\n * Request method (GET or POST).\n * @private {string}\n */\n this.method_ = 'GET';\n\n /**\n * Request URL.\n * @private {string}\n */\n this.url_ = '';\n\n /**\n * Whether the request is in progress.\n * @private {boolean}\n */\n this.inProgress_ = false;\n\n /** @private @final {?goog.log.Logger} */\n this.logger_ = goog.log.getLogger('goog.net.FetchXmlHttp');\n\n /** @private {?Response} */\n this.fetchResponse_ = null;\n\n /** @private {!ReadableStreamDefaultReader|null} */\n this.currentReader_ = null;\n\n /** @private {?TextDecoder} */\n this.textDecoder_ = null;\n};\ngoog.inherits(goog.net.FetchXmlHttp, goog.events.EventTarget);\n\n\n/**\n * State of the requests.\n * @enum {number}\n */\ngoog.net.FetchXmlHttp.RequestState = {\n UNSENT: 0,\n OPENED: 1,\n HEADER_RECEIVED: 2,\n LOADING: 3,\n DONE: 4,\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.open = function(method, url, opt_async) {\n 'use strict';\n goog.asserts.assert(!!opt_async, 'Only async requests are supported.');\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.UNSENT) {\n this.abort();\n throw new Error('Error reopening a connection');\n }\n\n this.method_ = method;\n this.url_ = url;\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.OPENED;\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.send = function(opt_data) {\n 'use strict';\n if (this.readyState != goog.net.FetchXmlHttp.RequestState.OPENED) {\n this.abort();\n throw new Error('need to call open() first. ');\n }\n\n this.inProgress_ = true;\n const requestInit = {\n headers: this.requestHeaders_,\n method: this.method_,\n credentials: this.credentialsMode_,\n cache: this.cacheMode_,\n };\n if (opt_data) {\n requestInit['body'] = opt_data;\n }\n\n (this.worker_ || goog.global)\n .fetch(new Request(this.url_, /** @type {!RequestInit} */ (requestInit)))\n .then(\n this.handleResponse_.bind(this), this.handleSendFailure_.bind(this));\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.abort = function() {\n 'use strict';\n this.response = this.responseText = '';\n this.requestHeaders_ = new Headers();\n this.status = 0;\n\n if (!!this.currentReader_) {\n this.currentReader_.cancel('Request was aborted.')\n .catch(\n e => goog.log.warning(\n this.logger_, 'Fetch reader cancellation error.', e));\n }\n\n if (((this.readyState >= goog.net.FetchXmlHttp.RequestState.OPENED) &&\n this.inProgress_) &&\n (this.readyState != goog.net.FetchXmlHttp.RequestState.DONE)) {\n this.inProgress_ = false;\n this.requestDone_();\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.UNSENT;\n};\n\n\n/**\n * Handles the fetch response.\n * @param {!Response} response\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponse_ = function(response) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.fetchResponse_ = response;\n\n if (!this.responseHeaders_) {\n this.status = this.fetchResponse_.status;\n this.statusText = this.fetchResponse_.statusText;\n this.responseHeaders_ = response.headers;\n this.readyState = goog.net.FetchXmlHttp.RequestState.HEADER_RECEIVED;\n this.dispatchCallback_();\n }\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n this.readyState = goog.net.FetchXmlHttp.RequestState.LOADING;\n this.dispatchCallback_();\n // A callback may abort the request.\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.responseType === 'arraybuffer') {\n response.arrayBuffer().then(\n this.handleResponseArrayBuffer_.bind(this),\n this.handleSendFailure_.bind(this));\n } else if (\n typeof (goog.global.ReadableStream) !== 'undefined' &&\n 'body' in response) {\n this.currentReader_ =\n /** @type {!ReadableStreamDefaultReader} */ (response.body.getReader());\n if (this.streamBinaryChunks_) {\n if (this.responseType) {\n throw new Error(\n 'responseType must be empty for \"streamBinaryChunks\" mode responses.');\n }\n this.response = [];\n } else {\n this.response = this.responseText = '';\n this.textDecoder_ = new TextDecoder();\n }\n this.readInputFromFetch_();\n } else {\n response.text().then(\n this.handleResponseText_.bind(this),\n this.handleSendFailure_.bind(this));\n }\n};\n\n\n/**\n * Reads the next chunk of data from the fetch response.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.readInputFromFetch_ = function() {\n 'use strict';\n this.currentReader_.read()\n .then(this.handleDataFromStream_.bind(this))\n .catch(this.handleSendFailure_.bind(this));\n};\n\n\n/**\n * Handles a chunk of data from the fetch response stream reader.\n * @param {!IIterableResult} result\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleDataFromStream_ = function(result) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n\n if (this.streamBinaryChunks_ && result.value) {\n // When streamBinaryChunks_ is enabled, \"response\" is an array\n /** @type {!Array} */ (this.response)\n .push(/** @type {!Uint8Array} */ (result.value));\n } else if (!this.streamBinaryChunks_) {\n const dataPacket = result.value ?\n /** @type {!Uint8Array} */ (result.value) :\n new Uint8Array(0);\n const newText =\n this.textDecoder_.decode(dataPacket, {stream: !result.done});\n if (newText) {\n this.responseText += newText;\n this.response = this.responseText;\n }\n }\n if (result.done) {\n this.requestDone_();\n } else {\n this.dispatchCallback_();\n }\n\n if (this.readyState == goog.net.FetchXmlHttp.RequestState.LOADING) {\n this.readInputFromFetch_();\n }\n};\n\n/**\n * Handles the response text.\n * @param {string} responseText\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseText_ = function(responseText) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = this.responseText = responseText;\n this.requestDone_();\n};\n\n\n/**\n * Handles the response text.\n * @param {!ArrayBuffer} responseArrayBuffer\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_ = function(\n responseArrayBuffer) {\n 'use strict';\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.response = responseArrayBuffer;\n this.requestDone_();\n};\n\n\n/**\n * Handles the send failure.\n * @param {*} error\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.handleSendFailure_ = function(error) {\n 'use strict';\n const e = error instanceof Error ? error : Error(error);\n goog.log.warning(this.logger_, 'Failed to fetch url ' + this.url_, e);\n if (!this.inProgress_) {\n // The request was aborted, ignore.\n return;\n }\n this.requestDone_();\n};\n\n\n/**\n * Sets the request state to DONE and performs cleanup.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.requestDone_ = function() {\n 'use strict';\n this.readyState = goog.net.FetchXmlHttp.RequestState.DONE;\n\n this.fetchResponse_ = null;\n this.currentReader_ = null;\n this.textDecoder_ = null;\n\n this.dispatchCallback_();\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.setRequestHeader = function(header, value) {\n 'use strict';\n this.requestHeaders_.append(header, value);\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getResponseHeader = function(header) {\n 'use strict';\n // TODO(user): This method should return null when the headers are not\n // present or the specified header is missing. The externs need to be fixed.\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get response header but no headers have been received ' +\n 'for url: ' + this.url_);\n return '';\n }\n return this.responseHeaders_.get(header.toLowerCase()) || '';\n};\n\n\n/** @override */\ngoog.net.FetchXmlHttp.prototype.getAllResponseHeaders = function() {\n 'use strict';\n if (!this.responseHeaders_) {\n goog.log.warning(\n this.logger_,\n 'Attempting to get all response headers but no headers have been ' +\n 'received for url: ' + this.url_);\n return '';\n }\n const lines = [];\n const iter = this.responseHeaders_.entries();\n let entry = iter.next();\n while (!entry.done) {\n const pair = entry.value;\n lines.push(pair[0] + ': ' + pair[1]);\n entry = iter.next();\n }\n return lines.join('\\r\\n');\n};\n\n\n/**\n * @param {!RequestCredentials} credentialsMode The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCredentialsMode = function(credentialsMode) {\n 'use strict';\n this.credentialsMode_ = credentialsMode;\n};\n\n/**\n * @return {!RequestCredentials|undefined} The credentials mode of the\n * Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.getCredentialsMode = function() {\n 'use strict';\n return this.credentialsMode_;\n};\n\n/**\n * @param {!RequestCache} cacheMode The cache mode of the Service Worker fetch.\n */\ngoog.net.FetchXmlHttp.prototype.setCacheMode = function(cacheMode) {\n 'use strict';\n this.cacheMode_ = cacheMode;\n};\n\n\n/**\n * Dispatches the callback, if the callback attribute is defined.\n * @private\n */\ngoog.net.FetchXmlHttp.prototype.dispatchCallback_ = function() {\n 'use strict';\n if (this.onreadystatechange) {\n this.onreadystatechange.call(this);\n }\n};\n\n// Polyfill XmlHttpRequest's withCredentials property for specifying whether to\n// include credentials on cross domain requests.\nObject.defineProperty(goog.net.FetchXmlHttp.prototype, 'withCredentials', {\n get:\n /**\n * @this {goog.net.FetchXmlHttp}\n * @return {boolean} Whether to include credentials in cross domain\n * requests.\n */\n function() {\n 'use strict';\n return this.getCredentialsMode() === 'include';\n },\n\n set:\n /**\n * @param {boolean} value Whether to include credentials in cross domain\n * requests.\n * @this {goog.net.FetchXmlHttp}\n **/\n function(value) {\n 'use strict';\n this.setCredentialsMode(value ? 'include' : 'same-origin');\n }\n});\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n\n/**\n * @fileoverview Utility to attempt native JSON processing, falling back to\n * goog.json if not available.\n *\n * This is intended as a drop-in for current users of goog.json who want\n * to take advantage of native JSON if present.\n */\n\ngoog.provide('goog.json.hybrid');\n\ngoog.require('goog.asserts');\ngoog.require('goog.json');\n\n\n/**\n * Attempts to serialize the JSON string natively, falling back to\n * `goog.json.serialize` if unsuccessful.\n * @param {!Object} obj JavaScript object to serialize to JSON.\n * @return {string} Resulting JSON string.\n */\ngoog.json.hybrid.stringify = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['stringify'] :\n function(obj) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n return goog.global.JSON.stringify(obj);\n } catch (e) {\n // Native serialization failed. Fall through to retry with\n // goog.json.serialize.\n }\n }\n\n return goog.json.serialize(obj);\n };\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * the supplied `fallbackParser` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @param {function(string):Object} fallbackParser Fallback JSON parser used\n * if native\n * @return {?Object} Resulting JSON object.\n * @private\n */\ngoog.json.hybrid.parse_ = function(jsonString, fallbackParser) {\n 'use strict';\n if (goog.global.JSON) {\n try {\n var obj = goog.global.JSON.parse(jsonString);\n goog.asserts.assert(typeof obj == 'object');\n return /** @type {?Object} */ (obj);\n } catch (e) {\n // Native parse failed. Fall through to retry with goog.json.parse.\n }\n }\n\n return fallbackParser(jsonString);\n};\n\n\n/**\n * Attempts to parse the JSON string natively, falling back to\n * `goog.json.parse` if unsuccessful.\n * @param {string} jsonString JSON string to parse.\n * @return {?Object} Resulting JSON object.\n */\ngoog.json.hybrid.parse = goog.json.USE_NATIVE_JSON ?\n goog.global['JSON']['parse'] :\n function(jsonString) {\n 'use strict';\n return goog.json.hybrid.parse_(jsonString, goog.json.parse);\n };\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Constants for HTTP status codes.\n */\n\ngoog.provide('goog.net.HttpStatus');\n\n\n/**\n * HTTP Status Codes defined in RFC 2616, RFC 6585, RFC 4918 and RFC 7538.\n * @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html\n * @see http://tools.ietf.org/html/rfc6585\n * @see https://tools.ietf.org/html/rfc4918\n * @see https://tools.ietf.org/html/rfc7538\n * @enum {number}\n */\ngoog.net.HttpStatus = {\n // Informational 1xx\n CONTINUE: 100,\n SWITCHING_PROTOCOLS: 101,\n\n // Successful 2xx\n OK: 200,\n CREATED: 201,\n ACCEPTED: 202,\n NON_AUTHORITATIVE_INFORMATION: 203,\n NO_CONTENT: 204,\n RESET_CONTENT: 205,\n PARTIAL_CONTENT: 206,\n MULTI_STATUS: 207,\n\n // Redirection 3xx\n MULTIPLE_CHOICES: 300,\n MOVED_PERMANENTLY: 301,\n FOUND: 302,\n SEE_OTHER: 303,\n NOT_MODIFIED: 304,\n USE_PROXY: 305,\n TEMPORARY_REDIRECT: 307,\n PERMANENT_REDIRECT: 308,\n\n // Client Error 4xx\n BAD_REQUEST: 400,\n UNAUTHORIZED: 401,\n PAYMENT_REQUIRED: 402,\n FORBIDDEN: 403,\n NOT_FOUND: 404,\n METHOD_NOT_ALLOWED: 405,\n NOT_ACCEPTABLE: 406,\n PROXY_AUTHENTICATION_REQUIRED: 407,\n REQUEST_TIMEOUT: 408,\n CONFLICT: 409,\n GONE: 410,\n LENGTH_REQUIRED: 411,\n PRECONDITION_FAILED: 412,\n REQUEST_ENTITY_TOO_LARGE: 413,\n REQUEST_URI_TOO_LONG: 414,\n UNSUPPORTED_MEDIA_TYPE: 415,\n REQUEST_RANGE_NOT_SATISFIABLE: 416,\n EXPECTATION_FAILED: 417,\n UNPROCESSABLE_ENTITY: 422,\n LOCKED: 423,\n FAILED_DEPENDENCY: 424,\n PRECONDITION_REQUIRED: 428,\n TOO_MANY_REQUESTS: 429,\n REQUEST_HEADER_FIELDS_TOO_LARGE: 431,\n CLIENT_CLOSED_REQUEST: 499, // Nonstandard, used by GRPC\n\n // Server Error 5xx\n INTERNAL_SERVER_ERROR: 500,\n NOT_IMPLEMENTED: 501,\n BAD_GATEWAY: 502,\n SERVICE_UNAVAILABLE: 503,\n GATEWAY_TIMEOUT: 504,\n HTTP_VERSION_NOT_SUPPORTED: 505,\n INSUFFICIENT_STORAGE: 507,\n NETWORK_AUTHENTICATION_REQUIRED: 511,\n\n /*\n * IE returns this code for 204 due to its use of URLMon, which returns this\n * code for 'Operation Aborted'. The status text is 'Unknown', the response\n * headers are ''. Known to occur on IE 6 on XP through IE9 on Win7.\n */\n QUIRK_IE_NO_CONTENT: 1223,\n};\n\n\n/**\n * Returns whether the given status should be considered successful.\n *\n * Successful codes are OK (200), CREATED (201), ACCEPTED (202),\n * NO CONTENT (204), PARTIAL CONTENT (206), NOT MODIFIED (304),\n * and IE's no content code (1223).\n *\n * @param {number} status The status code to test.\n * @return {boolean} Whether the status code should be considered successful.\n */\ngoog.net.HttpStatus.isSuccess = function(status) {\n 'use strict';\n switch (status) {\n case goog.net.HttpStatus.OK:\n case goog.net.HttpStatus.CREATED:\n case goog.net.HttpStatus.ACCEPTED:\n case goog.net.HttpStatus.NO_CONTENT:\n case goog.net.HttpStatus.PARTIAL_CONTENT:\n case goog.net.HttpStatus.NOT_MODIFIED:\n case goog.net.HttpStatus.QUIRK_IE_NO_CONTENT:\n return true;\n\n default:\n return false;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Provides CORS support for HTTP based RPC requests.\n *\n * As part of net.rpc package, CORS features provided by this class\n * depend on the server support. Please check related specs to decide how\n * to enable any of the features provided by this class.\n */\n\ngoog.module('goog.net.rpc.HttpCors');\n\nconst GoogUri = goog.require('goog.Uri');\nconst googObject = goog.require('goog.object');\nconst googString = goog.require('goog.string');\nconst googUriUtils = goog.require('goog.uri.utils');\n\n\n/**\n * The default URL parameter name to overwrite http headers with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_HEADERS_PARAM_NAME = '$httpHeaders';\n\n\n/**\n * The default URL parameter name to overwrite http method with a URL param\n * to avoid CORS preflight.\n *\n * See https://github.com/whatwg/fetch/issues/210#issue-129531743 for the spec.\n *\n * @type {string}\n */\nexports.HTTP_METHOD_PARAM_NAME = '$httpMethod';\n\n\n/**\n * Generates the URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateHttpHeadersOverwriteParam = function(headers) {\n let result = '';\n googObject.forEach(headers, function(value, key) {\n result += key;\n result += ':';\n result += value;\n result += '\\r\\n';\n });\n return result;\n};\n\n\n/**\n * Generates the URL-encoded URL parameter value with custom headers encoded as\n * HTTP/1.1 headers block.\n *\n * @param {!Object<string, string>} headers The custom headers.\n * @return {string} The URL param to overwrite custom HTTP headers.\n */\nexports.generateEncodedHttpHeadersOverwriteParam = function(headers) {\n return googString.urlEncode(\n exports.generateHttpHeadersOverwriteParam(headers));\n};\n\n\n/**\n * Sets custom HTTP headers via an overwrite URL param.\n *\n * @param {!GoogUri|string} url The URI object or a string path.\n * @param {string} urlParam The URL param name.\n * @param {!Object<string, string>} extraHeaders The HTTP headers.\n * @return {!GoogUri|string} The URI object or a string path with headers\n * encoded as a url param.\n */\nexports.setHttpHeadersWithOverwriteParam = function(\n url, urlParam, extraHeaders) {\n if (googObject.isEmpty(extraHeaders)) {\n return url;\n }\n const httpHeaders = exports.generateHttpHeadersOverwriteParam(extraHeaders);\n if (typeof url === 'string') {\n return googUriUtils.appendParam(\n url, googString.urlEncode(urlParam), httpHeaders);\n } else {\n url.setParameterValue(urlParam, httpHeaders); // duplicate removed!\n return url;\n }\n};\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Implementation of a WebChannel transport using WebChannelBase.\n *\n * When WebChannelBase is used as the underlying transport, the capabilities\n * of the WebChannel are limited to what's supported by the implementation.\n * Particularly, multiplexing is not possible, and only strings are\n * supported as message types.\n */\n\ngoog.provide('goog.labs.net.webChannel.WebChannelBaseTransport');\n\ngoog.require('goog.asserts');\ngoog.require('goog.collections.maps');\ngoog.require('goog.events.EventTarget');\ngoog.require('goog.json');\ngoog.require('goog.labs.net.webChannel.ChannelRequest');\ngoog.require('goog.labs.net.webChannel.WebChannelBase');\ngoog.require('goog.labs.net.webChannel.Wire');\ngoog.require('goog.log');\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.net.WebChannelTransport');\ngoog.require('goog.object');\ngoog.require('goog.string');\n\n\n\n/**\n * Implementation of {@link goog.net.WebChannelTransport} with\n * {@link goog.labs.net.webChannel.WebChannelBase} as the underlying channel\n * implementation.\n *\n * @constructor\n * @struct\n * @implements {goog.net.WebChannelTransport}\n * @final\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport = function() {\n 'use strict';\n if (!goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming()) {\n throw new Error('Environmental error: no available transport.');\n }\n};\n\n\ngoog.scope(function() {\n'use strict';\nconst WebChannelBaseTransport =\n goog.labs.net.webChannel.WebChannelBaseTransport;\nconst WebChannelBase = goog.labs.net.webChannel.WebChannelBase;\nconst Wire = goog.labs.net.webChannel.Wire;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.prototype.createWebChannel = function(\n url, opt_options) {\n 'use strict';\n return new WebChannelBaseTransport.Channel(url, opt_options);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel} interface.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance.\n *\n * @constructor\n * @implements {goog.net.WebChannel}\n * @extends {goog.events.EventTarget}\n * @final\n */\nWebChannelBaseTransport.Channel = function(url, opt_options) {\n 'use strict';\n WebChannelBaseTransport.Channel.base(this, 'constructor');\n\n /**\n * @private {!WebChannelBase} The underlying channel object.\n */\n this.channel_ = new WebChannelBase(\n opt_options, goog.net.WebChannelTransport.CLIENT_VERSION);\n\n /**\n * @private {string} The URL of the target server end-point.\n */\n this.url_ = url;\n\n /**\n * @private {goog.log.Logger} The logger for this class.\n */\n this.logger_ =\n goog.log.getLogger('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n /**\n * @private {Object<string, string>} Extra URL parameters\n * to be added to each HTTP request.\n */\n this.messageUrlParams_ =\n (opt_options && opt_options.messageUrlParams) || null;\n\n let messageHeaders = (opt_options && opt_options.messageHeaders) || null;\n\n // default is false\n if (opt_options && opt_options.clientProtocolHeaderRequired) {\n if (messageHeaders) {\n goog.object.set(\n messageHeaders, goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n } else {\n messageHeaders = goog.object.create(\n goog.net.WebChannel.X_CLIENT_PROTOCOL,\n goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);\n }\n }\n\n this.channel_.setExtraHeaders(messageHeaders);\n\n let initHeaders = (opt_options && opt_options.initMessageHeaders) || null;\n\n if (opt_options && opt_options.messageContentType) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE,\n opt_options.messageContentType);\n }\n }\n\n if (opt_options && opt_options.clientProfile) {\n if (initHeaders) {\n goog.object.set(\n initHeaders, goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n } else {\n initHeaders = goog.object.create(\n goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE,\n opt_options.clientProfile);\n }\n }\n\n this.channel_.setInitHeaders(initHeaders);\n\n const httpHeadersOverwriteParam =\n opt_options && opt_options.httpHeadersOverwriteParam;\n if (httpHeadersOverwriteParam &&\n !goog.string.isEmptyOrWhitespace(httpHeadersOverwriteParam)) {\n this.channel_.setHttpHeadersOverwriteParam(httpHeadersOverwriteParam);\n }\n\n /**\n * @private {boolean} Whether to enable CORS.\n */\n this.supportsCrossDomainXhr_ =\n (opt_options && opt_options.supportsCrossDomainXhr) || false;\n\n /**\n * @private {boolean} Whether to send raw Json and bypass v8 wire format.\n */\n this.sendRawJson_ = (opt_options && opt_options.sendRawJson) || false;\n\n // Note that httpSessionIdParam will be ignored if the same parameter name\n // has already been specified with messageUrlParams\n const httpSessionIdParam = opt_options && opt_options.httpSessionIdParam;\n if (httpSessionIdParam &&\n !goog.string.isEmptyOrWhitespace(httpSessionIdParam)) {\n this.channel_.setHttpSessionIdParam(httpSessionIdParam);\n if (goog.object.containsKey(this.messageUrlParams_, httpSessionIdParam)) {\n goog.object.remove(this.messageUrlParams_, httpSessionIdParam);\n goog.log.warning(\n this.logger_,\n 'Ignore httpSessionIdParam also specified with messageUrlParams: ' +\n httpSessionIdParam);\n }\n }\n\n /**\n * The channel handler.\n *\n * @private {!WebChannelBaseTransport.Channel.Handler_}\n */\n this.channelHandler_ = new WebChannelBaseTransport.Channel.Handler_(this);\n};\ngoog.inherits(WebChannelBaseTransport.Channel, goog.events.EventTarget);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.open = function() {\n 'use strict';\n this.channel_.setHandler(this.channelHandler_);\n if (this.supportsCrossDomainXhr_) {\n this.channel_.setSupportsCrossDomainXhrs(true);\n }\n this.channel_.connect(this.url_, (this.messageUrlParams_ || undefined));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.close = function() {\n 'use strict';\n this.channel_.disconnect();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.halfClose = function() {\n 'use strict';\n // to be implemented\n throw new Error('Not implemented');\n};\n\n\n/**\n * The WebChannelBase only supports object types.\n *\n * @param {!goog.net.WebChannel.MessageData} message The message to send.\n *\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.send = function(message) {\n 'use strict';\n this.channel_.sendMap(this.messageToMapObject_(message));\n};\n\n\n/**\n * Converts a message to the map used by the underlying channel.\n *\n * @param {!goog.net.WebChannel.MessageData} message\n * @return {!Object|!goog.collections.maps.MapLike}\n */\nWebChannelBaseTransport.Channel.prototype.messageToMapObject_ = function(\n message) {\n 'use strict';\n goog.asserts.assert(\n goog.isObject(message) || typeof message === 'string',\n 'only object type or raw string is supported');\n\n if (typeof message === 'string') {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = message;\n return rawJson;\n }\n\n if (this.sendRawJson_) {\n const rawJson = {};\n rawJson[Wire.RAW_DATA_KEY] = goog.json.serialize(message);\n return rawJson;\n }\n\n return message;\n};\n\n\n/**\n * Converts the map used by the underlying channel to a message.\n *\n * NOTE: In the case of the message being JS Object or string, the exact same\n * object passed during `messageToMapObject_()` is returned. In the case of raw\n * JSON, an equal (but not the same) object is returned (due to serialization).\n *\n * @param {!Object|!goog.collections.maps.MapLike} map\n * @return {!goog.net.WebChannel.MessageData}\n */\nWebChannelBaseTransport.Channel.prototype.mapObjectToMessage_ = function(map) {\n 'use strict';\n if (Wire.RAW_DATA_KEY in map) {\n const rawMessage = map[Wire.RAW_DATA_KEY];\n\n if (this.sendRawJson_) {\n return /** @type {!goog.net.WebChannel.MessageData} */ (\n goog.json.parse(rawMessage));\n } else { // string message\n return rawMessage;\n }\n }\n\n return map;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.disposeInternal = function() {\n 'use strict';\n this.channel_.setHandler(null);\n delete this.channelHandler_;\n this.channel_.disconnect();\n delete this.channel_;\n\n WebChannelBaseTransport.Channel.base(this, 'disposeInternal');\n};\n\n\n\n/**\n * The message event.\n *\n * @param {!Array<?>|!Object} array The data array from the underlying channel.\n * @constructor\n * @extends {goog.net.WebChannel.MessageEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.MessageEvent = function(array) {\n 'use strict';\n WebChannelBaseTransport.Channel.MessageEvent.base(this, 'constructor');\n\n // single-metadata only\n const metadata = array['__sm__'];\n if (metadata) {\n this.metadataKey = goog.object.getAnyKey(metadata);\n if (this.metadataKey) {\n this.data = goog.object.get(metadata, this.metadataKey);\n } else {\n this.data = metadata; // empty\n }\n } else {\n this.data = array;\n }\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.MessageEvent,\n goog.net.WebChannel.MessageEvent);\n\n\n\n/**\n * The error event.\n *\n * @param {WebChannelBase.Error} error The error code.\n * @constructor\n * @extends {goog.net.WebChannel.ErrorEvent}\n * @final\n */\nWebChannelBaseTransport.Channel.ErrorEvent = function(error) {\n 'use strict';\n WebChannelBaseTransport.Channel.ErrorEvent.base(this, 'constructor');\n\n /**\n * High-level status code.\n */\n this.status = goog.net.WebChannel.ErrorStatus.NETWORK_ERROR;\n\n /**\n * @const {WebChannelBase.Error} Internal error code, for debugging use only.\n */\n this.errorCode = error;\n};\ngoog.inherits(\n WebChannelBaseTransport.Channel.ErrorEvent, goog.net.WebChannel.ErrorEvent);\n\n\n\n/**\n * Implementation of {@link WebChannelBase.Handler} interface.\n *\n * @param {!WebChannelBaseTransport.Channel} channel The enclosing WebChannel.\n *\n * @constructor\n * @extends {WebChannelBase.Handler}\n * @private\n */\nWebChannelBaseTransport.Channel.Handler_ = function(channel) {\n 'use strict';\n WebChannelBaseTransport.Channel.Handler_.base(this, 'constructor');\n\n /**\n * @type {!WebChannelBaseTransport.Channel}\n * @private\n */\n this.channel_ = channel;\n};\ngoog.inherits(WebChannelBaseTransport.Channel.Handler_, WebChannelBase.Handler);\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelOpened = function(\n channel) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel opened on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.OPEN);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray =\n function(channel, array) {\n 'use strict';\n goog.asserts.assert(array, 'array expected to be defined');\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.MessageEvent(array));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelError = function(\n channel, error) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_,\n 'WebChannel aborted on ' + this.channel_.url_ +\n ' due to channel error: ' + error);\n this.channel_.dispatchEvent(\n new WebChannelBaseTransport.Channel.ErrorEvent(error));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.Handler_.prototype.channelClosed = function(\n channel, opt_pendingMaps, opt_undeliveredMaps) {\n 'use strict';\n goog.log.info(\n this.channel_.logger_, 'WebChannel closed on ' + this.channel_.url_);\n this.channel_.dispatchEvent(goog.net.WebChannel.EventType.CLOSE);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.Channel.prototype.getRuntimeProperties = function() {\n 'use strict';\n return new WebChannelBaseTransport.ChannelProperties(this, this.channel_);\n};\n\n\n\n/**\n * Implementation of the {@link goog.net.WebChannel.RuntimeProperties}.\n *\n * @param {!WebChannelBaseTransport.Channel} transportChannel The transport\n * channel object.\n * @param {!WebChannelBase} channel The underlying channel object.\n *\n * @constructor\n * @implements {goog.net.WebChannel.RuntimeProperties}\n * @final\n */\nWebChannelBaseTransport.ChannelProperties = function(\n transportChannel, channel) {\n 'use strict';\n /**\n * The transport channel object.\n *\n * @private @const {!WebChannelBaseTransport.Channel}\n */\n this.transportChannel_ = transportChannel;\n\n /**\n * The underlying channel object.\n *\n * @private @const {!WebChannelBase}\n */\n this.channel_ = channel;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getConcurrentRequestLimit =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getMaxSize();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.isSpdyEnabled = function() {\n 'use strict';\n return this.getConcurrentRequestLimit() > 1;\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getPendingRequestCount =\n function() {\n 'use strict';\n return this.channel_.getForwardChannelRequestPool().getRequestCount();\n};\n\n\n/**\n * @override\n * @return {!Array<!goog.net.WebChannel.MessageData>}\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getNonAckedMessages =\n function() {\n 'use strict';\n return this.channel_.getNonAckedMaps().map(\n queued_map => this.transportChannel_.mapObjectToMessage_(queued_map.map));\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.getHttpSessionId =\n function() {\n 'use strict';\n return this.channel_.getHttpSessionId();\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.commit = function(\n callback) {\n 'use strict';\n this.channel_.setForwardChannelFlushCallback(callback);\n};\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.notifyNonAckedMessageCount =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.onCommit =\n goog.abstractMethod;\n\n\n/**\n * @override\n */\nWebChannelBaseTransport.ChannelProperties.prototype.ackCommit =\n goog.abstractMethod;\n\n\n/** @override */\nWebChannelBaseTransport.ChannelProperties.prototype.getLastStatusCode =\n function() {\n 'use strict';\n return this.channel_.getLastStatusCode();\n};\n}); // goog.scope\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Transport support for WebChannel.\n *\n * The <code>WebChannelTransport</code> implementation serves as the factory\n * for <code>WebChannel</code>, which offers an abstraction for\n * point-to-point socket-like communication similar to what BrowserChannel\n * or HTML5 WebSocket offers.\n */\n\ngoog.provide('goog.net.WebChannelTransport');\n\ngoog.requireType('goog.net.WebChannel');\ngoog.requireType('goog.net.WebChannel.Options');\n\n\n\n/**\n * A WebChannelTransport instance represents a shared context of logical\n * connectivity between a browser client and a remote origin.\n *\n * Over a single WebChannelTransport instance, multiple WebChannels may be\n * created against different URLs, which may all share the same\n * underlying connectivity (i.e. TCP connection) whenever possible.\n *\n * When multi-domains are supported, such as CORS, multiple origins may be\n * supported over a single WebChannelTransport instance at the same time.\n *\n * Sharing between different window contexts such as tabs is not addressed\n * by WebChannelTransport. Applications may choose HTML5 shared workers\n * or other techniques to access the same transport instance\n * across different window contexts.\n *\n * @interface\n */\ngoog.net.WebChannelTransport = function() {};\n\n\n/**\n * The client version. This integer value will be passed to the server\n * when a channel is opened to inform the server the client \"capabilities\".\n *\n * Wire protocol version is a different concept and is internal to the\n * transport implementation.\n *\n * @const\n * @type {number}\n */\ngoog.net.WebChannelTransport.CLIENT_VERSION = 22;\n\n\n/**\n * Create a new WebChannel instance.\n *\n * The new WebChannel is to be opened against the server-side resource\n * as specified by the given URL. See {@link goog.net.WebChannel} for detailed\n * semantics.\n *\n * @param {string} url The URL path for the new WebChannel instance.\n * @param {!goog.net.WebChannel.Options=} opt_options Configuration for the\n * new WebChannel instance. The configuration object is reusable after\n * the new channel instance is created.\n * @return {!goog.net.WebChannel} the newly created WebChannel instance.\n */\ngoog.net.WebChannelTransport.prototype.createWebChannel = goog.abstractMethod;\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Bring in closure-library dependencies\n */\n\ngoog.provide('firebase.webchannel.wrapper');\n\n// goog.net.WebChannelTransport\ngoog.require('goog.net.createWebChannelTransport');\ngoog.require('goog.net.FetchXmlHttpFactory');\ngoog.require('goog.labs.net.webChannel.requestStats');\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\n\n/**\n * NOTE: The `createWebChannel` function takes an options object as a second param\n * whose properties are typically mangled. We override these in externs/overrides.js\n * Without those externs, this does not function properly.\n */\ngoog.labs.net.webChannel.WebChannelBaseTransport.prototype['createWebChannel'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.prototype.createWebChannel;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['send'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.send;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['open'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.open;\ngoog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype['close'] =\n goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.close;\n\n// goog.net.ErrorCode\ngoog.require('goog.net.ErrorCode');\ngoog.net.ErrorCode['NO_ERROR'] = goog.net.ErrorCode.NO_ERROR;\ngoog.net.ErrorCode['TIMEOUT'] = goog.net.ErrorCode.TIMEOUT;\ngoog.net.ErrorCode['HTTP_ERROR'] = goog.net.ErrorCode.HTTP_ERROR;\n\n// goog.net.ErrorType\ngoog.require('goog.net.EventType');\ngoog.net.EventType['COMPLETE'] = goog.net.EventType.COMPLETE;\n\n// goog.net.WebChannel\ngoog.require('goog.net.WebChannel');\ngoog.require('goog.events.EventTarget');\ngoog.net.WebChannel['EventType'] = goog.net.WebChannel.EventType;\ngoog.net.WebChannel.EventType['OPEN'] = goog.net.WebChannel.EventType.OPEN;\ngoog.net.WebChannel.EventType['CLOSE'] = goog.net.WebChannel.EventType.CLOSE;\ngoog.net.WebChannel.EventType['ERROR'] = goog.net.WebChannel.EventType.ERROR;\ngoog.net.WebChannel.EventType['MESSAGE'] =\n goog.net.WebChannel.EventType.MESSAGE;\ngoog.events.EventTarget.prototype['listen'] =\n goog.events.EventTarget.prototype.listen;\n\ngoog.require('goog.net.XhrIo');\ngoog.net.XhrIo.prototype['listenOnce'] = goog.net.XhrIo.prototype.listenOnce;\ngoog.net.XhrIo.prototype['getLastError'] =\n goog.net.XhrIo.prototype.getLastError;\ngoog.net.XhrIo.prototype['getLastErrorCode'] =\n goog.net.XhrIo.prototype.getLastErrorCode;\ngoog.net.XhrIo.prototype['getStatus'] = goog.net.XhrIo.prototype.getStatus;\ngoog.net.XhrIo.prototype['getResponseJson'] =\n goog.net.XhrIo.prototype.getResponseJson;\ngoog.net.XhrIo.prototype['getResponseText'] =\n goog.net.XhrIo.prototype.getResponseText;\ngoog.net.XhrIo.prototype['send'] = goog.net.XhrIo.prototype.send;\ngoog.net.XhrIo.prototype['setWithCredentials'] =\n goog.net.XhrIo.prototype.setWithCredentials;\n\nmodule['exports']['createWebChannelTransport'] =\n goog.net.createWebChannelTransport;\nmodule['exports']['getStatEventTarget'] =\n goog.labs.net.webChannel.requestStats.getStatEventTarget;\nmodule['exports']['ErrorCode'] = goog.net.ErrorCode;\nmodule['exports']['EventType'] = goog.net.EventType;\nmodule['exports']['Event'] = goog.labs.net.webChannel.requestStats.Event;\nmodule['exports']['Stat'] = goog.labs.net.webChannel.requestStats.Stat;\nmodule['exports']['FetchXmlHttpFactory'] = goog.net.FetchXmlHttpFactory;\nmodule['exports']['WebChannel'] = goog.net.WebChannel;\nmodule['exports']['XhrIo'] = goog.net.XhrIo;\n","import { _getProvider, getApp as t, _removeServiceInstance as e, _registerComponent as n, registerVersion as s, SDK_VERSION as i } from \"@firebase/app\";\n\nimport { Component as r } from \"@firebase/component\";\n\nimport { Logger as o, LogLevel as u } from \"@firebase/logger\";\n\nimport { FirebaseError as c, getUA as a, isIndexedDBAvailable as h, isSafari as l, createMockUserToken as f, getModularInstance as d, deepEqual as _, getDefaultEmulatorHostnameAndPort as w } from \"@firebase/util\";\n\nimport { XhrIo as m, EventType as g, ErrorCode as y, createWebChannelTransport as p, getStatEventTarget as I, FetchXmlHttpFactory as T, WebChannel as E, Event as A, Stat as R } from \"@firebase/webchannel-wrapper\";\n\nconst b = \"@firebase/firestore\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nclass P {\n constructor(t) {\n this.uid = t;\n }\n isAuthenticated() {\n return null != this.uid;\n }\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */ toKey() {\n return this.isAuthenticated() ? \"uid:\" + this.uid : \"anonymous-user\";\n }\n isEqual(t) {\n return t.uid === this.uid;\n }\n}\n\n/** A user with a null UID. */ P.UNAUTHENTICATED = new P(null), \n// TODO(mikelehen): Look into getting a proper uid-equivalent for\n// non-FirebaseAuth providers.\nP.GOOGLE_CREDENTIALS = new P(\"google-credentials-uid\"), P.FIRST_PARTY = new P(\"first-party-uid\"), \nP.MOCK_USER = new P(\"mock-user\");\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nlet v = \"9.16.0\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nconst V = new o(\"@firebase/firestore\");\n\n// Helper methods are needed because variables can't be exported as read/write\nfunction S() {\n return V.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n * <ul>\n * <li>`debug` for the most verbose logging level, primarily for\n * debugging.</li>\n * <li>`error` to log errors only.</li>\n * <li><code>`silent` to turn off logging.</li>\n * </ul>\n */ function D(t) {\n V.setLogLevel(t);\n}\n\nfunction C(t, ...e) {\n if (V.logLevel <= u.DEBUG) {\n const n = e.map(k);\n V.debug(`Firestore (${v}): ${t}`, ...n);\n }\n}\n\nfunction x(t, ...e) {\n if (V.logLevel <= u.ERROR) {\n const n = e.map(k);\n V.error(`Firestore (${v}): ${t}`, ...n);\n }\n}\n\n/**\n * @internal\n */ function N(t, ...e) {\n if (V.logLevel <= u.WARN) {\n const n = e.map(k);\n V.warn(`Firestore (${v}): ${t}`, ...n);\n }\n}\n\n/**\n * Converts an additional log parameter to a string representation.\n */ function k(t) {\n if (\"string\" == typeof t) return t;\n try {\n return e = t, JSON.stringify(e);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return t;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /** Formats an object as a JSON string, suitable for logging. */\n var e;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Unconditionally fails, throwing an Error with the given message.\n * Messages are stripped in production builds.\n *\n * Returns `never` and can be used in expressions:\n * @example\n * let futureVar = fail('not implemented yet');\n */ function O(t = \"Unexpected state\") {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n const e = `FIRESTORE (${v}) INTERNAL ASSERTION FAILED: ` + t;\n // NOTE: We don't use FirestoreError here because these are internal failures\n // that cannot be handled by the user. (Also it would create a circular\n // dependency between the error and assert modules which doesn't work.)\n throw x(e), new Error(e);\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * Messages are stripped in production builds.\n */ function M(t, e) {\n t || O();\n}\n\n/**\n * Fails if the given assertion condition is false, throwing an Error with the\n * given message if it did.\n *\n * The code of callsites invoking this function are stripped out in production\n * builds. Any side-effects of code within the debugAssert() invocation will not\n * happen in this case.\n *\n * @internal\n */ function F(t, e) {\n t || O();\n}\n\n/**\n * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an\n * instance of `T` before casting.\n */ function $(t, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ne) {\n return t;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const B = {\n // Causes are copied from:\n // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n /** Not an error; returned on success. */\n OK: \"ok\",\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: \"cancelled\",\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: \"unknown\",\n /**\n * Client specified an invalid argument. Note that this differs from\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\n * problematic regardless of the state of the system (e.g., a malformed file\n * name).\n */\n INVALID_ARGUMENT: \"invalid-argument\",\n /**\n * Deadline expired before operation could complete. For operations that\n * change the state of the system, this error may be returned even if the\n * operation has completed successfully. For example, a successful response\n * from a server could have been delayed long enough for the deadline to\n * expire.\n */\n DEADLINE_EXCEEDED: \"deadline-exceeded\",\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: \"not-found\",\n /**\n * Some entity that we attempted to create (e.g., file or directory) already\n * exists.\n */\n ALREADY_EXISTS: \"already-exists\",\n /**\n * The caller does not have permission to execute the specified operation.\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\n * PERMISSION_DENIED must not be used if the caller can not be identified\n * (use UNAUTHENTICATED instead for those errors).\n */\n PERMISSION_DENIED: \"permission-denied\",\n /**\n * The request does not have valid authentication credentials for the\n * operation.\n */\n UNAUTHENTICATED: \"unauthenticated\",\n /**\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\n * entire file system is out of space.\n */\n RESOURCE_EXHAUSTED: \"resource-exhausted\",\n /**\n * Operation was rejected because the system is not in a state required for\n * the operation's execution. For example, directory to be deleted may be\n * non-empty, an rmdir operation is applied to a non-directory, etc.\n *\n * A litmus test that may help a service implementor in deciding\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\n * (b) Use ABORTED if the client should retry at a higher-level\n * (e.g., restarting a read-modify-write sequence).\n * (c) Use FAILED_PRECONDITION if the client should not retry until\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\n * fails because the directory is non-empty, FAILED_PRECONDITION\n * should be returned since the client should not retry unless\n * they have first fixed up the directory by deleting files from it.\n * (d) Use FAILED_PRECONDITION if the client performs conditional\n * REST Get/Update/Delete on a resource and the resource on the\n * server does not match the condition. E.g., conflicting\n * read-modify-write on the same resource.\n */\n FAILED_PRECONDITION: \"failed-precondition\",\n /**\n * The operation was aborted, typically due to a concurrency issue like\n * sequencer check failures, transaction aborts, etc.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n ABORTED: \"aborted\",\n /**\n * Operation was attempted past the valid range. E.g., seeking or reading\n * past end of file.\n *\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\n * if the system state changes. For example, a 32-bit file system will\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\n * an offset past the current file size.\n *\n * There is a fair bit of overlap between FAILED_PRECONDITION and\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\n * when it applies so that callers who are iterating through a space can\n * easily look for an OUT_OF_RANGE error to detect when they are done.\n */\n OUT_OF_RANGE: \"out-of-range\",\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: \"unimplemented\",\n /**\n * Internal errors. Means some invariants expected by underlying System has\n * been broken. If you see one of these errors, Something is very broken.\n */\n INTERNAL: \"internal\",\n /**\n * The service is currently unavailable. This is a most likely a transient\n * condition and may be corrected by retrying with a backoff.\n *\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\n * and UNAVAILABLE.\n */\n UNAVAILABLE: \"unavailable\",\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: \"data-loss\"\n};\n\n/** An error returned by a Firestore operation. */ class L extends c {\n /** @hideconstructor */\n constructor(\n /**\n * The backend error code associated with this error.\n */\n t, \n /**\n * A custom error description.\n */\n e) {\n super(t, e), this.code = t, this.message = e, \n // HACK: We write a toString property directly because Error is not a real\n // class and so inheritance does not work correctly. We could alternatively\n // do the same \"back-door inheritance\" trick that FirebaseError does.\n this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class q {\n constructor() {\n this.promise = new Promise(((t, e) => {\n this.resolve = t, this.reject = e;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class U {\n constructor(t, e) {\n this.user = e, this.type = \"OAuth\", this.headers = new Map, this.headers.set(\"Authorization\", `Bearer ${t}`);\n }\n}\n\n/**\n * A CredentialsProvider that always yields an empty token.\n * @internal\n */ class K {\n getToken() {\n return Promise.resolve(null);\n }\n invalidateToken() {}\n start(t, e) {\n // Fire with initial user.\n t.enqueueRetryable((() => e(P.UNAUTHENTICATED)));\n }\n shutdown() {}\n}\n\n/**\n * A CredentialsProvider that always returns a constant token. Used for\n * emulator token mocking.\n */ class G {\n constructor(t) {\n this.token = t, \n /**\n * Stores the listener registered with setChangeListener()\n * This isn't actually necessary since the UID never changes, but we use this\n * to verify the listen contract is adhered to in tests.\n */\n this.changeListener = null;\n }\n getToken() {\n return Promise.resolve(this.token);\n }\n invalidateToken() {}\n start(t, e) {\n this.changeListener = e, \n // Fire with initial user.\n t.enqueueRetryable((() => e(this.token.user)));\n }\n shutdown() {\n this.changeListener = null;\n }\n}\n\nclass Q {\n constructor(t) {\n this.t = t, \n /** Tracks the current User. */\n this.currentUser = P.UNAUTHENTICATED, \n /**\n * Counter used to detect if the token changed while a getToken request was\n * outstanding.\n */\n this.i = 0, this.forceRefresh = !1, this.auth = null;\n }\n start(t, e) {\n let n = this.i;\n // A change listener that prevents double-firing for the same token change.\n const s = t => this.i !== n ? (n = this.i, e(t)) : Promise.resolve();\n // A promise that can be waited on to block on the next token change.\n // This promise is re-created after each change.\n let i = new q;\n this.o = () => {\n this.i++, this.currentUser = this.u(), i.resolve(), i = new q, t.enqueueRetryable((() => s(this.currentUser)));\n };\n const r = () => {\n const e = i;\n t.enqueueRetryable((async () => {\n await e.promise, await s(this.currentUser);\n }));\n }, o = t => {\n C(\"FirebaseAuthCredentialsProvider\", \"Auth detected\"), this.auth = t, this.auth.addAuthTokenListener(this.o), \n r();\n };\n this.t.onInit((t => o(t))), \n // Our users can initialize Auth right after Firestore, so we give it\n // a chance to register itself with the component framework before we\n // determine whether to start up in unauthenticated mode.\n setTimeout((() => {\n if (!this.auth) {\n const t = this.t.getImmediate({\n optional: !0\n });\n t ? o(t) : (\n // If auth is still not available, proceed with `null` user\n C(\"FirebaseAuthCredentialsProvider\", \"Auth not yet detected\"), i.resolve(), i = new q);\n }\n }), 0), r();\n }\n getToken() {\n // Take note of the current value of the tokenCounter so that this method\n // can fail (with an ABORTED error) if there is a token change while the\n // request is outstanding.\n const t = this.i, e = this.forceRefresh;\n return this.forceRefresh = !1, this.auth ? this.auth.getToken(e).then((e => \n // Cancel the request since the token changed while the request was\n // outstanding so the response is potentially for a previous user (which\n // user, we can't be sure).\n this.i !== t ? (C(\"FirebaseAuthCredentialsProvider\", \"getToken aborted due to token change.\"), \n this.getToken()) : e ? (M(\"string\" == typeof e.accessToken), new U(e.accessToken, this.currentUser)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.auth && this.auth.removeAuthTokenListener(this.o);\n }\n // Auth.getUid() can return null even with a user logged in. It is because\n // getUid() is synchronous, but the auth code populating Uid is asynchronous.\n // This method should only be called in the AuthTokenListener callback\n // to guarantee to get the actual user.\n u() {\n const t = this.auth && this.auth.getUid();\n return M(null === t || \"string\" == typeof t), new P(t);\n }\n}\n\n/*\n * FirstPartyToken provides a fresh token each time its value\n * is requested, because if the token is too old, requests will be rejected.\n * Technically this may no longer be necessary since the SDK should gracefully\n * recover from unauthenticated errors (see b/33147818 for context), but it's\n * safer to keep the implementation as-is.\n */ class j {\n constructor(t, e, n, s) {\n this.h = t, this.l = e, this.m = n, this.g = s, this.type = \"FirstParty\", this.user = P.FIRST_PARTY, \n this.p = new Map;\n }\n /** Gets an authorization token, using a provided factory function, or falling back to First Party GAPI. */ I() {\n return this.g ? this.g() : (\n // Make sure this really is a Gapi client.\n M(!(\"object\" != typeof this.h || null === this.h || !this.h.auth || !this.h.auth.getAuthHeaderValueForFirstParty)), \n this.h.auth.getAuthHeaderValueForFirstParty([]));\n }\n get headers() {\n this.p.set(\"X-Goog-AuthUser\", this.l);\n // Use array notation to prevent minification\n const t = this.I();\n return t && this.p.set(\"Authorization\", t), this.m && this.p.set(\"X-Goog-Iam-Authorization-Token\", this.m), \n this.p;\n }\n}\n\n/*\n * Provides user credentials required for the Firestore JavaScript SDK\n * to authenticate the user, using technique that is only available\n * to applications hosted by Google.\n */ class W {\n constructor(t, e, n, s) {\n this.h = t, this.l = e, this.m = n, this.g = s;\n }\n getToken() {\n return Promise.resolve(new j(this.h, this.l, this.m, this.g));\n }\n start(t, e) {\n // Fire with initial uid.\n t.enqueueRetryable((() => e(P.FIRST_PARTY)));\n }\n shutdown() {}\n invalidateToken() {}\n}\n\nclass z {\n constructor(t) {\n this.value = t, this.type = \"AppCheck\", this.headers = new Map, t && t.length > 0 && this.headers.set(\"x-firebase-appcheck\", this.value);\n }\n}\n\nclass H {\n constructor(t) {\n this.T = t, this.forceRefresh = !1, this.appCheck = null, this.A = null;\n }\n start(t, e) {\n const n = t => {\n null != t.error && C(\"FirebaseAppCheckTokenProvider\", `Error getting App Check token; using placeholder token instead. Error: ${t.error.message}`);\n const n = t.token !== this.A;\n return this.A = t.token, C(\"FirebaseAppCheckTokenProvider\", `Received ${n ? \"new\" : \"existing\"} token.`), \n n ? e(t.token) : Promise.resolve();\n };\n this.o = e => {\n t.enqueueRetryable((() => n(e)));\n };\n const s = t => {\n C(\"FirebaseAppCheckTokenProvider\", \"AppCheck detected\"), this.appCheck = t, this.appCheck.addTokenListener(this.o);\n };\n this.T.onInit((t => s(t))), \n // Our users can initialize AppCheck after Firestore, so we give it\n // a chance to register itself with the component framework.\n setTimeout((() => {\n if (!this.appCheck) {\n const t = this.T.getImmediate({\n optional: !0\n });\n t ? s(t) : \n // If AppCheck is still not available, proceed without it.\n C(\"FirebaseAppCheckTokenProvider\", \"AppCheck not yet detected\");\n }\n }), 0);\n }\n getToken() {\n const t = this.forceRefresh;\n return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(t).then((t => t ? (M(\"string\" == typeof t.token), \n this.A = t.token, new z(t.token)) : null)) : Promise.resolve(null);\n }\n invalidateToken() {\n this.forceRefresh = !0;\n }\n shutdown() {\n this.appCheck && this.appCheck.removeTokenListener(this.o);\n }\n}\n\n/**\n * An AppCheck token provider that always yields an empty token.\n * @internal\n */ class J {\n getToken() {\n return Promise.resolve(new z(\"\"));\n }\n invalidateToken() {}\n start(t, e) {}\n shutdown() {}\n}\n\n/**\n * Builds a CredentialsProvider depending on the type of\n * the credentials passed in.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Generates `nBytes` of random bytes.\n *\n * If `nBytes < 0` , an error will be thrown.\n */\nfunction Y(t) {\n // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available.\n const e = \n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n \"undefined\" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(t);\n if (e && \"function\" == typeof e.getRandomValues) e.getRandomValues(n); else \n // Falls back to Math.random\n for (let e = 0; e < t; e++) n[e] = Math.floor(256 * Math.random());\n return n;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class X {\n static R() {\n // Alphanumeric characters\n const t = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\", e = Math.floor(256 / t.length) * t.length;\n // The largest byte value that is a multiple of `char.length`.\n let n = \"\";\n for (;n.length < 20; ) {\n const s = Y(40);\n for (let i = 0; i < s.length; ++i) \n // Only accept values that are [0, maxMultiple), this ensures they can\n // be evenly mapped to indices of `chars` via a modulo operation.\n n.length < 20 && s[i] < e && (n += t.charAt(s[i] % t.length));\n }\n return n;\n }\n}\n\nfunction Z(t, e) {\n return t < e ? -1 : t > e ? 1 : 0;\n}\n\n/** Helper to compare arrays using isEqual(). */ function tt(t, e, n) {\n return t.length === e.length && t.every(((t, s) => n(t, e[s])));\n}\n\n/**\n * Returns the immediate lexicographically-following string. This is useful to\n * construct an inclusive range for indexeddb iterators.\n */ function et(t) {\n // Return the input string, with an additional NUL byte appended.\n return t + \"\\0\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z).\n/**\n * A `Timestamp` represents a point in time independent of any time zone or\n * calendar, represented as seconds and fractions of seconds at nanosecond\n * resolution in UTC Epoch time.\n *\n * It is encoded using the Proleptic Gregorian Calendar which extends the\n * Gregorian calendar backwards to year one. It is encoded assuming all minutes\n * are 60 seconds long, i.e. leap seconds are \"smeared\" so that no leap second\n * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59.999999999Z.\n *\n * For examples and further specifications, refer to the\n * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}.\n */\nclass nt {\n /**\n * Creates a new timestamp.\n *\n * @param seconds - The number of seconds of UTC time since Unix epoch\n * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to\n * 9999-12-31T23:59:59Z inclusive.\n * @param nanoseconds - The non-negative fractions of a second at nanosecond\n * resolution. Negative second values with fractions must still have\n * non-negative nanoseconds values that count forward in time. Must be\n * from 0 to 999,999,999 inclusive.\n */\n constructor(\n /**\n * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.\n */\n t, \n /**\n * The fractions of a second at nanosecond resolution.*\n */\n e) {\n if (this.seconds = t, this.nanoseconds = e, e < 0) throw new L(B.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + e);\n if (e >= 1e9) throw new L(B.INVALID_ARGUMENT, \"Timestamp nanoseconds out of range: \" + e);\n if (t < -62135596800) throw new L(B.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + t);\n // This will break in the year 10,000.\n if (t >= 253402300800) throw new L(B.INVALID_ARGUMENT, \"Timestamp seconds out of range: \" + t);\n }\n /**\n * Creates a new timestamp with the current date, with millisecond precision.\n *\n * @returns a new timestamp representing the current date.\n */ static now() {\n return nt.fromMillis(Date.now());\n }\n /**\n * Creates a new timestamp from the given date.\n *\n * @param date - The date to initialize the `Timestamp` from.\n * @returns A new `Timestamp` representing the same point in time as the given\n * date.\n */ static fromDate(t) {\n return nt.fromMillis(t.getTime());\n }\n /**\n * Creates a new timestamp from the given number of milliseconds.\n *\n * @param milliseconds - Number of milliseconds since Unix epoch\n * 1970-01-01T00:00:00Z.\n * @returns A new `Timestamp` representing the same point in time as the given\n * number of milliseconds.\n */ static fromMillis(t) {\n const e = Math.floor(t / 1e3), n = Math.floor(1e6 * (t - 1e3 * e));\n return new nt(e, n);\n }\n /**\n * Converts a `Timestamp` to a JavaScript `Date` object. This conversion\n * causes a loss of precision since `Date` objects only support millisecond\n * precision.\n *\n * @returns JavaScript `Date` object representing the same point in time as\n * this `Timestamp`, with millisecond precision.\n */ toDate() {\n return new Date(this.toMillis());\n }\n /**\n * Converts a `Timestamp` to a numeric timestamp (in milliseconds since\n * epoch). This operation causes a loss of precision.\n *\n * @returns The point in time corresponding to this timestamp, represented as\n * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.\n */ toMillis() {\n return 1e3 * this.seconds + this.nanoseconds / 1e6;\n }\n _compareTo(t) {\n return this.seconds === t.seconds ? Z(this.nanoseconds, t.nanoseconds) : Z(this.seconds, t.seconds);\n }\n /**\n * Returns true if this `Timestamp` is equal to the provided one.\n *\n * @param other - The `Timestamp` to compare against.\n * @returns true if this `Timestamp` is equal to the provided one.\n */ isEqual(t) {\n return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds;\n }\n /** Returns a textual representation of this `Timestamp`. */ toString() {\n return \"Timestamp(seconds=\" + this.seconds + \", nanoseconds=\" + this.nanoseconds + \")\";\n }\n /** Returns a JSON-serializable representation of this `Timestamp`. */ toJSON() {\n return {\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n /**\n * Converts this object to a primitive string, which allows `Timestamp` objects\n * to be compared using the `>`, `<=`, `>=` and `>` operators.\n */ valueOf() {\n // This method returns a string of the form <seconds>.<nanoseconds> where\n // <seconds> is translated to have a non-negative value and both <seconds>\n // and <nanoseconds> are left-padded with zeroes to be a consistent length.\n // Strings with this format then have a lexiographical ordering that matches\n // the expected ordering. The <seconds> translation is done to avoid having\n // a leading negative sign (i.e. a leading '-' character) in its string\n // representation, which would affect its lexiographical ordering.\n const t = this.seconds - -62135596800;\n // Note: Up to 12 decimal digits are required to represent all valid\n // 'seconds' values.\n return String(t).padStart(12, \"0\") + \".\" + String(this.nanoseconds).padStart(9, \"0\");\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A version of a document in Firestore. This corresponds to the version\n * timestamp, such as update_time or read_time.\n */ class st {\n constructor(t) {\n this.timestamp = t;\n }\n static fromTimestamp(t) {\n return new st(t);\n }\n static min() {\n return new st(new nt(0, 0));\n }\n static max() {\n return new st(new nt(253402300799, 999999999));\n }\n compareTo(t) {\n return this.timestamp._compareTo(t.timestamp);\n }\n isEqual(t) {\n return this.timestamp.isEqual(t.timestamp);\n }\n /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() {\n // Convert to microseconds.\n return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3;\n }\n toString() {\n return \"SnapshotVersion(\" + this.timestamp.toString() + \")\";\n }\n toTimestamp() {\n return this.timestamp;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Path represents an ordered sequence of string segments.\n */\nclass it {\n constructor(t, e, n) {\n void 0 === e ? e = 0 : e > t.length && O(), void 0 === n ? n = t.length - e : n > t.length - e && O(), \n this.segments = t, this.offset = e, this.len = n;\n }\n get length() {\n return this.len;\n }\n isEqual(t) {\n return 0 === it.comparator(this, t);\n }\n child(t) {\n const e = this.segments.slice(this.offset, this.limit());\n return t instanceof it ? t.forEach((t => {\n e.push(t);\n })) : e.push(t), this.construct(e);\n }\n /** The index of one past the last segment of the path. */ limit() {\n return this.offset + this.length;\n }\n popFirst(t) {\n return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t);\n }\n popLast() {\n return this.construct(this.segments, this.offset, this.length - 1);\n }\n firstSegment() {\n return this.segments[this.offset];\n }\n lastSegment() {\n return this.get(this.length - 1);\n }\n get(t) {\n return this.segments[this.offset + t];\n }\n isEmpty() {\n return 0 === this.length;\n }\n isPrefixOf(t) {\n if (t.length < this.length) return !1;\n for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;\n return !0;\n }\n isImmediateParentOf(t) {\n if (this.length + 1 !== t.length) return !1;\n for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1;\n return !0;\n }\n forEach(t) {\n for (let e = this.offset, n = this.limit(); e < n; e++) t(this.segments[e]);\n }\n toArray() {\n return this.segments.slice(this.offset, this.limit());\n }\n static comparator(t, e) {\n const n = Math.min(t.length, e.length);\n for (let s = 0; s < n; s++) {\n const n = t.get(s), i = e.get(s);\n if (n < i) return -1;\n if (n > i) return 1;\n }\n return t.length < e.length ? -1 : t.length > e.length ? 1 : 0;\n }\n}\n\n/**\n * A slash-separated path for navigating resources (documents and collections)\n * within Firestore.\n *\n * @internal\n */ class rt extends it {\n construct(t, e, n) {\n return new rt(t, e, n);\n }\n canonicalString() {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n return this.toArray().join(\"/\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Creates a resource path from the given slash-delimited string. If multiple\n * arguments are provided, all components are combined. Leading and trailing\n * slashes from all components are ignored.\n */ static fromString(...t) {\n // NOTE: The client is ignorant of any path segments containing escape\n // sequences (e.g. __id123__) and just passes them through raw (they exist\n // for legacy reasons and should not be used frequently).\n const e = [];\n for (const n of t) {\n if (n.indexOf(\"//\") >= 0) throw new L(B.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`);\n // Strip leading and traling slashed.\n e.push(...n.split(\"/\").filter((t => t.length > 0)));\n }\n return new rt(e);\n }\n static emptyPath() {\n return new rt([]);\n }\n}\n\nconst ot = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n\n/**\n * A dot-separated path for navigating sub-objects within a document.\n * @internal\n */ class ut extends it {\n construct(t, e, n) {\n return new ut(t, e, n);\n }\n /**\n * Returns true if the string could be used as a segment in a field path\n * without escaping.\n */ static isValidIdentifier(t) {\n return ot.test(t);\n }\n canonicalString() {\n return this.toArray().map((t => (t = t.replace(/\\\\/g, \"\\\\\\\\\").replace(/`/g, \"\\\\`\"), \n ut.isValidIdentifier(t) || (t = \"`\" + t + \"`\"), t))).join(\".\");\n }\n toString() {\n return this.canonicalString();\n }\n /**\n * Returns true if this field references the key of a document.\n */ isKeyField() {\n return 1 === this.length && \"__name__\" === this.get(0);\n }\n /**\n * The field designating the key of a document.\n */ static keyField() {\n return new ut([ \"__name__\" ]);\n }\n /**\n * Parses a field string from the given server-formatted string.\n *\n * - Splitting the empty string is not allowed (for now at least).\n * - Empty segments within the string (e.g. if there are two consecutive\n * separators) are not allowed.\n *\n * TODO(b/37244157): we should make this more strict. Right now, it allows\n * non-identifier path components, even if they aren't escaped.\n */ static fromServerFormat(t) {\n const e = [];\n let n = \"\", s = 0;\n const i = () => {\n if (0 === n.length) throw new L(B.INVALID_ARGUMENT, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`);\n e.push(n), n = \"\";\n };\n let r = !1;\n for (;s < t.length; ) {\n const e = t[s];\n if (\"\\\\\" === e) {\n if (s + 1 === t.length) throw new L(B.INVALID_ARGUMENT, \"Path has trailing escape character: \" + t);\n const e = t[s + 1];\n if (\"\\\\\" !== e && \".\" !== e && \"`\" !== e) throw new L(B.INVALID_ARGUMENT, \"Path has invalid escape sequence: \" + t);\n n += e, s += 2;\n } else \"`\" === e ? (r = !r, s++) : \".\" !== e || r ? (n += e, s++) : (i(), s++);\n }\n if (i(), r) throw new L(B.INVALID_ARGUMENT, \"Unterminated ` in path: \" + t);\n return new ut(e);\n }\n static emptyPath() {\n return new ut([]);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @internal\n */ class ct {\n constructor(t) {\n this.path = t;\n }\n static fromPath(t) {\n return new ct(rt.fromString(t));\n }\n static fromName(t) {\n return new ct(rt.fromString(t).popFirst(5));\n }\n static empty() {\n return new ct(rt.emptyPath());\n }\n get collectionGroup() {\n return this.path.popLast().lastSegment();\n }\n /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) {\n return this.path.length >= 2 && this.path.get(this.path.length - 2) === t;\n }\n /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() {\n return this.path.get(this.path.length - 2);\n }\n /** Returns the fully qualified path to the parent collection. */ getCollectionPath() {\n return this.path.popLast();\n }\n isEqual(t) {\n return null !== t && 0 === rt.comparator(this.path, t.path);\n }\n toString() {\n return this.path.toString();\n }\n static comparator(t, e) {\n return rt.comparator(t.path, e.path);\n }\n static isDocumentKey(t) {\n return t.length % 2 == 0;\n }\n /**\n * Creates and returns a new document key with the given segments.\n *\n * @param segments - The segments of the path to the document\n * @returns A new instance of DocumentKey\n */ static fromSegments(t) {\n return new ct(new rt(t.slice()));\n }\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The initial mutation batch id for each index. Gets updated during index\n * backfill.\n */\n/**\n * An index definition for field indexes in Firestore.\n *\n * Every index is associated with a collection. The definition contains a list\n * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or\n * `CONTAINS` for ArrayContains/ArrayContainsAny queries).\n *\n * Unlike the backend, the SDK does not differentiate between collection or\n * collection group-scoped indices. Every index can be used for both single\n * collection and collection group queries.\n */\nclass at {\n constructor(\n /**\n * The index ID. Returns -1 if the index ID is not available (e.g. the index\n * has not yet been persisted).\n */\n t, \n /** The collection ID this index applies to. */\n e, \n /** The field segments for this index. */\n n, \n /** Shows how up-to-date the index is for the current user. */\n s) {\n this.indexId = t, this.collectionGroup = e, this.fields = n, this.indexState = s;\n }\n}\n\n/** An ID for an index that has not yet been added to persistence. */\n/** Returns the ArrayContains/ArrayContainsAny segment for this index. */\nfunction ht(t) {\n return t.fields.find((t => 2 /* IndexKind.CONTAINS */ === t.kind));\n}\n\n/** Returns all directional (ascending/descending) segments for this index. */ function lt(t) {\n return t.fields.filter((t => 2 /* IndexKind.CONTAINS */ !== t.kind));\n}\n\n/**\n * Returns the order of the document key component for the given index.\n *\n * PORTING NOTE: This is only used in the Web IndexedDb implementation.\n */\n/**\n * Compares indexes by collection group and segments. Ignores update time and\n * index ID.\n */\nfunction ft(t, e) {\n let n = Z(t.collectionGroup, e.collectionGroup);\n if (0 !== n) return n;\n for (let s = 0; s < Math.min(t.fields.length, e.fields.length); ++s) if (n = _t(t.fields[s], e.fields[s]), \n 0 !== n) return n;\n return Z(t.fields.length, e.fields.length);\n}\n\n/** Returns a debug representation of the field index */ at.UNKNOWN_ID = -1;\n\n/** An index component consisting of field path and index type. */\nclass dt {\n constructor(\n /** The field path of the component. */\n t, \n /** The fields sorting order. */\n e) {\n this.fieldPath = t, this.kind = e;\n }\n}\n\nfunction _t(t, e) {\n const n = ut.comparator(t.fieldPath, e.fieldPath);\n return 0 !== n ? n : Z(t.kind, e.kind);\n}\n\n/**\n * Stores the \"high water mark\" that indicates how updated the Index is for the\n * current user.\n */ class wt {\n constructor(\n /**\n * Indicates when the index was last updated (relative to other indexes).\n */\n t, \n /** The the latest indexed read time, document and batch id. */\n e) {\n this.sequenceNumber = t, this.offset = e;\n }\n /** The state of an index that has not yet been backfilled. */ static empty() {\n return new wt(0, yt.min());\n }\n}\n\n/**\n * Creates an offset that matches all documents with a read time higher than\n * `readTime`.\n */ function mt(t, e) {\n // We want to create an offset that matches all documents with a read time\n // greater than the provided read time. To do so, we technically need to\n // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use\n // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use\n // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches\n // all valid document IDs.\n const n = t.toTimestamp().seconds, s = t.toTimestamp().nanoseconds + 1, i = st.fromTimestamp(1e9 === s ? new nt(n + 1, 0) : new nt(n, s));\n return new yt(i, ct.empty(), e);\n}\n\n/** Creates a new offset based on the provided document. */ function gt(t) {\n return new yt(t.readTime, t.key, -1);\n}\n\n/**\n * Stores the latest read time, document and batch ID that were processed for an\n * index.\n */ class yt {\n constructor(\n /**\n * The latest read time version that has been indexed by Firestore for this\n * field index.\n */\n t, \n /**\n * The key of the last document that was indexed for this query. Use\n * `DocumentKey.empty()` if no document has been indexed.\n */\n e, \n /*\n * The largest mutation batch id that's been processed by Firestore.\n */\n n) {\n this.readTime = t, this.documentKey = e, this.largestBatchId = n;\n }\n /** Returns an offset that sorts before all regular offsets. */ static min() {\n return new yt(st.min(), ct.empty(), -1);\n }\n /** Returns an offset that sorts after all regular offsets. */ static max() {\n return new yt(st.max(), ct.empty(), -1);\n }\n}\n\nfunction pt(t, e) {\n let n = t.readTime.compareTo(e.readTime);\n return 0 !== n ? n : (n = ct.comparator(t.documentKey, e.documentKey), 0 !== n ? n : Z(t.largestBatchId, e.largestBatchId));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const It = \"The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab.\";\n\n/**\n * A base class representing a persistence transaction, encapsulating both the\n * transaction's sequence numbers as well as a list of onCommitted listeners.\n *\n * When you call Persistence.runTransaction(), it will create a transaction and\n * pass it to your callback. You then pass it to any method that operates\n * on persistence.\n */ class Tt {\n constructor() {\n this.onCommittedListeners = [];\n }\n addOnCommittedListener(t) {\n this.onCommittedListeners.push(t);\n }\n raiseOnCommittedEvent() {\n this.onCommittedListeners.forEach((t => t()));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Verifies the error thrown by a LocalStore operation. If a LocalStore\n * operation fails because the primary lease has been taken by another client,\n * we ignore the error (the persistence layer will immediately call\n * `applyPrimaryLease` to propagate the primary state change). All other errors\n * are re-thrown.\n *\n * @param err - An error returned by a LocalStore operation.\n * @returns A Promise that resolves after we recovered, or the original error.\n */ async function Et(t) {\n if (t.code !== B.FAILED_PRECONDITION || t.message !== It) throw t;\n C(\"LocalStore\", \"Unexpectedly lost primary lease\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * PersistencePromise is essentially a re-implementation of Promise except\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\n * are executed synchronously when a PersistencePromise resolves rather than\n * asynchronously (Promise implementations use setImmediate() or similar).\n *\n * This is necessary to interoperate with IndexedDB which will automatically\n * commit transactions if control is returned to the event loop without\n * synchronously initiating another operation on the transaction.\n *\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\n * Promises.\n */ class At {\n constructor(t) {\n // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n this.nextCallback = null, this.catchCallback = null, \n // When the operation resolves, we'll set result or error and mark isDone.\n this.result = void 0, this.error = void 0, this.isDone = !1, \n // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n this.callbackAttached = !1, t((t => {\n this.isDone = !0, this.result = t, this.nextCallback && \n // value should be defined unless T is Void, but we can't express\n // that in the type system.\n this.nextCallback(t);\n }), (t => {\n this.isDone = !0, this.error = t, this.catchCallback && this.catchCallback(t);\n }));\n }\n catch(t) {\n return this.next(void 0, t);\n }\n next(t, e) {\n return this.callbackAttached && O(), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(e, this.error) : this.wrapSuccess(t, this.result) : new At(((n, s) => {\n this.nextCallback = e => {\n this.wrapSuccess(t, e).next(n, s);\n }, this.catchCallback = t => {\n this.wrapFailure(e, t).next(n, s);\n };\n }));\n }\n toPromise() {\n return new Promise(((t, e) => {\n this.next(t, e);\n }));\n }\n wrapUserFunction(t) {\n try {\n const e = t();\n return e instanceof At ? e : At.resolve(e);\n } catch (t) {\n return At.reject(t);\n }\n }\n wrapSuccess(t, e) {\n return t ? this.wrapUserFunction((() => t(e))) : At.resolve(e);\n }\n wrapFailure(t, e) {\n return t ? this.wrapUserFunction((() => t(e))) : At.reject(e);\n }\n static resolve(t) {\n return new At(((e, n) => {\n e(t);\n }));\n }\n static reject(t) {\n return new At(((e, n) => {\n n(t);\n }));\n }\n static waitFor(\n // Accept all Promise types in waitFor().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n t) {\n return new At(((e, n) => {\n let s = 0, i = 0, r = !1;\n t.forEach((t => {\n ++s, t.next((() => {\n ++i, r && i === s && e();\n }), (t => n(t)));\n })), r = !0, i === s && e();\n }));\n }\n /**\n * Given an array of predicate functions that asynchronously evaluate to a\n * boolean, implements a short-circuiting `or` between the results. Predicates\n * will be evaluated until one of them returns `true`, then stop. The final\n * result will be whether any of them returned `true`.\n */ static or(t) {\n let e = At.resolve(!1);\n for (const n of t) e = e.next((t => t ? At.resolve(t) : n()));\n return e;\n }\n static forEach(t, e) {\n const n = [];\n return t.forEach(((t, s) => {\n n.push(e.call(this, t, s));\n })), this.waitFor(n);\n }\n /**\n * Concurrently map all array elements through asynchronous function.\n */ static mapArray(t, e) {\n return new At(((n, s) => {\n const i = t.length, r = new Array(i);\n let o = 0;\n for (let u = 0; u < i; u++) {\n const c = u;\n e(t[c]).next((t => {\n r[c] = t, ++o, o === i && n(r);\n }), (t => s(t)));\n }\n }));\n }\n /**\n * An alternative to recursive PersistencePromise calls, that avoids\n * potential memory problems from unbounded chains of promises.\n *\n * The `action` will be called repeatedly while `condition` is true.\n */ static doWhile(t, e) {\n return new At(((n, s) => {\n const i = () => {\n !0 === t() ? e().next((() => {\n i();\n }), s) : n();\n };\n i();\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by SimpleDb.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\n * specific object store.\n */\nclass Rt {\n constructor(t, e) {\n this.action = t, this.transaction = e, this.aborted = !1, \n /**\n * A `Promise` that resolves with the result of the IndexedDb transaction.\n */\n this.P = new q, this.transaction.oncomplete = () => {\n this.P.resolve();\n }, this.transaction.onabort = () => {\n e.error ? this.P.reject(new vt(t, e.error)) : this.P.resolve();\n }, this.transaction.onerror = e => {\n const n = xt(e.target.error);\n this.P.reject(new vt(t, n));\n };\n }\n static open(t, e, n, s) {\n try {\n return new Rt(e, t.transaction(s, n));\n } catch (t) {\n throw new vt(e, t);\n }\n }\n get v() {\n return this.P.promise;\n }\n abort(t) {\n t && this.P.reject(t), this.aborted || (C(\"SimpleDb\", \"Aborting transaction:\", t ? t.message : \"Client-initiated abort\"), \n this.aborted = !0, this.transaction.abort());\n }\n V() {\n // If the browser supports V3 IndexedDB, we invoke commit() explicitly to\n // speed up index DB processing if the event loop remains blocks.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const t = this.transaction;\n this.aborted || \"function\" != typeof t.commit || t.commit();\n }\n /**\n * Returns a SimpleDbStore<KeyType, ValueType> for the specified store. All\n * operations performed on the SimpleDbStore happen within the context of this\n * transaction and it cannot be used anymore once the transaction is\n * completed.\n *\n * Note that we can't actually enforce that the KeyType and ValueType are\n * correct, but they allow type safety through the rest of the consuming code.\n */ store(t) {\n const e = this.transaction.objectStore(t);\n return new St(e);\n }\n}\n\n/**\n * Provides a wrapper around IndexedDb with a simplified interface that uses\n * Promise-like return values to chain operations. Real promises cannot be used\n * since .then() continuations are executed asynchronously (e.g. via\n * .setImmediate), which would cause IndexedDB to end the transaction.\n * See PersistencePromise for more details.\n */ class bt {\n /*\n * Creates a new SimpleDb wrapper for IndexedDb database `name`.\n *\n * Note that `version` must not be a downgrade. IndexedDB does not support\n * downgrading the schema version. We currently do not support any way to do\n * versioning outside of IndexedDB's versioning mechanism, as only\n * version-upgrade transactions are allowed to do things like create\n * objectstores.\n */\n constructor(t, e, n) {\n this.name = t, this.version = e, this.S = n;\n // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the\n // bug we're checking for should exist in iOS >= 12.2 and < 13, but for\n // whatever reason it's much harder to hit after 12.2 so we only proactively\n // log on 12.2.\n 12.2 === bt.D(a()) && x(\"Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.\");\n }\n /** Deletes the specified database. */ static delete(t) {\n return C(\"SimpleDb\", \"Removing database:\", t), Dt(window.indexedDB.deleteDatabase(t)).toPromise();\n }\n /** Returns true if IndexedDB is available in the current environment. */ static C() {\n if (!h()) return !1;\n if (bt.N()) return !0;\n // We extensively use indexed array values and compound keys,\n // which IE and Edge do not support. However, they still have indexedDB\n // defined on the window, so we need to check for them here and make sure\n // to return that persistence is not enabled for those browsers.\n // For tracking support of this feature, see here:\n // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/\n // Check the UA string to find out the browser.\n const t = a(), e = bt.D(t), n = 0 < e && e < 10, s = bt.k(t), i = 0 < s && s < 4.5;\n // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\n // Edge\n // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,\n // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';\n // iOS Safari: Disable for users running iOS version < 10.\n return !(t.indexOf(\"MSIE \") > 0 || t.indexOf(\"Trident/\") > 0 || t.indexOf(\"Edge/\") > 0 || n || i);\n }\n /**\n * Returns true if the backing IndexedDB store is the Node IndexedDBShim\n * (see https://github.com/axemclion/IndexedDBShim).\n */ static N() {\n var t;\n return \"undefined\" != typeof process && \"YES\" === (null === (t = process.env) || void 0 === t ? void 0 : t.O);\n }\n /** Helper to get a typed SimpleDbStore from a transaction. */ static M(t, e) {\n return t.store(e);\n }\n // visible for testing\n /** Parse User Agent to determine iOS version. Returns -1 if not found. */\n static D(t) {\n const e = t.match(/i(?:phone|pad|pod) os ([\\d_]+)/i), n = e ? e[1].split(\"_\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n // visible for testing\n /** Parse User Agent to determine Android version. Returns -1 if not found. */\n static k(t) {\n const e = t.match(/Android ([\\d.]+)/i), n = e ? e[1].split(\".\").slice(0, 2).join(\".\") : \"-1\";\n return Number(n);\n }\n /**\n * Opens the specified database, creating or upgrading it if necessary.\n */ async F(t) {\n return this.db || (C(\"SimpleDb\", \"Opening database:\", this.name), this.db = await new Promise(((e, n) => {\n // TODO(mikelehen): Investigate browser compatibility.\n // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB\n // suggests IE9 and older WebKit browsers handle upgrade\n // differently. They expect setVersion, as described here:\n // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion\n const s = indexedDB.open(this.name, this.version);\n s.onsuccess = t => {\n const n = t.target.result;\n e(n);\n }, s.onblocked = () => {\n n(new vt(t, \"Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.\"));\n }, s.onerror = e => {\n const s = e.target.error;\n \"VersionError\" === s.name ? n(new L(B.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\" === s.name ? n(new L(B.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: \" + s)) : n(new vt(t, s));\n }, s.onupgradeneeded = t => {\n C(\"SimpleDb\", 'Database \"' + this.name + '\" requires upgrade from version:', t.oldVersion);\n const e = t.target.result;\n this.S.$(e, s.transaction, t.oldVersion, this.version).next((() => {\n C(\"SimpleDb\", \"Database upgrade to version \" + this.version + \" complete\");\n }));\n };\n }))), this.B && (this.db.onversionchange = t => this.B(t)), this.db;\n }\n L(t) {\n this.B = t, this.db && (this.db.onversionchange = e => t(e));\n }\n async runTransaction(t, e, n, s) {\n const i = \"readonly\" === e;\n let r = 0;\n for (;;) {\n ++r;\n try {\n this.db = await this.F(t);\n const e = Rt.open(this.db, t, i ? \"readonly\" : \"readwrite\", n), r = s(e).next((t => (e.V(), \n t))).catch((t => (\n // Abort the transaction if there was an error.\n e.abort(t), At.reject(t)))).toPromise();\n // As noted above, errors are propagated by aborting the transaction. So\n // we swallow any error here to avoid the browser logging it as unhandled.\n return r.catch((() => {})), \n // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to\n // fire), but still return the original transactionFnResult back to the\n // caller.\n await e.v, r;\n } catch (t) {\n const e = t, n = \"FirebaseError\" !== e.name && r < 3;\n // TODO(schmidt-sebastian): We could probably be smarter about this and\n // not retry exceptions that are likely unrecoverable (such as quota\n // exceeded errors).\n // Note: We cannot use an instanceof check for FirestoreException, since the\n // exception is wrapped in a generic error by our async/await handling.\n if (C(\"SimpleDb\", \"Transaction failed with error:\", e.message, \"Retrying:\", n), \n this.close(), !n) return Promise.reject(e);\n }\n }\n }\n close() {\n this.db && this.db.close(), this.db = void 0;\n }\n}\n\n/**\n * A controller for iterating over a key range or index. It allows an iterate\n * callback to delete the currently-referenced object, or jump to a new key\n * within the key range or index.\n */ class Pt {\n constructor(t) {\n this.q = t, this.U = !1, this.K = null;\n }\n get isDone() {\n return this.U;\n }\n get G() {\n return this.K;\n }\n set cursor(t) {\n this.q = t;\n }\n /**\n * This function can be called to stop iteration at any point.\n */ done() {\n this.U = !0;\n }\n /**\n * This function can be called to skip to that next key, which could be\n * an index or a primary key.\n */ j(t) {\n this.K = t;\n }\n /**\n * Delete the current cursor value from the object store.\n *\n * NOTE: You CANNOT do this with a keysOnly query.\n */ delete() {\n return Dt(this.q.delete());\n }\n}\n\n/** An error that wraps exceptions that thrown during IndexedDB execution. */ class vt extends L {\n constructor(t, e) {\n super(B.UNAVAILABLE, `IndexedDB transaction '${t}' failed: ${e}`), this.name = \"IndexedDbTransactionError\";\n }\n}\n\n/** Verifies whether `e` is an IndexedDbTransactionError. */ function Vt(t) {\n // Use name equality, as instanceof checks on errors don't work with errors\n // that wrap other errors.\n return \"IndexedDbTransactionError\" === t.name;\n}\n\n/**\n * A wrapper around an IDBObjectStore providing an API that:\n *\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\n * methods for acting against the object store.\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\n * method return a PersistencePromise instead.\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\n */ class St {\n constructor(t) {\n this.store = t;\n }\n put(t, e) {\n let n;\n return void 0 !== e ? (C(\"SimpleDb\", \"PUT\", this.store.name, t, e), n = this.store.put(e, t)) : (C(\"SimpleDb\", \"PUT\", this.store.name, \"<auto-key>\", t), \n n = this.store.put(t)), Dt(n);\n }\n /**\n * Adds a new value into an Object Store and returns the new key. Similar to\n * IndexedDb's `add()`, this method will fail on primary key collisions.\n *\n * @param value - The object to write.\n * @returns The key of the value to add.\n */ add(t) {\n C(\"SimpleDb\", \"ADD\", this.store.name, t, t);\n return Dt(this.store.add(t));\n }\n /**\n * Gets the object with the specified key from the specified store, or null\n * if no object exists with the specified key.\n *\n * @key The key of the object to get.\n * @returns The object with the specified key or null if no object exists.\n */ get(t) {\n // We're doing an unsafe cast to ValueType.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return Dt(this.store.get(t)).next((e => (\n // Normalize nonexistence to null.\n void 0 === e && (e = null), C(\"SimpleDb\", \"GET\", this.store.name, t, e), e)));\n }\n delete(t) {\n C(\"SimpleDb\", \"DELETE\", this.store.name, t);\n return Dt(this.store.delete(t));\n }\n /**\n * If we ever need more of the count variants, we can add overloads. For now,\n * all we need is to count everything in a store.\n *\n * Returns the number of rows in the store.\n */ count() {\n C(\"SimpleDb\", \"COUNT\", this.store.name);\n return Dt(this.store.count());\n }\n W(t, e) {\n const n = this.options(t, e);\n // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly\n // 20% faster. Unfortunately, getAll() does not support custom indices.\n if (n.index || \"function\" != typeof this.store.getAll) {\n const t = this.cursor(n), e = [];\n return this.H(t, ((t, n) => {\n e.push(n);\n })).next((() => e));\n }\n {\n const t = this.store.getAll(n.range);\n return new At(((e, n) => {\n t.onerror = t => {\n n(t.target.error);\n }, t.onsuccess = t => {\n e(t.target.result);\n };\n }));\n }\n }\n /**\n * Loads the first `count` elements from the provided index range. Loads all\n * elements if no limit is provided.\n */ J(t, e) {\n const n = this.store.getAll(t, null === e ? void 0 : e);\n return new At(((t, e) => {\n n.onerror = t => {\n e(t.target.error);\n }, n.onsuccess = e => {\n t(e.target.result);\n };\n }));\n }\n Y(t, e) {\n C(\"SimpleDb\", \"DELETE ALL\", this.store.name);\n const n = this.options(t, e);\n n.X = !1;\n const s = this.cursor(n);\n return this.H(s, ((t, e, n) => n.delete()));\n }\n Z(t, e) {\n let n;\n e ? n = t : (n = {}, e = t);\n const s = this.cursor(n);\n return this.H(s, e);\n }\n /**\n * Iterates over a store, but waits for the given callback to complete for\n * each entry before iterating the next entry. This allows the callback to do\n * asynchronous work to determine if this iteration should continue.\n *\n * The provided callback should return `true` to continue iteration, and\n * `false` otherwise.\n */ tt(t) {\n const e = this.cursor({});\n return new At(((n, s) => {\n e.onerror = t => {\n const e = xt(t.target.error);\n s(e);\n }, e.onsuccess = e => {\n const s = e.target.result;\n s ? t(s.primaryKey, s.value).next((t => {\n t ? s.continue() : n();\n })) : n();\n };\n }));\n }\n H(t, e) {\n const n = [];\n return new At(((s, i) => {\n t.onerror = t => {\n i(t.target.error);\n }, t.onsuccess = t => {\n const i = t.target.result;\n if (!i) return void s();\n const r = new Pt(i), o = e(i.primaryKey, i.value, r);\n if (o instanceof At) {\n const t = o.catch((t => (r.done(), At.reject(t))));\n n.push(t);\n }\n r.isDone ? s() : null === r.G ? i.continue() : i.continue(r.G);\n };\n })).next((() => At.waitFor(n)));\n }\n options(t, e) {\n let n;\n return void 0 !== t && (\"string\" == typeof t ? n = t : e = t), {\n index: n,\n range: e\n };\n }\n cursor(t) {\n let e = \"next\";\n if (t.reverse && (e = \"prev\"), t.index) {\n const n = this.store.index(t.index);\n return t.X ? n.openKeyCursor(t.range, e) : n.openCursor(t.range, e);\n }\n return this.store.openCursor(t.range, e);\n }\n}\n\n/**\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\n * handlers to resolve / reject the PersistencePromise as appropriate.\n */ function Dt(t) {\n return new At(((e, n) => {\n t.onsuccess = t => {\n const n = t.target.result;\n e(n);\n }, t.onerror = t => {\n const e = xt(t.target.error);\n n(e);\n };\n }));\n}\n\n// Guard so we only report the error once.\nlet Ct = !1;\n\nfunction xt(t) {\n const e = bt.D(a());\n if (e >= 12.2 && e < 13) {\n const e = \"An internal error was encountered in the Indexed Database server\";\n if (t.message.indexOf(e) >= 0) {\n // Wrap error in a more descriptive one.\n const t = new L(\"internal\", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${e}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`);\n return Ct || (Ct = !0, \n // Throw a global exception outside of this promise chain, for the user to\n // potentially catch.\n setTimeout((() => {\n throw t;\n }), 0)), t;\n }\n }\n return t;\n}\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nclass Nt {\n constructor(t, e) {\n this.asyncQueue = t, this.et = e, this.task = null;\n }\n start() {\n this.nt(15e3);\n }\n stop() {\n this.task && (this.task.cancel(), this.task = null);\n }\n get started() {\n return null !== this.task;\n }\n nt(t) {\n C(\"IndexBackiller\", `Scheduled in ${t}ms`), this.task = this.asyncQueue.enqueueAfterDelay(\"index_backfill\" /* TimerId.IndexBackfill */ , t, (async () => {\n this.task = null;\n try {\n C(\"IndexBackiller\", `Documents written: ${await this.et.st()}`);\n } catch (t) {\n Vt(t) ? C(\"IndexBackiller\", \"Ignoring IndexedDB error during index backfill: \", t) : await Et(t);\n }\n await this.nt(6e4);\n }));\n }\n}\n\n/** Implements the steps for backfilling indexes. */ class kt {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n t, e) {\n this.localStore = t, this.persistence = e;\n }\n async st(t = 50) {\n return this.persistence.runTransaction(\"Backfill Indexes\", \"readwrite-primary\", (e => this.it(e, t)));\n }\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */ it(t, e) {\n const n = new Set;\n let s = e, i = !0;\n return At.doWhile((() => !0 === i && s > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(t).next((e => {\n if (null !== e && !n.has(e)) return C(\"IndexBackiller\", `Processing collection: ${e}`), \n this.rt(t, e, s).next((t => {\n s -= t, n.add(e);\n }));\n i = !1;\n })))).next((() => e - s));\n }\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */ rt(t, e, n) {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager.getMinOffsetFromCollectionGroup(t, e).next((s => this.localStore.localDocuments.getNextDocuments(t, e, s, n).next((n => {\n const i = n.changes;\n return this.localStore.indexManager.updateIndexEntries(t, i).next((() => this.ot(s, n))).next((n => (C(\"IndexBackiller\", `Updating offset: ${n}`), \n this.localStore.indexManager.updateCollectionGroup(t, e, n)))).next((() => i.size));\n }))));\n }\n /** Returns the next offset based on the provided documents. */ ot(t, e) {\n let n = t;\n return e.changes.forEach(((t, e) => {\n const s = gt(e);\n pt(s, n) > 0 && (n = s);\n })), new yt(n.readTime, n.documentKey, Math.max(e.batchId, t.largestBatchId));\n }\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */ class Ot {\n constructor(t, e) {\n this.previousValue = t, e && (e.sequenceNumberHandler = t => this.ut(t), this.ct = t => e.writeSequenceNumber(t));\n }\n ut(t) {\n return this.previousValue = Math.max(t, this.previousValue), this.previousValue;\n }\n next() {\n const t = ++this.previousValue;\n return this.ct && this.ct(t), t;\n }\n}\n\nOt.at = -1;\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Mt {\n /**\n * Constructs a DatabaseInfo using the provided host, databaseId and\n * persistenceKey.\n *\n * @param databaseId - The database to use.\n * @param appId - The Firebase App Id.\n * @param persistenceKey - A unique identifier for this Firestore's local\n * storage (used in conjunction with the databaseId).\n * @param host - The Firestore backend host to connect to.\n * @param ssl - Whether to use SSL when connecting.\n * @param forceLongPolling - Whether to use the forceLongPolling option\n * when using WebChannel as the network transport.\n * @param autoDetectLongPolling - Whether to use the detectBufferingProxy\n * option when using WebChannel as the network transport.\n * @param useFetchStreams Whether to use the Fetch API instead of\n * XMLHTTPRequest\n */\n constructor(t, e, n, s, i, r, o, u) {\n this.databaseId = t, this.appId = e, this.persistenceKey = n, this.host = s, this.ssl = i, \n this.forceLongPolling = r, this.autoDetectLongPolling = o, this.useFetchStreams = u;\n }\n}\n\n/** The default database name for a project. */\n/**\n * Represents the database ID a Firestore client is associated with.\n * @internal\n */\nclass Ft {\n constructor(t, e) {\n this.projectId = t, this.database = e || \"(default)\";\n }\n static empty() {\n return new Ft(\"\", \"\");\n }\n get isDefaultDatabase() {\n return \"(default)\" === this.database;\n }\n isEqual(t) {\n return t instanceof Ft && t.projectId === this.projectId && t.database === this.database;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nfunction $t(t) {\n let e = 0;\n for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e++;\n return e;\n}\n\nfunction Bt(t, e) {\n for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && e(n, t[n]);\n}\n\nfunction Lt(t) {\n for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1;\n return !0;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Sentinel value that sorts before any Mutation Batch ID. */\n/**\n * Returns whether a variable is either undefined or null.\n */\nfunction qt(t) {\n return null == t;\n}\n\n/** Returns whether the value represents -0. */ function Ut(t) {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return 0 === t && 1 / t == -1 / 0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */ function Kt(t) {\n return \"number\" == typeof t && Number.isInteger(t) && !Ut(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Converts a Base64 encoded string to a binary string. */\n/** True if and only if the Base64 conversion functions are available. */\nfunction Gt() {\n return \"undefined\" != typeof atob;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Immutable class that represents a \"proto\" byte string.\n *\n * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when\n * sent on the wire. This class abstracts away this differentiation by holding\n * the proto byte string in a common class that must be converted into a string\n * before being sent as a proto.\n * @internal\n */ class Qt {\n constructor(t) {\n this.binaryString = t;\n }\n static fromBase64String(t) {\n const e = atob(t);\n return new Qt(e);\n }\n static fromUint8Array(t) {\n // TODO(indexing); Remove the copy of the byte string here as this method\n // is frequently called during indexing.\n const e = \n /**\n * Helper function to convert an Uint8array to a binary string.\n */\n function(t) {\n let e = \"\";\n for (let n = 0; n < t.length; ++n) e += String.fromCharCode(t[n]);\n return e;\n }\n /**\n * Helper function to convert a binary string to an Uint8Array.\n */ (t);\n return new Qt(e);\n }\n [Symbol.iterator]() {\n let t = 0;\n return {\n next: () => t < this.binaryString.length ? {\n value: this.binaryString.charCodeAt(t++),\n done: !1\n } : {\n value: void 0,\n done: !0\n }\n };\n }\n toBase64() {\n return t = this.binaryString, btoa(t);\n /** Converts a binary string to a Base64 encoded string. */\n var t;\n }\n toUint8Array() {\n return function(t) {\n const e = new Uint8Array(t.length);\n for (let n = 0; n < t.length; n++) e[n] = t.charCodeAt(n);\n return e;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\n (this.binaryString);\n }\n approximateByteSize() {\n return 2 * this.binaryString.length;\n }\n compareTo(t) {\n return Z(this.binaryString, t.binaryString);\n }\n isEqual(t) {\n return this.binaryString === t.binaryString;\n }\n}\n\nQt.EMPTY_BYTE_STRING = new Qt(\"\");\n\nconst jt = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\n/**\n * Converts the possible Proto values for a timestamp value into a \"seconds and\n * nanos\" representation.\n */ function Wt(t) {\n // The json interface (for the browser) will return an iso timestamp string,\n // while the proto js library (for node) will return a\n // google.protobuf.Timestamp instance.\n if (M(!!t), \"string\" == typeof t) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n let e = 0;\n const n = jt.exec(t);\n if (M(!!n), n[1]) {\n // Pad the fraction out to 9 digits (nanos).\n let t = n[1];\n t = (t + \"000000000\").substr(0, 9), e = Number(t);\n }\n // Parse the date to get the seconds.\n const s = new Date(t);\n return {\n seconds: Math.floor(s.getTime() / 1e3),\n nanos: e\n };\n }\n return {\n seconds: zt(t.seconds),\n nanos: zt(t.nanos)\n };\n}\n\n/**\n * Converts the possible Proto types for numbers into a JavaScript number.\n * Returns 0 if the value is not numeric.\n */ function zt(t) {\n // TODO(bjornick): Handle int64 greater than 53 bits.\n return \"number\" == typeof t ? t : \"string\" == typeof t ? Number(t) : 0;\n}\n\n/** Converts the possible Proto types for Blobs into a ByteString. */ function Ht(t) {\n return \"string\" == typeof t ? Qt.fromBase64String(t) : Qt.fromUint8Array(t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a locally-applied ServerTimestamp.\n *\n * Server Timestamps are backed by MapValues that contain an internal field\n * `__type__` with a value of `server_timestamp`. The previous value and local\n * write time are stored in its `__previous_value__` and `__local_write_time__`\n * fields respectively.\n *\n * Notes:\n * - ServerTimestampValue instances are created as the result of applying a\n * transform. They can only exist in the local view of a document. Therefore\n * they do not need to be parsed or serialized.\n * - When evaluated locally (e.g. for snapshot.data()), they by default\n * evaluate to `null`. This behavior can be configured by passing custom\n * FieldValueOptions to value().\n * - With respect to other ServerTimestampValues, they sort by their\n * localWriteTime.\n */ function Jt(t) {\n var e, n;\n return \"server_timestamp\" === (null === (n = ((null === (e = null == t ? void 0 : t.mapValue) || void 0 === e ? void 0 : e.fields) || {}).__type__) || void 0 === n ? void 0 : n.stringValue);\n}\n\n/**\n * Creates a new ServerTimestamp proto value (using the internal format).\n */\n/**\n * Returns the value of the field before this ServerTimestamp was set.\n *\n * Preserving the previous values allows the user to display the last resoled\n * value until the backend responds with the timestamp.\n */\nfunction Yt(t) {\n const e = t.mapValue.fields.__previous_value__;\n return Jt(e) ? Yt(e) : e;\n}\n\n/**\n * Returns the local time at which this timestamp was first set.\n */ function Xt(t) {\n const e = Wt(t.mapValue.fields.__local_write_time__.timestampValue);\n return new nt(e.seconds, e.nanos);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Zt = {\n mapValue: {\n fields: {\n __type__: {\n stringValue: \"__max__\"\n }\n }\n }\n}, te = {\n nullValue: \"NULL_VALUE\"\n};\n\n/** Extracts the backend's type order for the provided value. */\nfunction ee(t) {\n return \"nullValue\" in t ? 0 /* TypeOrder.NullValue */ : \"booleanValue\" in t ? 1 /* TypeOrder.BooleanValue */ : \"integerValue\" in t || \"doubleValue\" in t ? 2 /* TypeOrder.NumberValue */ : \"timestampValue\" in t ? 3 /* TypeOrder.TimestampValue */ : \"stringValue\" in t ? 5 /* TypeOrder.StringValue */ : \"bytesValue\" in t ? 6 /* TypeOrder.BlobValue */ : \"referenceValue\" in t ? 7 /* TypeOrder.RefValue */ : \"geoPointValue\" in t ? 8 /* TypeOrder.GeoPointValue */ : \"arrayValue\" in t ? 9 /* TypeOrder.ArrayValue */ : \"mapValue\" in t ? Jt(t) ? 4 /* TypeOrder.ServerTimestampValue */ : we(t) ? 9007199254740991 /* TypeOrder.MaxValue */ : 10 /* TypeOrder.ObjectValue */ : O();\n}\n\n/** Tests `left` and `right` for equality based on the backend semantics. */ function ne(t, e) {\n if (t === e) return !0;\n const n = ee(t);\n if (n !== ee(e)) return !1;\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return !0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return t.booleanValue === e.booleanValue;\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return Xt(t).isEqual(Xt(e));\n\n case 3 /* TypeOrder.TimestampValue */ :\n return function(t, e) {\n if (\"string\" == typeof t.timestampValue && \"string\" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) \n // Use string equality for ISO 8601 timestamps\n return t.timestampValue === e.timestampValue;\n const n = Wt(t.timestampValue), s = Wt(e.timestampValue);\n return n.seconds === s.seconds && n.nanos === s.nanos;\n }(t, e);\n\n case 5 /* TypeOrder.StringValue */ :\n return t.stringValue === e.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return function(t, e) {\n return Ht(t.bytesValue).isEqual(Ht(e.bytesValue));\n }(t, e);\n\n case 7 /* TypeOrder.RefValue */ :\n return t.referenceValue === e.referenceValue;\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function(t, e) {\n return zt(t.geoPointValue.latitude) === zt(e.geoPointValue.latitude) && zt(t.geoPointValue.longitude) === zt(e.geoPointValue.longitude);\n }(t, e);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function(t, e) {\n if (\"integerValue\" in t && \"integerValue\" in e) return zt(t.integerValue) === zt(e.integerValue);\n if (\"doubleValue\" in t && \"doubleValue\" in e) {\n const n = zt(t.doubleValue), s = zt(e.doubleValue);\n return n === s ? Ut(n) === Ut(s) : isNaN(n) && isNaN(s);\n }\n return !1;\n }(t, e);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return tt(t.arrayValue.values || [], e.arrayValue.values || [], ne);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function(t, e) {\n const n = t.mapValue.fields || {}, s = e.mapValue.fields || {};\n if ($t(n) !== $t(s)) return !1;\n for (const t in n) if (n.hasOwnProperty(t) && (void 0 === s[t] || !ne(n[t], s[t]))) return !1;\n return !0;\n }\n /** Returns true if the ArrayValue contains the specified element. */ (t, e);\n\n default:\n return O();\n }\n}\n\nfunction se(t, e) {\n return void 0 !== (t.values || []).find((t => ne(t, e)));\n}\n\nfunction ie(t, e) {\n if (t === e) return 0;\n const n = ee(t), s = ee(e);\n if (n !== s) return Z(n, s);\n switch (n) {\n case 0 /* TypeOrder.NullValue */ :\n case 9007199254740991 /* TypeOrder.MaxValue */ :\n return 0;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return Z(t.booleanValue, e.booleanValue);\n\n case 2 /* TypeOrder.NumberValue */ :\n return function(t, e) {\n const n = zt(t.integerValue || t.doubleValue), s = zt(e.integerValue || e.doubleValue);\n return n < s ? -1 : n > s ? 1 : n === s ? 0 : \n // one or both are NaN.\n isNaN(n) ? isNaN(s) ? 0 : -1 : 1;\n }(t, e);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return re(t.timestampValue, e.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return re(Xt(t), Xt(e));\n\n case 5 /* TypeOrder.StringValue */ :\n return Z(t.stringValue, e.stringValue);\n\n case 6 /* TypeOrder.BlobValue */ :\n return function(t, e) {\n const n = Ht(t), s = Ht(e);\n return n.compareTo(s);\n }(t.bytesValue, e.bytesValue);\n\n case 7 /* TypeOrder.RefValue */ :\n return function(t, e) {\n const n = t.split(\"/\"), s = e.split(\"/\");\n for (let t = 0; t < n.length && t < s.length; t++) {\n const e = Z(n[t], s[t]);\n if (0 !== e) return e;\n }\n return Z(n.length, s.length);\n }(t.referenceValue, e.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return function(t, e) {\n const n = Z(zt(t.latitude), zt(e.latitude));\n if (0 !== n) return n;\n return Z(zt(t.longitude), zt(e.longitude));\n }(t.geoPointValue, e.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return function(t, e) {\n const n = t.values || [], s = e.values || [];\n for (let t = 0; t < n.length && t < s.length; ++t) {\n const e = ie(n[t], s[t]);\n if (e) return e;\n }\n return Z(n.length, s.length);\n }(t.arrayValue, e.arrayValue);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return function(t, e) {\n if (t === Zt.mapValue && e === Zt.mapValue) return 0;\n if (t === Zt.mapValue) return 1;\n if (e === Zt.mapValue) return -1;\n const n = t.fields || {}, s = Object.keys(n), i = e.fields || {}, r = Object.keys(i);\n // Even though MapValues are likely sorted correctly based on their insertion\n // order (e.g. when received from the backend), local modifications can bring\n // elements out of order. We need to re-sort the elements to ensure that\n // canonical IDs are independent of insertion order.\n s.sort(), r.sort();\n for (let t = 0; t < s.length && t < r.length; ++t) {\n const e = Z(s[t], r[t]);\n if (0 !== e) return e;\n const o = ie(n[s[t]], i[r[t]]);\n if (0 !== o) return o;\n }\n return Z(s.length, r.length);\n }\n /**\n * Generates the canonical ID for the provided field value (as used in Target\n * serialization).\n */ (t.mapValue, e.mapValue);\n\n default:\n throw O();\n }\n}\n\nfunction re(t, e) {\n if (\"string\" == typeof t && \"string\" == typeof e && t.length === e.length) return Z(t, e);\n const n = Wt(t), s = Wt(e), i = Z(n.seconds, s.seconds);\n return 0 !== i ? i : Z(n.nanos, s.nanos);\n}\n\nfunction oe(t) {\n return ue(t);\n}\n\nfunction ue(t) {\n return \"nullValue\" in t ? \"null\" : \"booleanValue\" in t ? \"\" + t.booleanValue : \"integerValue\" in t ? \"\" + t.integerValue : \"doubleValue\" in t ? \"\" + t.doubleValue : \"timestampValue\" in t ? function(t) {\n const e = Wt(t);\n return `time(${e.seconds},${e.nanos})`;\n }(t.timestampValue) : \"stringValue\" in t ? t.stringValue : \"bytesValue\" in t ? Ht(t.bytesValue).toBase64() : \"referenceValue\" in t ? (n = t.referenceValue, \n ct.fromName(n).toString()) : \"geoPointValue\" in t ? `geo(${(e = t.geoPointValue).latitude},${e.longitude})` : \"arrayValue\" in t ? function(t) {\n let e = \"[\", n = !0;\n for (const s of t.values || []) n ? n = !1 : e += \",\", e += ue(s);\n return e + \"]\";\n }\n /** Returns a reference value for the provided database and key. */ (t.arrayValue) : \"mapValue\" in t ? function(t) {\n // Iteration order in JavaScript is not guaranteed. To ensure that we generate\n // matching canonical IDs for identical maps, we need to sort the keys.\n const e = Object.keys(t.fields || {}).sort();\n let n = \"{\", s = !0;\n for (const i of e) s ? s = !1 : n += \",\", n += `${i}:${ue(t.fields[i])}`;\n return n + \"}\";\n }(t.mapValue) : O();\n var e, n;\n}\n\nfunction ce(t, e) {\n return {\n referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}`\n };\n}\n\n/** Returns true if `value` is an IntegerValue . */ function ae(t) {\n return !!t && \"integerValue\" in t;\n}\n\n/** Returns true if `value` is a DoubleValue. */\n/** Returns true if `value` is an ArrayValue. */\nfunction he(t) {\n return !!t && \"arrayValue\" in t;\n}\n\n/** Returns true if `value` is a NullValue. */ function le(t) {\n return !!t && \"nullValue\" in t;\n}\n\n/** Returns true if `value` is NaN. */ function fe(t) {\n return !!t && \"doubleValue\" in t && isNaN(Number(t.doubleValue));\n}\n\n/** Returns true if `value` is a MapValue. */ function de(t) {\n return !!t && \"mapValue\" in t;\n}\n\n/** Creates a deep copy of `source`. */ function _e(t) {\n if (t.geoPointValue) return {\n geoPointValue: Object.assign({}, t.geoPointValue)\n };\n if (t.timestampValue && \"object\" == typeof t.timestampValue) return {\n timestampValue: Object.assign({}, t.timestampValue)\n };\n if (t.mapValue) {\n const e = {\n mapValue: {\n fields: {}\n }\n };\n return Bt(t.mapValue.fields, ((t, n) => e.mapValue.fields[t] = _e(n))), e;\n }\n if (t.arrayValue) {\n const e = {\n arrayValue: {\n values: []\n }\n };\n for (let n = 0; n < (t.arrayValue.values || []).length; ++n) e.arrayValue.values[n] = _e(t.arrayValue.values[n]);\n return e;\n }\n return Object.assign({}, t);\n}\n\n/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function we(t) {\n return \"__max__\" === (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue;\n}\n\n/** Returns the lowest value for the given value type (inclusive). */ function me(t) {\n return \"nullValue\" in t ? te : \"booleanValue\" in t ? {\n booleanValue: !1\n } : \"integerValue\" in t || \"doubleValue\" in t ? {\n doubleValue: NaN\n } : \"timestampValue\" in t ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"stringValue\" in t ? {\n stringValue: \"\"\n } : \"bytesValue\" in t ? {\n bytesValue: \"\"\n } : \"referenceValue\" in t ? ce(Ft.empty(), ct.empty()) : \"geoPointValue\" in t ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"arrayValue\" in t ? {\n arrayValue: {}\n } : \"mapValue\" in t ? {\n mapValue: {}\n } : O();\n}\n\n/** Returns the largest value for the given value type (exclusive). */ function ge(t) {\n return \"nullValue\" in t ? {\n booleanValue: !1\n } : \"booleanValue\" in t ? {\n doubleValue: NaN\n } : \"integerValue\" in t || \"doubleValue\" in t ? {\n timestampValue: {\n seconds: Number.MIN_SAFE_INTEGER\n }\n } : \"timestampValue\" in t ? {\n stringValue: \"\"\n } : \"stringValue\" in t ? {\n bytesValue: \"\"\n } : \"bytesValue\" in t ? ce(Ft.empty(), ct.empty()) : \"referenceValue\" in t ? {\n geoPointValue: {\n latitude: -90,\n longitude: -180\n }\n } : \"geoPointValue\" in t ? {\n arrayValue: {}\n } : \"arrayValue\" in t ? {\n mapValue: {}\n } : \"mapValue\" in t ? Zt : O();\n}\n\nfunction ye(t, e) {\n const n = ie(t.value, e.value);\n return 0 !== n ? n : t.inclusive && !e.inclusive ? -1 : !t.inclusive && e.inclusive ? 1 : 0;\n}\n\nfunction pe(t, e) {\n const n = ie(t.value, e.value);\n return 0 !== n ? n : t.inclusive && !e.inclusive ? 1 : !t.inclusive && e.inclusive ? -1 : 0;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a bound of a query.\n *\n * The bound is specified with the given components representing a position and\n * whether it's just before or just after the position (relative to whatever the\n * query order is).\n *\n * The position represents a logical index position for a query. It's a prefix\n * of values for the (potentially implicit) order by clauses of a query.\n *\n * Bound provides a function to determine whether a document comes before or\n * after a bound. This is influenced by whether the position is just before or\n * just after the provided values.\n */ class Ie {\n constructor(t, e) {\n this.position = t, this.inclusive = e;\n }\n}\n\nfunction Te(t, e, n) {\n let s = 0;\n for (let i = 0; i < t.position.length; i++) {\n const r = e[i], o = t.position[i];\n if (r.field.isKeyField()) s = ct.comparator(ct.fromName(o.referenceValue), n.key); else {\n s = ie(o, n.data.field(r.field));\n }\n if (\"desc\" /* Direction.DESCENDING */ === r.dir && (s *= -1), 0 !== s) break;\n }\n return s;\n}\n\n/**\n * Returns true if a document sorts after a bound using the provided sort\n * order.\n */ function Ee(t, e) {\n if (null === t) return null === e;\n if (null === e) return !1;\n if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1;\n for (let n = 0; n < t.position.length; n++) {\n if (!ne(t.position[n], e.position[n])) return !1;\n }\n return !0;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Ae {}\n\nclass Re extends Ae {\n constructor(t, e, n) {\n super(), this.field = t, this.op = e, this.value = n;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(t, e, n) {\n return t.isKeyField() ? \"in\" /* Operator.IN */ === e || \"not-in\" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, n) : new ke(t, e, n) : \"array-contains\" /* Operator.ARRAY_CONTAINS */ === e ? new $e(t, n) : \"in\" /* Operator.IN */ === e ? new Be(t, n) : \"not-in\" /* Operator.NOT_IN */ === e ? new Le(t, n) : \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new qe(t, n) : new Re(t, e, n);\n }\n static createKeyFieldInFilter(t, e, n) {\n return \"in\" /* Operator.IN */ === e ? new Oe(t, n) : new Me(t, n);\n }\n matches(t) {\n const e = t.data.field(this.field);\n // Types do not have to match in NOT_EQUAL filters.\n return \"!=\" /* Operator.NOT_EQUAL */ === this.op ? null !== e && this.matchesComparison(ie(e, this.value)) : null !== e && ee(this.value) === ee(e) && this.matchesComparison(ie(e, this.value));\n // Only compare types with matching backend order (such as double and int).\n }\n matchesComparison(t) {\n switch (this.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n return t < 0;\n\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n return t <= 0;\n\n case \"==\" /* Operator.EQUAL */ :\n return 0 === t;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return 0 !== t;\n\n case \">\" /* Operator.GREATER_THAN */ :\n return t > 0;\n\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n return t >= 0;\n\n default:\n return O();\n }\n }\n isInequality() {\n return [ \"<\" /* Operator.LESS_THAN */ , \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ , \">\" /* Operator.GREATER_THAN */ , \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ , \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0;\n }\n getFlattenedFilters() {\n return [ this ];\n }\n getFilters() {\n return [ this ];\n }\n getFirstInequalityField() {\n return this.isInequality() ? this.field : null;\n }\n}\n\nclass be extends Ae {\n constructor(t, e) {\n super(), this.filters = t, this.op = e, this.ht = null;\n }\n /**\n * Creates a filter based on the provided arguments.\n */ static create(t, e) {\n return new be(t, e);\n }\n matches(t) {\n return Pe(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t)));\n }\n getFlattenedFilters() {\n return null !== this.ht || (this.ht = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), \n this.ht;\n }\n // Returns a mutable copy of `this.filters`\n getFilters() {\n return Object.assign([], this.filters);\n }\n getFirstInequalityField() {\n const t = this.lt((t => t.isInequality()));\n return null !== t ? t.field : null;\n }\n // Performs a depth-first search to find and return the first FieldFilter in the composite filter\n // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the\n // predicate.\n lt(t) {\n for (const e of this.getFlattenedFilters()) if (t(e)) return e;\n return null;\n }\n}\n\nfunction Pe(t) {\n return \"and\" /* CompositeOperator.AND */ === t.op;\n}\n\nfunction ve(t) {\n return \"or\" /* CompositeOperator.OR */ === t.op;\n}\n\n/**\n * Returns true if this filter is a conjunction of field filters only. Returns false otherwise.\n */ function Ve(t) {\n return Se(t) && Pe(t);\n}\n\n/**\n * Returns true if this filter does not contain any composite filters. Returns false otherwise.\n */ function Se(t) {\n for (const e of t.filters) if (e instanceof be) return !1;\n return !0;\n}\n\nfunction De(t) {\n if (t instanceof Re) \n // TODO(b/29183165): Technically, this won't be unique if two values have\n // the same description, such as the int 3 and the string \"3\". So we should\n // add the types in here somehow, too.\n return t.field.canonicalString() + t.op.toString() + oe(t.value);\n if (Ve(t)) \n // Older SDK versions use an implicit AND operation between their filters.\n // In the new SDK versions, the developer may use an explicit AND filter.\n // To stay consistent with the old usages, we add a special case to ensure\n // the canonical ID for these two are the same. For example:\n // `col.whereEquals(\"a\", 1).whereEquals(\"b\", 2)` should have the same\n // canonical ID as `col.where(and(equals(\"a\",1), equals(\"b\",2)))`.\n return t.filters.map((t => De(t))).join(\",\");\n {\n // filter instanceof CompositeFilter\n const e = t.filters.map((t => De(t))).join(\",\");\n return `${t.op}(${e})`;\n }\n}\n\nfunction Ce(t, e) {\n return t instanceof Re ? function(t, e) {\n return e instanceof Re && t.op === e.op && t.field.isEqual(e.field) && ne(t.value, e.value);\n }(t, e) : t instanceof be ? function(t, e) {\n if (e instanceof be && t.op === e.op && t.filters.length === e.filters.length) {\n return t.filters.reduce(((t, n, s) => t && Ce(n, e.filters[s])), !0);\n }\n return !1;\n }\n /**\n * Returns a new composite filter that contains all filter from\n * `compositeFilter` plus all the given filters in `otherFilters`.\n */ (t, e) : void O();\n}\n\nfunction xe(t, e) {\n const n = t.filters.concat(e);\n return be.create(n, t.op);\n}\n\n/** Returns a debug description for `filter`. */ function Ne(t) {\n return t instanceof Re ? function(t) {\n return `${t.field.canonicalString()} ${t.op} ${oe(t.value)}`;\n }\n /** Filter that matches on key fields (i.e. '__name__'). */ (t) : t instanceof be ? function(t) {\n return t.op.toString() + \" {\" + t.getFilters().map(Ne).join(\" ,\") + \"}\";\n }(t) : \"Filter\";\n}\n\nclass ke extends Re {\n constructor(t, e, n) {\n super(t, e, n), this.key = ct.fromName(n.referenceValue);\n }\n matches(t) {\n const e = ct.comparator(t.key, this.key);\n return this.matchesComparison(e);\n }\n}\n\n/** Filter that matches on key fields within an array. */ class Oe extends Re {\n constructor(t, e) {\n super(t, \"in\" /* Operator.IN */ , e), this.keys = Fe(\"in\" /* Operator.IN */ , e);\n }\n matches(t) {\n return this.keys.some((e => e.isEqual(t.key)));\n }\n}\n\n/** Filter that matches on key fields not present within an array. */ class Me extends Re {\n constructor(t, e) {\n super(t, \"not-in\" /* Operator.NOT_IN */ , e), this.keys = Fe(\"not-in\" /* Operator.NOT_IN */ , e);\n }\n matches(t) {\n return !this.keys.some((e => e.isEqual(t.key)));\n }\n}\n\nfunction Fe(t, e) {\n var n;\n return ((null === (n = e.arrayValue) || void 0 === n ? void 0 : n.values) || []).map((t => ct.fromName(t.referenceValue)));\n}\n\n/** A Filter that implements the array-contains operator. */ class $e extends Re {\n constructor(t, e) {\n super(t, \"array-contains\" /* Operator.ARRAY_CONTAINS */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return he(e) && se(e.arrayValue, this.value);\n }\n}\n\n/** A Filter that implements the IN operator. */ class Be extends Re {\n constructor(t, e) {\n super(t, \"in\" /* Operator.IN */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return null !== e && se(this.value.arrayValue, e);\n }\n}\n\n/** A Filter that implements the not-in operator. */ class Le extends Re {\n constructor(t, e) {\n super(t, \"not-in\" /* Operator.NOT_IN */ , e);\n }\n matches(t) {\n if (se(this.value.arrayValue, {\n nullValue: \"NULL_VALUE\"\n })) return !1;\n const e = t.data.field(this.field);\n return null !== e && !se(this.value.arrayValue, e);\n }\n}\n\n/** A Filter that implements the array-contains-any operator. */ class qe extends Re {\n constructor(t, e) {\n super(t, \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , e);\n }\n matches(t) {\n const e = t.data.field(this.field);\n return !(!he(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => se(this.value.arrayValue, t)));\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\n */ class Ue {\n constructor(t, e = \"asc\" /* Direction.ASCENDING */) {\n this.field = t, this.dir = e;\n }\n}\n\nfunction Ke(t, e) {\n return t.dir === e.dir && t.field.isEqual(e.field);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\nclass Ge {\n constructor(t, e) {\n this.comparator = t, this.root = e || je.EMPTY;\n }\n // Returns a copy of the map, with the specified key/value added or replaced.\n insert(t, e) {\n return new Ge(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, je.BLACK, null, null));\n }\n // Returns a copy of the map, with the specified key removed.\n remove(t) {\n return new Ge(this.comparator, this.root.remove(t, this.comparator).copy(null, null, je.BLACK, null, null));\n }\n // Returns the value of the node with the given key, or null.\n get(t) {\n let e = this.root;\n for (;!e.isEmpty(); ) {\n const n = this.comparator(t, e.key);\n if (0 === n) return e.value;\n n < 0 ? e = e.left : n > 0 && (e = e.right);\n }\n return null;\n }\n // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n indexOf(t) {\n // Number of nodes that were pruned when descending right\n let e = 0, n = this.root;\n for (;!n.isEmpty(); ) {\n const s = this.comparator(t, n.key);\n if (0 === s) return e + n.left.size;\n s < 0 ? n = n.left : (\n // Count all nodes left of the node plus the node itself\n e += n.left.size + 1, n = n.right);\n }\n // Node not found\n return -1;\n }\n isEmpty() {\n return this.root.isEmpty();\n }\n // Returns the total number of nodes in the map.\n get size() {\n return this.root.size;\n }\n // Returns the minimum key in the map.\n minKey() {\n return this.root.minKey();\n }\n // Returns the maximum key in the map.\n maxKey() {\n return this.root.maxKey();\n }\n // Traverses the map in key order and calls the specified action function\n // for each key/value pair. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(t) {\n return this.root.inorderTraversal(t);\n }\n forEach(t) {\n this.inorderTraversal(((e, n) => (t(e, n), !1)));\n }\n toString() {\n const t = [];\n return this.inorderTraversal(((e, n) => (t.push(`${e}:${n}`), !1))), `{${t.join(\", \")}}`;\n }\n // Traverses the map in reverse key order and calls the specified action\n // function for each key/value pair. If action returns true, traversal is\n // aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(t) {\n return this.root.reverseTraversal(t);\n }\n // Returns an iterator over the SortedMap.\n getIterator() {\n return new Qe(this.root, null, this.comparator, !1);\n }\n getIteratorFrom(t) {\n return new Qe(this.root, t, this.comparator, !1);\n }\n getReverseIterator() {\n return new Qe(this.root, null, this.comparator, !0);\n }\n getReverseIteratorFrom(t) {\n return new Qe(this.root, t, this.comparator, !0);\n }\n}\n\n // end SortedMap\n// An iterator over an LLRBNode.\nclass Qe {\n constructor(t, e, n, s) {\n this.isReverse = s, this.nodeStack = [];\n let i = 1;\n for (;!t.isEmpty(); ) if (i = e ? n(t.key, e) : 1, \n // flip the comparison if we're going in reverse\n e && s && (i *= -1), i < 0) \n // This node is less than our start key. ignore it\n t = this.isReverse ? t.left : t.right; else {\n if (0 === i) {\n // This node is exactly equal to our start key. Push it on the stack,\n // but stop iterating;\n this.nodeStack.push(t);\n break;\n }\n // This node is greater than our start key, add it to the stack and move\n // to the next one\n this.nodeStack.push(t), t = this.isReverse ? t.right : t.left;\n }\n }\n getNext() {\n let t = this.nodeStack.pop();\n const e = {\n key: t.key,\n value: t.value\n };\n if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), \n t = t.left;\n return e;\n }\n hasNext() {\n return this.nodeStack.length > 0;\n }\n peek() {\n if (0 === this.nodeStack.length) return null;\n const t = this.nodeStack[this.nodeStack.length - 1];\n return {\n key: t.key,\n value: t.value\n };\n }\n}\n\n // end SortedMapIterator\n// Represents a node in a Left-leaning Red-Black tree.\nclass je {\n constructor(t, e, n, s, i) {\n this.key = t, this.value = e, this.color = null != n ? n : je.RED, this.left = null != s ? s : je.EMPTY, \n this.right = null != i ? i : je.EMPTY, this.size = this.left.size + 1 + this.right.size;\n }\n // Returns a copy of the current node, optionally replacing pieces of it.\n copy(t, e, n, s, i) {\n return new je(null != t ? t : this.key, null != e ? e : this.value, null != n ? n : this.color, null != s ? s : this.left, null != i ? i : this.right);\n }\n isEmpty() {\n return !1;\n }\n // Traverses the tree in key order and calls the specified action function\n // for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n inorderTraversal(t) {\n return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t);\n }\n // Traverses the tree in reverse key order and calls the specified action\n // function for each node. If action returns true, traversal is aborted.\n // Returns the first truthy value returned by action, or the last falsey\n // value returned by action.\n reverseTraversal(t) {\n return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t);\n }\n // Returns the minimum node in the tree.\n min() {\n return this.left.isEmpty() ? this : this.left.min();\n }\n // Returns the maximum key in the tree.\n minKey() {\n return this.min().key;\n }\n // Returns the maximum key in the tree.\n maxKey() {\n return this.right.isEmpty() ? this.key : this.right.maxKey();\n }\n // Returns new tree, with the key/value added.\n insert(t, e, n) {\n let s = this;\n const i = n(t, s.key);\n return s = i < 0 ? s.copy(null, null, null, s.left.insert(t, e, n), null) : 0 === i ? s.copy(null, e, null, null, null) : s.copy(null, null, null, null, s.right.insert(t, e, n)), \n s.fixUp();\n }\n removeMin() {\n if (this.left.isEmpty()) return je.EMPTY;\n let t = this;\n return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), \n t.fixUp();\n }\n // Returns new tree, with the specified item removed.\n remove(t, e) {\n let n, s = this;\n if (e(t, s.key) < 0) s.left.isEmpty() || s.left.isRed() || s.left.left.isRed() || (s = s.moveRedLeft()), \n s = s.copy(null, null, null, s.left.remove(t, e), null); else {\n if (s.left.isRed() && (s = s.rotateRight()), s.right.isEmpty() || s.right.isRed() || s.right.left.isRed() || (s = s.moveRedRight()), \n 0 === e(t, s.key)) {\n if (s.right.isEmpty()) return je.EMPTY;\n n = s.right.min(), s = s.copy(n.key, n.value, null, null, s.right.removeMin());\n }\n s = s.copy(null, null, null, null, s.right.remove(t, e));\n }\n return s.fixUp();\n }\n isRed() {\n return this.color;\n }\n // Returns new tree after performing any needed rotations.\n fixUp() {\n let t = this;\n return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), \n t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t;\n }\n moveRedLeft() {\n let t = this.colorFlip();\n return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), \n t = t.rotateLeft(), t = t.colorFlip()), t;\n }\n moveRedRight() {\n let t = this.colorFlip();\n return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t;\n }\n rotateLeft() {\n const t = this.copy(null, null, je.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, t, null);\n }\n rotateRight() {\n const t = this.copy(null, null, je.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, t);\n }\n colorFlip() {\n const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, t, e);\n }\n // For testing.\n checkMaxDepth() {\n const t = this.check();\n return Math.pow(2, t) <= this.size + 1;\n }\n // In a balanced RB tree, the black-depth (number of black nodes) from root to\n // leaves is equal on both sides. This function verifies that or asserts.\n check() {\n if (this.isRed() && this.left.isRed()) throw O();\n if (this.right.isRed()) throw O();\n const t = this.left.check();\n if (t !== this.right.check()) throw O();\n return t + (this.isRed() ? 0 : 1);\n }\n}\n\n // end LLRBNode\n// Empty node is shared between all LLRB trees.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nje.EMPTY = null, je.RED = !0, je.BLACK = !1;\n\n// end LLRBEmptyNode\nje.EMPTY = new \n// Represents an empty node (a leaf node in the Red-Black Tree).\nclass {\n constructor() {\n this.size = 0;\n }\n get key() {\n throw O();\n }\n get value() {\n throw O();\n }\n get color() {\n throw O();\n }\n get left() {\n throw O();\n }\n get right() {\n throw O();\n }\n // Returns a copy of the current node.\n copy(t, e, n, s, i) {\n return this;\n }\n // Returns a copy of the tree, with the specified key/value added.\n insert(t, e, n) {\n return new je(t, e);\n }\n // Returns a copy of the tree, with the specified key removed.\n remove(t, e) {\n return this;\n }\n isEmpty() {\n return !0;\n }\n inorderTraversal(t) {\n return !1;\n }\n reverseTraversal(t) {\n return !1;\n }\n minKey() {\n return null;\n }\n maxKey() {\n return null;\n }\n isRed() {\n return !1;\n }\n // For testing.\n checkMaxDepth() {\n return !0;\n }\n check() {\n return 0;\n }\n};\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * SortedSet is an immutable (copy-on-write) collection that holds elements\n * in order specified by the provided comparator.\n *\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\n * be equal!\n */\nclass We {\n constructor(t) {\n this.comparator = t, this.data = new Ge(this.comparator);\n }\n has(t) {\n return null !== this.data.get(t);\n }\n first() {\n return this.data.minKey();\n }\n last() {\n return this.data.maxKey();\n }\n get size() {\n return this.data.size;\n }\n indexOf(t) {\n return this.data.indexOf(t);\n }\n /** Iterates elements in order defined by \"comparator\" */ forEach(t) {\n this.data.inorderTraversal(((e, n) => (t(e), !1)));\n }\n /** Iterates over `elem`s such that: range[0] &lt;= elem &lt; range[1]. */ forEachInRange(t, e) {\n const n = this.data.getIteratorFrom(t[0]);\n for (;n.hasNext(); ) {\n const s = n.getNext();\n if (this.comparator(s.key, t[1]) >= 0) return;\n e(s.key);\n }\n }\n /**\n * Iterates over `elem`s such that: start &lt;= elem until false is returned.\n */ forEachWhile(t, e) {\n let n;\n for (n = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); n.hasNext(); ) {\n if (!t(n.getNext().key)) return;\n }\n }\n /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) {\n const e = this.data.getIteratorFrom(t);\n return e.hasNext() ? e.getNext().key : null;\n }\n getIterator() {\n return new ze(this.data.getIterator());\n }\n getIteratorFrom(t) {\n return new ze(this.data.getIteratorFrom(t));\n }\n /** Inserts or updates an element */ add(t) {\n return this.copy(this.data.remove(t).insert(t, !0));\n }\n /** Deletes an element */ delete(t) {\n return this.has(t) ? this.copy(this.data.remove(t)) : this;\n }\n isEmpty() {\n return this.data.isEmpty();\n }\n unionWith(t) {\n let e = this;\n // Make sure `result` always refers to the larger one of the two sets.\n return e.size < t.size && (e = t, t = this), t.forEach((t => {\n e = e.add(t);\n })), e;\n }\n isEqual(t) {\n if (!(t instanceof We)) return !1;\n if (this.size !== t.size) return !1;\n const e = this.data.getIterator(), n = t.data.getIterator();\n for (;e.hasNext(); ) {\n const t = e.getNext().key, s = n.getNext().key;\n if (0 !== this.comparator(t, s)) return !1;\n }\n return !0;\n }\n toArray() {\n const t = [];\n return this.forEach((e => {\n t.push(e);\n })), t;\n }\n toString() {\n const t = [];\n return this.forEach((e => t.push(e))), \"SortedSet(\" + t.toString() + \")\";\n }\n copy(t) {\n const e = new We(this.comparator);\n return e.data = t, e;\n }\n}\n\nclass ze {\n constructor(t) {\n this.iter = t;\n }\n getNext() {\n return this.iter.getNext().key;\n }\n hasNext() {\n return this.iter.hasNext();\n }\n}\n\n/**\n * Compares two sorted sets for equality using their natural ordering. The\n * method computes the intersection and invokes `onAdd` for every element that\n * is in `after` but not `before`. `onRemove` is invoked for every element in\n * `before` but missing from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original set.\n * @param after - The elements to diff against the original set.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */\n/**\n * Returns the next element from the iterator or `undefined` if none available.\n */\nfunction He(t) {\n return t.hasNext() ? t.getNext() : void 0;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a set of fields that can be used to partially patch a document.\n * FieldMask is used in conjunction with ObjectValue.\n * Examples:\n * foo - Overwrites foo entirely with the provided value. If foo is not\n * present in the companion ObjectValue, the field is deleted.\n * foo.bar - Overwrites only the field bar of the object foo.\n * If foo is not an object, foo is replaced with an object\n * containing foo\n */ class Je {\n constructor(t) {\n this.fields = t, \n // TODO(dimond): validation of FieldMask\n // Sort the field mask to support `FieldMask.isEqual()` and assert below.\n t.sort(ut.comparator);\n }\n static empty() {\n return new Je([]);\n }\n /**\n * Returns a new FieldMask object that is the result of adding all the given\n * fields paths to this field mask.\n */ unionWith(t) {\n let e = new We(ut.comparator);\n for (const t of this.fields) e = e.add(t);\n for (const n of t) e = e.add(n);\n return new Je(e.toArray());\n }\n /**\n * Verifies that `fieldPath` is included by at least one field in this field\n * mask.\n *\n * This is an O(n) operation, where `n` is the size of the field mask.\n */ covers(t) {\n for (const e of this.fields) if (e.isPrefixOf(t)) return !0;\n return !1;\n }\n isEqual(t) {\n return tt(this.fields, t.fields, ((t, e) => t.isEqual(e)));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An ObjectValue represents a MapValue in the Firestore Proto and offers the\n * ability to add and remove fields (via the ObjectValueBuilder).\n */ class Ye {\n constructor(t) {\n this.value = t;\n }\n static empty() {\n return new Ye({\n mapValue: {}\n });\n }\n /**\n * Returns the value at the given path or null.\n *\n * @param path - the path to search\n * @returns The value at the path or null if the path is not set.\n */ field(t) {\n if (t.isEmpty()) return this.value;\n {\n let e = this.value;\n for (let n = 0; n < t.length - 1; ++n) if (e = (e.mapValue.fields || {})[t.get(n)], \n !de(e)) return null;\n return e = (e.mapValue.fields || {})[t.lastSegment()], e || null;\n }\n }\n /**\n * Sets the field to the provided value.\n *\n * @param path - The field path to set.\n * @param value - The value to set.\n */ set(t, e) {\n this.getFieldsMap(t.popLast())[t.lastSegment()] = _e(e);\n }\n /**\n * Sets the provided fields to the provided values.\n *\n * @param data - A map of fields to values (or null for deletes).\n */ setAll(t) {\n let e = ut.emptyPath(), n = {}, s = [];\n t.forEach(((t, i) => {\n if (!e.isImmediateParentOf(i)) {\n // Insert the accumulated changes at this parent location\n const t = this.getFieldsMap(e);\n this.applyChanges(t, n, s), n = {}, s = [], e = i.popLast();\n }\n t ? n[i.lastSegment()] = _e(t) : s.push(i.lastSegment());\n }));\n const i = this.getFieldsMap(e);\n this.applyChanges(i, n, s);\n }\n /**\n * Removes the field at the specified path. If there is no field at the\n * specified path, nothing is changed.\n *\n * @param path - The field path to remove.\n */ delete(t) {\n const e = this.field(t.popLast());\n de(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()];\n }\n isEqual(t) {\n return ne(this.value, t.value);\n }\n /**\n * Returns the map that contains the leaf element of `path`. If the parent\n * entry does not yet exist, or if it is not a map, a new map will be created.\n */ getFieldsMap(t) {\n let e = this.value;\n e.mapValue.fields || (e.mapValue = {\n fields: {}\n });\n for (let n = 0; n < t.length; ++n) {\n let s = e.mapValue.fields[t.get(n)];\n de(s) && s.mapValue.fields || (s = {\n mapValue: {\n fields: {}\n }\n }, e.mapValue.fields[t.get(n)] = s), e = s;\n }\n return e.mapValue.fields;\n }\n /**\n * Modifies `fieldsMap` by adding, replacing or deleting the specified\n * entries.\n */ applyChanges(t, e, n) {\n Bt(e, ((e, n) => t[e] = n));\n for (const e of n) delete t[e];\n }\n clone() {\n return new Ye(_e(this.value));\n }\n}\n\n/**\n * Returns a FieldMask built from all fields in a MapValue.\n */ function Xe(t) {\n const e = [];\n return Bt(t.fields, ((t, n) => {\n const s = new ut([ t ]);\n if (de(n)) {\n const t = Xe(n.mapValue).fields;\n if (0 === t.length) \n // Preserve the empty map by adding it to the FieldMask.\n e.push(s); else \n // For nested and non-empty ObjectValues, add the FieldPath of the\n // leaf nodes.\n for (const n of t) e.push(s.child(n));\n } else \n // For nested and non-empty ObjectValues, add the FieldPath of the leaf\n // nodes.\n e.push(s);\n })), new Je(e);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a document in Firestore with a key, version, data and whether it\n * has local mutations applied to it.\n *\n * Documents can transition between states via `convertToFoundDocument()`,\n * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does\n * not transition to one of these states even after all mutations have been\n * applied, `isValidDocument()` returns false and the document should be removed\n * from all views.\n */ class Ze {\n constructor(t, e, n, s, i, r, o) {\n this.key = t, this.documentType = e, this.version = n, this.readTime = s, this.createTime = i, \n this.data = r, this.documentState = o;\n }\n /**\n * Creates a document with no known version or data, but which can serve as\n * base document for mutations.\n */ static newInvalidDocument(t) {\n return new Ze(t, 0 /* DocumentType.INVALID */ , \n /* version */ st.min(), \n /* readTime */ st.min(), \n /* createTime */ st.min(), Ye.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist with the given data at the\n * given version.\n */ static newFoundDocument(t, e, n, s) {\n return new Ze(t, 1 /* DocumentType.FOUND_DOCUMENT */ , \n /* version */ e, \n /* readTime */ st.min(), \n /* createTime */ n, s, 0 /* DocumentState.SYNCED */);\n }\n /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) {\n return new Ze(t, 2 /* DocumentType.NO_DOCUMENT */ , \n /* version */ e, \n /* readTime */ st.min(), \n /* createTime */ st.min(), Ye.empty(), 0 /* DocumentState.SYNCED */);\n }\n /**\n * Creates a new document that is known to exist at the given version but\n * whose data is not known (e.g. a document that was updated without a known\n * base document).\n */ static newUnknownDocument(t, e) {\n return new Ze(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n /* version */ e, \n /* readTime */ st.min(), \n /* createTime */ st.min(), Ye.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */);\n }\n /**\n * Changes the document type to indicate that it exists and that its version\n * and data are known.\n */ convertToFoundDocument(t, e) {\n // If a document is switching state from being an invalid or deleted\n // document to a valid (FOUND_DOCUMENT) document, either due to receiving an\n // update from Watch or due to applying a local set mutation on top\n // of a deleted document, our best guess about its createTime would be the\n // version at which the document transitioned to a FOUND_DOCUMENT.\n return !this.createTime.isEqual(st.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), \n this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, \n this.documentState = 0 /* DocumentState.SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it doesn't exist at the given\n * version.\n */ convertToNoDocument(t) {\n return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , \n this.data = Ye.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , this;\n }\n /**\n * Changes the document type to indicate that it exists at a given version but\n * that its data is not known (e.g. a document that was updated without a known\n * base document).\n */ convertToUnknownDocument(t) {\n return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , \n this.data = Ye.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , \n this;\n }\n setHasCommittedMutations() {\n return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this;\n }\n setHasLocalMutations() {\n return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = st.min(), \n this;\n }\n setReadTime(t) {\n return this.readTime = t, this;\n }\n get hasLocalMutations() {\n return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState;\n }\n get hasCommittedMutations() {\n return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState;\n }\n get hasPendingWrites() {\n return this.hasLocalMutations || this.hasCommittedMutations;\n }\n isValidDocument() {\n return 0 /* DocumentType.INVALID */ !== this.documentType;\n }\n isFoundDocument() {\n return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType;\n }\n isNoDocument() {\n return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType;\n }\n isUnknownDocument() {\n return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType;\n }\n isEqual(t) {\n return t instanceof Ze && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data);\n }\n mutableCopy() {\n return new Ze(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState);\n }\n toString() {\n return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`;\n }\n}\n\n/**\n * Compares the value for field `field` in the provided documents. Throws if\n * the field does not exist in both documents.\n */\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Visible for testing\nclass tn {\n constructor(t, e = null, n = [], s = [], i = null, r = null, o = null) {\n this.path = t, this.collectionGroup = e, this.orderBy = n, this.filters = s, this.limit = i, \n this.startAt = r, this.endAt = o, this.ft = null;\n }\n}\n\n/**\n * Initializes a Target with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n *\n * NOTE: you should always construct `Target` from `Query.toTarget` instead of\n * using this factory method, because `Query` provides an implicit `orderBy`\n * property.\n */ function en(t, e = null, n = [], s = [], i = null, r = null, o = null) {\n return new tn(t, e, n, s, i, r, o);\n}\n\nfunction nn(t) {\n const e = $(t);\n if (null === e.ft) {\n let t = e.path.canonicalString();\n null !== e.collectionGroup && (t += \"|cg:\" + e.collectionGroup), t += \"|f:\", t += e.filters.map((t => De(t))).join(\",\"), \n t += \"|ob:\", t += e.orderBy.map((t => function(t) {\n // TODO(b/29183165): Make this collision robust.\n return t.field.canonicalString() + t.dir;\n }(t))).join(\",\"), qt(e.limit) || (t += \"|l:\", t += e.limit), e.startAt && (t += \"|lb:\", \n t += e.startAt.inclusive ? \"b:\" : \"a:\", t += e.startAt.position.map((t => oe(t))).join(\",\")), \n e.endAt && (t += \"|ub:\", t += e.endAt.inclusive ? \"a:\" : \"b:\", t += e.endAt.position.map((t => oe(t))).join(\",\")), \n e.ft = t;\n }\n return e.ft;\n}\n\nfunction sn(t, e) {\n if (t.limit !== e.limit) return !1;\n if (t.orderBy.length !== e.orderBy.length) return !1;\n for (let n = 0; n < t.orderBy.length; n++) if (!Ke(t.orderBy[n], e.orderBy[n])) return !1;\n if (t.filters.length !== e.filters.length) return !1;\n for (let n = 0; n < t.filters.length; n++) if (!Ce(t.filters[n], e.filters[n])) return !1;\n return t.collectionGroup === e.collectionGroup && (!!t.path.isEqual(e.path) && (!!Ee(t.startAt, e.startAt) && Ee(t.endAt, e.endAt)));\n}\n\nfunction rn(t) {\n return ct.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;\n}\n\n/** Returns the field filters that target the given field path. */ function on(t, e) {\n return t.filters.filter((t => t instanceof Re && t.field.isEqual(e)));\n}\n\n/**\n * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY\n * filters. Returns `null` if there are no such filters.\n */\n/**\n * Returns the value to use as the lower bound for ascending index segment at\n * the provided `fieldPath` (or the upper bound for an descending segment).\n */\nfunction un(t, e, n) {\n let s = te, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of on(t, e)) {\n let t = te, e = !0;\n switch (n.op) {\n case \"<\" /* Operator.LESS_THAN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n t = me(n.value);\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n t = n.value;\n break;\n\n case \">\" /* Operator.GREATER_THAN */ :\n t = n.value, e = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n t = te;\n // Remaining filters cannot be used as lower bounds.\n }\n ye({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: e\n }) < 0 && (s = t, i = e);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {\n if (t.orderBy[r].field.isEqual(e)) {\n const t = n.position[r];\n ye({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: n.inclusive\n }) < 0 && (s = t, i = n.inclusive);\n break;\n }\n }\n return {\n value: s,\n inclusive: i\n };\n}\n\n/**\n * Returns the value to use as the upper bound for ascending index segment at\n * the provided `fieldPath` (or the lower bound for a descending segment).\n */ function cn(t, e, n) {\n let s = Zt, i = !0;\n // Process all filters to find a value for the current field segment\n for (const n of on(t, e)) {\n let t = Zt, e = !0;\n switch (n.op) {\n case \">=\" /* Operator.GREATER_THAN_OR_EQUAL */ :\n case \">\" /* Operator.GREATER_THAN */ :\n t = ge(n.value), e = !1;\n break;\n\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n case \"<=\" /* Operator.LESS_THAN_OR_EQUAL */ :\n t = n.value;\n break;\n\n case \"<\" /* Operator.LESS_THAN */ :\n t = n.value, e = !1;\n break;\n\n case \"!=\" /* Operator.NOT_EQUAL */ :\n case \"not-in\" /* Operator.NOT_IN */ :\n t = Zt;\n // Remaining filters cannot be used as upper bounds.\n }\n pe({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: e\n }) > 0 && (s = t, i = e);\n }\n // If there is an additional bound, compare the values against the existing\n // range to see if we can narrow the scope.\n if (null !== n) for (let r = 0; r < t.orderBy.length; ++r) {\n if (t.orderBy[r].field.isEqual(e)) {\n const t = n.position[r];\n pe({\n value: s,\n inclusive: i\n }, {\n value: t,\n inclusive: n.inclusive\n }) > 0 && (s = t, i = n.inclusive);\n break;\n }\n }\n return {\n value: s,\n inclusive: i\n };\n}\n\n/** Returns the number of segments of a perfect index for this target. */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Query encapsulates all the query attributes we support in the SDK. It can\n * be run against the LocalStore, as well as be converted to a `Target` to\n * query the RemoteStore results.\n *\n * Visible for testing.\n */\nclass an {\n /**\n * Initializes a Query with a path and optional additional query constraints.\n * Path must currently be empty if this is a collection group query.\n */\n constructor(t, e = null, n = [], s = [], i = null, r = \"F\" /* LimitType.First */ , o = null, u = null) {\n this.path = t, this.collectionGroup = e, this.explicitOrderBy = n, this.filters = s, \n this.limit = i, this.limitType = r, this.startAt = o, this.endAt = u, this.dt = null, \n // The corresponding `Target` of this `Query` instance.\n this._t = null, this.startAt, this.endAt;\n }\n}\n\n/** Creates a new Query instance with the options provided. */ function hn(t, e, n, s, i, r, o, u) {\n return new an(t, e, n, s, i, r, o, u);\n}\n\n/** Creates a new Query for a query that matches all documents at `path` */ function ln(t) {\n return new an(t);\n}\n\n/**\n * Helper to convert a collection group query into a collection query at a\n * specific path. This is used when executing collection group queries, since\n * we have to split the query into a set of collection queries at multiple\n * paths.\n */\n/**\n * Returns true if this query does not specify any query constraints that\n * could remove results.\n */\nfunction fn(t) {\n return 0 === t.filters.length && null === t.limit && null == t.startAt && null == t.endAt && (0 === t.explicitOrderBy.length || 1 === t.explicitOrderBy.length && t.explicitOrderBy[0].field.isKeyField());\n}\n\nfunction dn(t) {\n return t.explicitOrderBy.length > 0 ? t.explicitOrderBy[0].field : null;\n}\n\nfunction _n(t) {\n for (const e of t.filters) {\n const t = e.getFirstInequalityField();\n if (null !== t) return t;\n }\n return null;\n}\n\n/**\n * Creates a new Query for a collection group query that matches all documents\n * within the provided collection group.\n */\n/**\n * Returns whether the query matches a collection group rather than a specific\n * collection.\n */\nfunction wn(t) {\n return null !== t.collectionGroup;\n}\n\n/**\n * Returns the implicit order by constraint that is used to execute the Query,\n * which can be different from the order by constraints the user provided (e.g.\n * the SDK and backend always orders by `__name__`).\n */ function mn(t) {\n const e = $(t);\n if (null === e.dt) {\n e.dt = [];\n const t = _n(e), n = dn(e);\n if (null !== t && null === n) \n // In order to implicitly add key ordering, we must also add the\n // inequality filter field for it to be a valid query.\n // Note that the default inequality field and key ordering is ascending.\n t.isKeyField() || e.dt.push(new Ue(t)), e.dt.push(new Ue(ut.keyField(), \"asc\" /* Direction.ASCENDING */)); else {\n let t = !1;\n for (const n of e.explicitOrderBy) e.dt.push(n), n.field.isKeyField() && (t = !0);\n if (!t) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n const t = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : \"asc\" /* Direction.ASCENDING */;\n e.dt.push(new Ue(ut.keyField(), t));\n }\n }\n }\n return e.dt;\n}\n\n/**\n * Converts this `Query` instance to it's corresponding `Target` representation.\n */ function gn(t) {\n const e = $(t);\n if (!e._t) if (\"F\" /* LimitType.First */ === e.limitType) e._t = en(e.path, e.collectionGroup, mn(e), e.filters, e.limit, e.startAt, e.endAt); else {\n // Flip the orderBy directions since we want the last results\n const t = [];\n for (const n of mn(e)) {\n const e = \"desc\" /* Direction.DESCENDING */ === n.dir ? \"asc\" /* Direction.ASCENDING */ : \"desc\" /* Direction.DESCENDING */;\n t.push(new Ue(n.field, e));\n }\n // We need to swap the cursors to match the now-flipped query ordering.\n const n = e.endAt ? new Ie(e.endAt.position, e.endAt.inclusive) : null, s = e.startAt ? new Ie(e.startAt.position, e.startAt.inclusive) : null;\n // Now return as a LimitType.First query.\n e._t = en(e.path, e.collectionGroup, t, e.filters, e.limit, n, s);\n }\n return e._t;\n}\n\nfunction yn(t, e) {\n e.getFirstInequalityField(), _n(t);\n const n = t.filters.concat([ e ]);\n return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), n, t.limit, t.limitType, t.startAt, t.endAt);\n}\n\nfunction pn(t, e, n) {\n return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, n, t.startAt, t.endAt);\n}\n\nfunction In(t, e) {\n return sn(gn(t), gn(e)) && t.limitType === e.limitType;\n}\n\n// TODO(b/29183165): This is used to get a unique string from a query to, for\n// example, use as a dictionary key, but the implementation is subject to\n// collisions. Make it collision-free.\nfunction Tn(t) {\n return `${nn(gn(t))}|lt:${t.limitType}`;\n}\n\nfunction En(t) {\n return `Query(target=${function(t) {\n let e = t.path.canonicalString();\n return null !== t.collectionGroup && (e += \" collectionGroup=\" + t.collectionGroup), \n t.filters.length > 0 && (e += `, filters: [${t.filters.map((t => Ne(t))).join(\", \")}]`), \n qt(t.limit) || (e += \", limit: \" + t.limit), t.orderBy.length > 0 && (e += `, orderBy: [${t.orderBy.map((t => function(t) {\n return `${t.field.canonicalString()} (${t.dir})`;\n }(t))).join(\", \")}]`), t.startAt && (e += \", startAt: \", e += t.startAt.inclusive ? \"b:\" : \"a:\", \n e += t.startAt.position.map((t => oe(t))).join(\",\")), t.endAt && (e += \", endAt: \", \n e += t.endAt.inclusive ? \"a:\" : \"b:\", e += t.endAt.position.map((t => oe(t))).join(\",\")), \n `Target(${e})`;\n }(gn(t))}; limitType=${t.limitType})`;\n}\n\n/** Returns whether `doc` matches the constraints of `query`. */ function An(t, e) {\n return e.isFoundDocument() && function(t, e) {\n const n = e.key.path;\n return null !== t.collectionGroup ? e.key.hasCollectionId(t.collectionGroup) && t.path.isPrefixOf(n) : ct.isDocumentKey(t.path) ? t.path.isEqual(n) : t.path.isImmediateParentOf(n);\n }\n /**\n * A document must have a value for every ordering clause in order to show up\n * in the results.\n */ (t, e) && function(t, e) {\n // We must use `queryOrderBy()` to get the list of all orderBys (both implicit and explicit).\n // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must\n // be taken into account. For example, the query \"a > 1 || b==1\" has an implicit \"orderBy a\" due\n // to the inequality, and is evaluated as \"a > 1 orderBy a || b==1 orderBy a\".\n // A document with content of {b:1} matches the filters, but does not match the orderBy because\n // it's missing the field 'a'.\n for (const n of mn(t)) \n // order by key always matches\n if (!n.field.isKeyField() && null === e.data.field(n.field)) return !1;\n return !0;\n }(t, e) && function(t, e) {\n for (const n of t.filters) if (!n.matches(e)) return !1;\n return !0;\n }\n /** Makes sure a document is within the bounds, if provided. */ (t, e) && function(t, e) {\n if (t.startAt && !\n /**\n * Returns true if a document sorts before a bound using the provided sort\n * order.\n */\n function(t, e, n) {\n const s = Te(t, e, n);\n return t.inclusive ? s <= 0 : s < 0;\n }(t.startAt, mn(t), e)) return !1;\n if (t.endAt && !function(t, e, n) {\n const s = Te(t, e, n);\n return t.inclusive ? s >= 0 : s > 0;\n }(t.endAt, mn(t), e)) return !1;\n return !0;\n }\n /**\n * Returns the collection group that this query targets.\n *\n * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab\n * synchronization for query results.\n */ (t, e);\n}\n\nfunction Rn(t) {\n return t.collectionGroup || (t.path.length % 2 == 1 ? t.path.lastSegment() : t.path.get(t.path.length - 2));\n}\n\n/**\n * Returns a new comparator function that can be used to compare two documents\n * based on the Query's ordering constraint.\n */ function bn(t) {\n return (e, n) => {\n let s = !1;\n for (const i of mn(t)) {\n const t = Pn(i, e, n);\n if (0 !== t) return t;\n s = s || i.field.isKeyField();\n }\n return 0;\n };\n}\n\nfunction Pn(t, e, n) {\n const s = t.field.isKeyField() ? ct.comparator(e.key, n.key) : function(t, e, n) {\n const s = e.data.field(t), i = n.data.field(t);\n return null !== s && null !== i ? ie(s, i) : O();\n }(t.field, e, n);\n switch (t.dir) {\n case \"asc\" /* Direction.ASCENDING */ :\n return s;\n\n case \"desc\" /* Direction.DESCENDING */ :\n return -1 * s;\n\n default:\n return O();\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns an DoubleValue for `value` that is encoded based the serializer's\n * `useProto3Json` setting.\n */ function vn(t, e) {\n if (t.wt) {\n if (isNaN(e)) return {\n doubleValue: \"NaN\"\n };\n if (e === 1 / 0) return {\n doubleValue: \"Infinity\"\n };\n if (e === -1 / 0) return {\n doubleValue: \"-Infinity\"\n };\n }\n return {\n doubleValue: Ut(e) ? \"-0\" : e\n };\n}\n\n/**\n * Returns an IntegerValue for `value`.\n */ function Vn(t) {\n return {\n integerValue: \"\" + t\n };\n}\n\n/**\n * Returns a value for a number that's appropriate to put into a proto.\n * The return value is an IntegerValue if it can safely represent the value,\n * otherwise a DoubleValue is returned.\n */ function Sn(t, e) {\n return Kt(e) ? Vn(e) : vn(t, e);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Used to represent a field transform on a mutation. */ class Dn {\n constructor() {\n // Make sure that the structural type of `TransformOperation` is unique.\n // See https://github.com/microsoft/TypeScript/issues/5451\n this._ = void 0;\n }\n}\n\n/**\n * Computes the local transform result against the provided `previousValue`,\n * optionally using the provided localWriteTime.\n */ function Cn(t, e, n) {\n return t instanceof kn ? function(t, e) {\n const n = {\n fields: {\n __type__: {\n stringValue: \"server_timestamp\"\n },\n __local_write_time__: {\n timestampValue: {\n seconds: t.seconds,\n nanos: t.nanoseconds\n }\n }\n }\n };\n return e && (n.fields.__previous_value__ = e), {\n mapValue: n\n };\n }(n, e) : t instanceof On ? Mn(t, e) : t instanceof Fn ? $n(t, e) : function(t, e) {\n // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit\n // precision and resolves overflows by reducing precision, we do not\n // manually cap overflows at 2^63.\n const n = Nn(t, e), s = Ln(n) + Ln(t.gt);\n return ae(n) && ae(t.gt) ? Vn(s) : vn(t.yt, s);\n }(t, e);\n}\n\n/**\n * Computes a final transform result after the transform has been acknowledged\n * by the server, potentially using the server-provided transformResult.\n */ function xn(t, e, n) {\n // The server just sends null as the transform result for array operations,\n // so we have to calculate a result the same as we do for local\n // applications.\n return t instanceof On ? Mn(t, e) : t instanceof Fn ? $n(t, e) : n;\n}\n\n/**\n * If this transform operation is not idempotent, returns the base value to\n * persist for this transform. If a base value is returned, the transform\n * operation is always applied to this base value, even if document has\n * already been updated.\n *\n * Base values provide consistent behavior for non-idempotent transforms and\n * allow us to return the same latency-compensated value even if the backend\n * has already applied the transform operation. The base value is null for\n * idempotent transforms, as they can be re-played even if the backend has\n * already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent transforms.\n */ function Nn(t, e) {\n return t instanceof Bn ? ae(n = e) || function(t) {\n return !!t && \"doubleValue\" in t;\n }\n /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ (n) ? e : {\n integerValue: 0\n } : null;\n var n;\n}\n\n/** Transforms a value into a server-generated timestamp. */\nclass kn extends Dn {}\n\n/** Transforms an array value via a union operation. */ class On extends Dn {\n constructor(t) {\n super(), this.elements = t;\n }\n}\n\nfunction Mn(t, e) {\n const n = qn(e);\n for (const e of t.elements) n.some((t => ne(t, e))) || n.push(e);\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/** Transforms an array value via a remove operation. */ class Fn extends Dn {\n constructor(t) {\n super(), this.elements = t;\n }\n}\n\nfunction $n(t, e) {\n let n = qn(e);\n for (const e of t.elements) n = n.filter((t => !ne(t, e)));\n return {\n arrayValue: {\n values: n\n }\n };\n}\n\n/**\n * Implements the backend semantics for locally computed NUMERIC_ADD (increment)\n * transforms. Converts all field values to integers or doubles, but unlike the\n * backend does not cap integer values at 2^63. Instead, JavaScript number\n * arithmetic is used and precision loss can occur for values greater than 2^53.\n */ class Bn extends Dn {\n constructor(t, e) {\n super(), this.yt = t, this.gt = e;\n }\n}\n\nfunction Ln(t) {\n return zt(t.integerValue || t.doubleValue);\n}\n\nfunction qn(t) {\n return he(t) && t.arrayValue.values ? t.arrayValue.values.slice() : [];\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A field path and the TransformOperation to perform upon it. */ class Un {\n constructor(t, e) {\n this.field = t, this.transform = e;\n }\n}\n\nfunction Kn(t, e) {\n return t.field.isEqual(e.field) && function(t, e) {\n return t instanceof On && e instanceof On || t instanceof Fn && e instanceof Fn ? tt(t.elements, e.elements, ne) : t instanceof Bn && e instanceof Bn ? ne(t.gt, e.gt) : t instanceof kn && e instanceof kn;\n }(t.transform, e.transform);\n}\n\n/** The result of successfully applying a mutation to the backend. */\nclass Gn {\n constructor(\n /**\n * The version at which the mutation was committed:\n *\n * - For most operations, this is the updateTime in the WriteResult.\n * - For deletes, the commitTime of the WriteResponse (because deletes are\n * not stored and have no updateTime).\n *\n * Note that these versions can be different: No-op writes will not change\n * the updateTime even though the commitTime advances.\n */\n t, \n /**\n * The resulting fields returned from the backend after a mutation\n * containing field transforms has been committed. Contains one FieldValue\n * for each FieldTransform that was in the mutation.\n *\n * Will be empty if the mutation did not contain any field transforms.\n */\n e) {\n this.version = t, this.transformResults = e;\n }\n}\n\n/**\n * Encodes a precondition for a mutation. This follows the model that the\n * backend accepts with the special case of an explicit \"empty\" precondition\n * (meaning no precondition).\n */ class Qn {\n constructor(t, e) {\n this.updateTime = t, this.exists = e;\n }\n /** Creates a new empty Precondition. */ static none() {\n return new Qn;\n }\n /** Creates a new Precondition with an exists flag. */ static exists(t) {\n return new Qn(void 0, t);\n }\n /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) {\n return new Qn(t);\n }\n /** Returns whether this Precondition is empty. */ get isNone() {\n return void 0 === this.updateTime && void 0 === this.exists;\n }\n isEqual(t) {\n return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime);\n }\n}\n\n/** Returns true if the preconditions is valid for the given document. */ function jn(t, e) {\n return void 0 !== t.updateTime ? e.isFoundDocument() && e.version.isEqual(t.updateTime) : void 0 === t.exists || t.exists === e.isFoundDocument();\n}\n\n/**\n * A mutation describes a self-contained change to a document. Mutations can\n * create, replace, delete, and update subsets of documents.\n *\n * Mutations not only act on the value of the document but also its version.\n *\n * For local mutations (mutations that haven't been committed yet), we preserve\n * the existing version for Set and Patch mutations. For Delete mutations, we\n * reset the version to 0.\n *\n * Here's the expected transition table.\n *\n * MUTATION APPLIED TO RESULTS IN\n *\n * SetMutation Document(v3) Document(v3)\n * SetMutation NoDocument(v3) Document(v0)\n * SetMutation InvalidDocument(v0) Document(v0)\n * PatchMutation Document(v3) Document(v3)\n * PatchMutation NoDocument(v3) NoDocument(v3)\n * PatchMutation InvalidDocument(v0) UnknownDocument(v3)\n * DeleteMutation Document(v3) NoDocument(v0)\n * DeleteMutation NoDocument(v3) NoDocument(v0)\n * DeleteMutation InvalidDocument(v0) NoDocument(v0)\n *\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\n * the resulting version for Set and Patch mutations. As deletes have no\n * explicit update time, we use the commitTime of the WriteResponse for\n * Delete mutations.\n *\n * If a mutation is acknowledged by the backend but fails the precondition check\n * locally, we transition to an `UnknownDocument` and rely on Watch to send us\n * the updated version.\n *\n * Field transforms are used only with Patch and Set Mutations. We use the\n * `updateTransforms` message to store transforms, rather than the `transforms`s\n * messages.\n *\n * ## Subclassing Notes\n *\n * Every type of mutation needs to implement its own applyToRemoteDocument() and\n * applyToLocalView() to implement the actual behavior of applying the mutation\n * to some source document (see `setMutationApplyToRemoteDocument()` for an\n * example).\n */ class Wn {}\n\n/**\n * A utility method to calculate a `Mutation` representing the overlay from the\n * final state of the document, and a `FieldMask` representing the fields that\n * are mutated by the local mutations.\n */ function zn(t, e) {\n if (!t.hasLocalMutations || e && 0 === e.fields.length) return null;\n // mask is null when sets or deletes are applied to the current document.\n if (null === e) return t.isNoDocument() ? new is(t.key, Qn.none()) : new Zn(t.key, t.data, Qn.none());\n {\n const n = t.data, s = Ye.empty();\n let i = new We(ut.comparator);\n for (let t of e.fields) if (!i.has(t)) {\n let e = n.field(t);\n // If we are deleting a nested field, we take the immediate parent as\n // the mask used to construct the resulting mutation.\n // Justification: Nested fields can create parent fields implicitly. If\n // only a leaf entry is deleted in later mutations, the parent field\n // should still remain, but we may have lost this information.\n // Consider mutation (foo.bar 1), then mutation (foo.bar delete()).\n // This leaves the final result (foo, {}). Despite the fact that `doc`\n // has the correct result, `foo` is not in `mask`, and the resulting\n // mutation would miss `foo`.\n null === e && t.length > 1 && (t = t.popLast(), e = n.field(t)), null === e ? s.delete(t) : s.set(t, e), \n i = i.add(t);\n }\n return new ts(t.key, s, new Je(i.toArray()), Qn.none());\n }\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing a\n * new remote document. If the input document doesn't match the expected state\n * (e.g. it is invalid or outdated), the document type may transition to\n * unknown.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param mutationResult - The result of applying the mutation from the backend.\n */ function Hn(t, e, n) {\n t instanceof Zn ? function(t, e, n) {\n // Unlike setMutationApplyToLocalView, if we're applying a mutation to a\n // remote document the server has accepted the mutation so the precondition\n // must have held.\n const s = t.value.clone(), i = ns(t.fieldTransforms, e, n.transformResults);\n s.setAll(i), e.convertToFoundDocument(n.version, s).setHasCommittedMutations();\n }(t, e, n) : t instanceof ts ? function(t, e, n) {\n if (!jn(t.precondition, e)) \n // Since the mutation was not rejected, we know that the precondition\n // matched on the backend. We therefore must not have the expected version\n // of the document in our cache and convert to an UnknownDocument with a\n // known updateTime.\n return void e.convertToUnknownDocument(n.version);\n const s = ns(t.fieldTransforms, e, n.transformResults), i = e.data;\n i.setAll(es(t)), i.setAll(s), e.convertToFoundDocument(n.version, i).setHasCommittedMutations();\n }(t, e, n) : function(t, e, n) {\n // Unlike applyToLocalView, if we're applying a mutation to a remote\n // document the server has accepted the mutation so the precondition must\n // have held.\n e.convertToNoDocument(n.version).setHasCommittedMutations();\n }(0, e, n);\n}\n\n/**\n * Applies this mutation to the given document for the purposes of computing\n * the new local view of a document. If the input document doesn't match the\n * expected state, the document is not modified.\n *\n * @param mutation - The mutation to apply.\n * @param document - The document to mutate. The input document can be an\n * invalid document if the client has no knowledge of the pre-mutation state\n * of the document.\n * @param previousMask - The fields that have been updated before applying this mutation.\n * @param localWriteTime - A timestamp indicating the local write time of the\n * batch this mutation is a part of.\n * @returns A `FieldMask` representing the fields that are changed by applying this mutation.\n */ function Jn(t, e, n, s) {\n return t instanceof Zn ? function(t, e, n, s) {\n if (!jn(t.precondition, e)) \n // The mutation failed to apply (e.g. a document ID created with add()\n // caused a name collision).\n return n;\n const i = t.value.clone(), r = ss(t.fieldTransforms, s, e);\n return i.setAll(r), e.convertToFoundDocument(e.version, i).setHasLocalMutations(), \n null;\n // SetMutation overwrites all fields.\n }\n /**\n * A mutation that modifies fields of the document at the given key with the\n * given values. The values are applied through a field mask:\n *\n * * When a field is in both the mask and the values, the corresponding field\n * is updated.\n * * When a field is in neither the mask nor the values, the corresponding\n * field is unmodified.\n * * When a field is in the mask but not in the values, the corresponding field\n * is deleted.\n * * When a field is not in the mask but is in the values, the values map is\n * ignored.\n */ (t, e, n, s) : t instanceof ts ? function(t, e, n, s) {\n if (!jn(t.precondition, e)) return n;\n const i = ss(t.fieldTransforms, s, e), r = e.data;\n if (r.setAll(es(t)), r.setAll(i), e.convertToFoundDocument(e.version, r).setHasLocalMutations(), \n null === n) return null;\n return n.unionWith(t.fieldMask.fields).unionWith(t.fieldTransforms.map((t => t.field)));\n }\n /**\n * Returns a FieldPath/Value map with the content of the PatchMutation.\n */ (t, e, n, s) : function(t, e, n) {\n if (jn(t.precondition, e)) return e.convertToNoDocument(e.version).setHasLocalMutations(), \n null;\n return n;\n }\n /**\n * A mutation that verifies the existence of the document at the given key with\n * the provided precondition.\n *\n * The `verify` operation is only used in Transactions, and this class serves\n * primarily to facilitate serialization into protos.\n */ (t, e, n);\n}\n\n/**\n * If this mutation is not idempotent, returns the base value to persist with\n * this mutation. If a base value is returned, the mutation is always applied\n * to this base value, even if document has already been updated.\n *\n * The base value is a sparse object that consists of only the document\n * fields for which this mutation contains a non-idempotent transformation\n * (e.g. a numeric increment). The provided value guarantees consistent\n * behavior for non-idempotent transforms and allow us to return the same\n * latency-compensated value even if the backend has already applied the\n * mutation. The base value is null for idempotent mutations, as they can be\n * re-played even if the backend has already applied them.\n *\n * @returns a base value to store along with the mutation, or null for\n * idempotent mutations.\n */ function Yn(t, e) {\n let n = null;\n for (const s of t.fieldTransforms) {\n const t = e.data.field(s.field), i = Nn(s.transform, t || null);\n null != i && (null === n && (n = Ye.empty()), n.set(s.field, i));\n }\n return n || null;\n}\n\nfunction Xn(t, e) {\n return t.type === e.type && (!!t.key.isEqual(e.key) && (!!t.precondition.isEqual(e.precondition) && (!!function(t, e) {\n return void 0 === t && void 0 === e || !(!t || !e) && tt(t, e, ((t, e) => Kn(t, e)));\n }(t.fieldTransforms, e.fieldTransforms) && (0 /* MutationType.Set */ === t.type ? t.value.isEqual(e.value) : 1 /* MutationType.Patch */ !== t.type || t.data.isEqual(e.data) && t.fieldMask.isEqual(e.fieldMask)))));\n}\n\n/**\n * A mutation that creates or replaces the document at the given key with the\n * object value contents.\n */ class Zn extends Wn {\n constructor(t, e, n, s = []) {\n super(), this.key = t, this.value = e, this.precondition = n, this.fieldTransforms = s, \n this.type = 0 /* MutationType.Set */;\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass ts extends Wn {\n constructor(t, e, n, s, i = []) {\n super(), this.key = t, this.data = e, this.fieldMask = n, this.precondition = s, \n this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */;\n }\n getFieldMask() {\n return this.fieldMask;\n }\n}\n\nfunction es(t) {\n const e = new Map;\n return t.fieldMask.fields.forEach((n => {\n if (!n.isEmpty()) {\n const s = t.data.field(n);\n e.set(n, s);\n }\n })), e;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use after a mutation\n * containing transforms has been acknowledged by the server.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param mutableDocument - The current state of the document after applying all\n * previous mutations.\n * @param serverTransformResults - The transform results received by the server.\n * @returns The transform results list.\n */ function ns(t, e, n) {\n const s = new Map;\n M(t.length === n.length);\n for (let i = 0; i < n.length; i++) {\n const r = t[i], o = r.transform, u = e.data.field(r.field);\n s.set(r.field, xn(o, u, n[i]));\n }\n return s;\n}\n\n/**\n * Creates a list of \"transform results\" (a transform result is a field value\n * representing the result of applying a transform) for use when applying a\n * transform locally.\n *\n * @param fieldTransforms - The field transforms to apply the result to.\n * @param localWriteTime - The local time of the mutation (used to\n * generate ServerTimestampValues).\n * @param mutableDocument - The document to apply transforms on.\n * @returns The transform results list.\n */ function ss(t, e, n) {\n const s = new Map;\n for (const i of t) {\n const t = i.transform, r = n.data.field(i.field);\n s.set(i.field, Cn(t, r, e));\n }\n return s;\n}\n\n/** A mutation that deletes the document at the given key. */ class is extends Wn {\n constructor(t, e) {\n super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\nclass rs extends Wn {\n constructor(t, e) {\n super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , \n this.fieldTransforms = [];\n }\n getFieldMask() {\n return null;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class os {\n // TODO(b/33078163): just use simplest form of existence filter for now\n constructor(t) {\n this.count = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Error Codes describing the different ways GRPC can fail. These are copied\n * directly from GRPC's sources here:\n *\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\n *\n * Important! The names of these identifiers matter because the string forms\n * are used for reverse lookups from the webchannel stream. Do NOT change the\n * names of these identifiers or change this into a const enum.\n */ var us, cs;\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a non-write operation.\n *\n * See isPermanentWriteError for classifying write errors.\n */\nfunction as(t) {\n switch (t) {\n default:\n return O();\n\n case B.CANCELLED:\n case B.UNKNOWN:\n case B.DEADLINE_EXCEEDED:\n case B.RESOURCE_EXHAUSTED:\n case B.INTERNAL:\n case B.UNAVAILABLE:\n // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n case B.UNAUTHENTICATED:\n return !1;\n\n case B.INVALID_ARGUMENT:\n case B.NOT_FOUND:\n case B.ALREADY_EXISTS:\n case B.PERMISSION_DENIED:\n case B.FAILED_PRECONDITION:\n // Aborted might be retried in some scenarios, but that is dependant on\n // the context and should handled individually by the calling code.\n // See https://cloud.google.com/apis/design/errors.\n case B.ABORTED:\n case B.OUT_OF_RANGE:\n case B.UNIMPLEMENTED:\n case B.DATA_LOSS:\n return !0;\n }\n}\n\n/**\n * Determines whether an error code represents a permanent error when received\n * in response to a write operation.\n *\n * Write operations must be handled specially because as of b/119437764, ABORTED\n * errors on the write stream should be retried too (even though ABORTED errors\n * are not generally retryable).\n *\n * Note that during the initial handshake on the write stream an ABORTED error\n * signals that we should discard our stream token (i.e. it is permanent). This\n * means a handshake error should be classified with isPermanentError, above.\n */\n/**\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\n * are not the same as HTTP status codes.\n *\n * @returns The Code equivalent to the given GRPC status code. Fails if there\n * is no match.\n */\nfunction hs(t) {\n if (void 0 === t) \n // This shouldn't normally happen, but in certain error cases (like trying\n // to send invalid proto messages) we may get an error with no GRPC code.\n return x(\"GRPC error has no .code\"), B.UNKNOWN;\n switch (t) {\n case us.OK:\n return B.OK;\n\n case us.CANCELLED:\n return B.CANCELLED;\n\n case us.UNKNOWN:\n return B.UNKNOWN;\n\n case us.DEADLINE_EXCEEDED:\n return B.DEADLINE_EXCEEDED;\n\n case us.RESOURCE_EXHAUSTED:\n return B.RESOURCE_EXHAUSTED;\n\n case us.INTERNAL:\n return B.INTERNAL;\n\n case us.UNAVAILABLE:\n return B.UNAVAILABLE;\n\n case us.UNAUTHENTICATED:\n return B.UNAUTHENTICATED;\n\n case us.INVALID_ARGUMENT:\n return B.INVALID_ARGUMENT;\n\n case us.NOT_FOUND:\n return B.NOT_FOUND;\n\n case us.ALREADY_EXISTS:\n return B.ALREADY_EXISTS;\n\n case us.PERMISSION_DENIED:\n return B.PERMISSION_DENIED;\n\n case us.FAILED_PRECONDITION:\n return B.FAILED_PRECONDITION;\n\n case us.ABORTED:\n return B.ABORTED;\n\n case us.OUT_OF_RANGE:\n return B.OUT_OF_RANGE;\n\n case us.UNIMPLEMENTED:\n return B.UNIMPLEMENTED;\n\n case us.DATA_LOSS:\n return B.DATA_LOSS;\n\n default:\n return O();\n }\n}\n\n/**\n * Converts an HTTP response's error status to the equivalent error code.\n *\n * @param status - An HTTP error response status (\"FAILED_PRECONDITION\",\n * \"UNKNOWN\", etc.)\n * @returns The equivalent Code. Non-matching responses are mapped to\n * Code.UNKNOWN.\n */ (cs = us || (us = {}))[cs.OK = 0] = \"OK\", cs[cs.CANCELLED = 1] = \"CANCELLED\", \ncs[cs.UNKNOWN = 2] = \"UNKNOWN\", cs[cs.INVALID_ARGUMENT = 3] = \"INVALID_ARGUMENT\", \ncs[cs.DEADLINE_EXCEEDED = 4] = \"DEADLINE_EXCEEDED\", cs[cs.NOT_FOUND = 5] = \"NOT_FOUND\", \ncs[cs.ALREADY_EXISTS = 6] = \"ALREADY_EXISTS\", cs[cs.PERMISSION_DENIED = 7] = \"PERMISSION_DENIED\", \ncs[cs.UNAUTHENTICATED = 16] = \"UNAUTHENTICATED\", cs[cs.RESOURCE_EXHAUSTED = 8] = \"RESOURCE_EXHAUSTED\", \ncs[cs.FAILED_PRECONDITION = 9] = \"FAILED_PRECONDITION\", cs[cs.ABORTED = 10] = \"ABORTED\", \ncs[cs.OUT_OF_RANGE = 11] = \"OUT_OF_RANGE\", cs[cs.UNIMPLEMENTED = 12] = \"UNIMPLEMENTED\", \ncs[cs.INTERNAL = 13] = \"INTERNAL\", cs[cs.UNAVAILABLE = 14] = \"UNAVAILABLE\", cs[cs.DATA_LOSS = 15] = \"DATA_LOSS\";\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A map implementation that uses objects as keys. Objects must have an\n * associated equals function and must be immutable. Entries in the map are\n * stored together with the key being produced from the mapKeyFn. This map\n * automatically handles collisions of keys.\n */\nclass ls {\n constructor(t, e) {\n this.mapKeyFn = t, this.equalsFn = e, \n /**\n * The inner map for a key/value pair. Due to the possibility of collisions we\n * keep a list of entries that we do a linear search through to find an actual\n * match. Note that collisions should be rare, so we still expect near\n * constant time lookups in practice.\n */\n this.inner = {}, \n /** The number of entries stored in the map */\n this.innerSize = 0;\n }\n /** Get a value for this key, or undefined if it does not exist. */ get(t) {\n const e = this.mapKeyFn(t), n = this.inner[e];\n if (void 0 !== n) for (const [e, s] of n) if (this.equalsFn(e, t)) return s;\n }\n has(t) {\n return void 0 !== this.get(t);\n }\n /** Put this key and value in the map. */ set(t, e) {\n const n = this.mapKeyFn(t), s = this.inner[n];\n if (void 0 === s) return this.inner[n] = [ [ t, e ] ], void this.innerSize++;\n for (let n = 0; n < s.length; n++) if (this.equalsFn(s[n][0], t)) \n // This is updating an existing entry and does not increase `innerSize`.\n return void (s[n] = [ t, e ]);\n s.push([ t, e ]), this.innerSize++;\n }\n /**\n * Remove this key from the map. Returns a boolean if anything was deleted.\n */ delete(t) {\n const e = this.mapKeyFn(t), n = this.inner[e];\n if (void 0 === n) return !1;\n for (let s = 0; s < n.length; s++) if (this.equalsFn(n[s][0], t)) return 1 === n.length ? delete this.inner[e] : n.splice(s, 1), \n this.innerSize--, !0;\n return !1;\n }\n forEach(t) {\n Bt(this.inner, ((e, n) => {\n for (const [e, s] of n) t(e, s);\n }));\n }\n isEmpty() {\n return Lt(this.inner);\n }\n size() {\n return this.innerSize;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const fs = new Ge(ct.comparator);\n\nfunction ds() {\n return fs;\n}\n\nconst _s = new Ge(ct.comparator);\n\nfunction ws(...t) {\n let e = _s;\n for (const n of t) e = e.insert(n.key, n);\n return e;\n}\n\nfunction ms(t) {\n let e = _s;\n return t.forEach(((t, n) => e = e.insert(t, n.overlayedDocument))), e;\n}\n\nfunction gs() {\n return ps();\n}\n\nfunction ys() {\n return ps();\n}\n\nfunction ps() {\n return new ls((t => t.toString()), ((t, e) => t.isEqual(e)));\n}\n\nconst Is = new Ge(ct.comparator);\n\nconst Ts = new We(ct.comparator);\n\nfunction Es(...t) {\n let e = Ts;\n for (const n of t) e = e.add(n);\n return e;\n}\n\nconst As = new We(Z);\n\nfunction Rs() {\n return As;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An event from the RemoteStore. It is split into targetChanges (changes to the\n * state or the set of documents in our watched targets) and documentUpdates\n * (changes to the actual documents).\n */ class bs {\n constructor(\n /**\n * The snapshot version this event brings us up to, or MIN if not set.\n */\n t, \n /**\n * A map from target to changes to the target. See TargetChange.\n */\n e, \n /**\n * A set of targets that is known to be inconsistent. Listens for these\n * targets should be re-established without resume tokens.\n */\n n, \n /**\n * A set of which documents have changed or been deleted, along with the\n * doc's new values (if not deleted).\n */\n s, \n /**\n * A set of which document updates are due only to limbo resolution targets.\n */\n i) {\n this.snapshotVersion = t, this.targetChanges = e, this.targetMismatches = n, this.documentUpdates = s, \n this.resolvedLimboDocuments = i;\n }\n /**\n * HACK: Views require RemoteEvents in order to determine whether the view is\n * CURRENT, but secondary tabs don't receive remote events. So this method is\n * used to create a synthesized RemoteEvent that can be used to apply a\n * CURRENT status change to a View, for queries executed in a different tab.\n */\n // PORTING NOTE: Multi-tab only\n static createSynthesizedRemoteEventForCurrentChange(t, e, n) {\n const s = new Map;\n return s.set(t, Ps.createSynthesizedTargetChangeForCurrentChange(t, e, n)), new bs(st.min(), s, Rs(), ds(), Es());\n }\n}\n\n/**\n * A TargetChange specifies the set of changes for a specific target as part of\n * a RemoteEvent. These changes track which documents are added, modified or\n * removed, as well as the target's resume token and whether the target is\n * marked CURRENT.\n * The actual changes *to* documents are not part of the TargetChange since\n * documents may be part of multiple targets.\n */ class Ps {\n constructor(\n /**\n * An opaque, server-assigned token that allows watching a query to be resumed\n * after disconnecting without retransmitting all the data that matches the\n * query. The resume token essentially identifies a point in time from which\n * the server should resume sending results.\n */\n t, \n /**\n * The \"current\" (synced) status of this target. Note that \"current\"\n * has special meaning in the RPC protocol that implies that a target is\n * both up-to-date and consistent with the rest of the watch stream.\n */\n e, \n /**\n * The set of documents that were newly assigned to this target as part of\n * this remote event.\n */\n n, \n /**\n * The set of documents that were already assigned to this target but received\n * an update during this remote event.\n */\n s, \n /**\n * The set of documents that were removed from this target as part of this\n * remote event.\n */\n i) {\n this.resumeToken = t, this.current = e, this.addedDocuments = n, this.modifiedDocuments = s, \n this.removedDocuments = i;\n }\n /**\n * This method is used to create a synthesized TargetChanges that can be used to\n * apply a CURRENT status change to a View (for queries executed in a different\n * tab) or for new queries (to raise snapshots with correct CURRENT status).\n */ static createSynthesizedTargetChangeForCurrentChange(t, e, n) {\n return new Ps(n, e, Es(), Es(), Es());\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a changed document and a list of target ids to which this change\n * applies.\n *\n * If document has been deleted NoDocument will be provided.\n */ class vs {\n constructor(\n /** The new document applies to all of these targets. */\n t, \n /** The new document is removed from all of these targets. */\n e, \n /** The key of the document for this change. */\n n, \n /**\n * The new document or NoDocument if it was deleted. Is null if the\n * document went out of view without the server sending a new document.\n */\n s) {\n this.It = t, this.removedTargetIds = e, this.key = n, this.Tt = s;\n }\n}\n\nclass Vs {\n constructor(t, e) {\n this.targetId = t, this.Et = e;\n }\n}\n\nclass Ss {\n constructor(\n /** What kind of change occurred to the watch target. */\n t, \n /** The target IDs that were added/removed/set. */\n e, \n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */\n n = Qt.EMPTY_BYTE_STRING\n /** An RPC error indicating why the watch failed. */ , s = null) {\n this.state = t, this.targetIds = e, this.resumeToken = n, this.cause = s;\n }\n}\n\n/** Tracks the internal state of a Watch target. */ class Ds {\n constructor() {\n /**\n * The number of pending responses (adds or removes) that we are waiting on.\n * We only consider targets active that have no pending responses.\n */\n this.At = 0, \n /**\n * Keeps track of the document changes since the last raised snapshot.\n *\n * These changes are continuously updated as we receive document updates and\n * always reflect the current set of changes against the last issued snapshot.\n */\n this.Rt = Ns(), \n /** See public getters for explanations of these fields. */\n this.bt = Qt.EMPTY_BYTE_STRING, this.Pt = !1, \n /**\n * Whether this target state should be included in the next snapshot. We\n * initialize to true so that newly-added targets are included in the next\n * RemoteEvent.\n */\n this.vt = !0;\n }\n /**\n * Whether this target has been marked 'current'.\n *\n * 'Current' has special meaning in the RPC protocol: It implies that the\n * Watch backend has sent us all changes up to the point at which the target\n * was added and that the target is consistent with the rest of the watch\n * stream.\n */ get current() {\n return this.Pt;\n }\n /** The last resume token sent to us for this target. */ get resumeToken() {\n return this.bt;\n }\n /** Whether this target has pending target adds or target removes. */ get Vt() {\n return 0 !== this.At;\n }\n /** Whether we have modified any state that should trigger a snapshot. */ get St() {\n return this.vt;\n }\n /**\n * Applies the resume token to the TargetChange, but only when it has a new\n * value. Empty resumeTokens are discarded.\n */ Dt(t) {\n t.approximateByteSize() > 0 && (this.vt = !0, this.bt = t);\n }\n /**\n * Creates a target change from the current set of changes.\n *\n * To reset the document changes after raising this snapshot, call\n * `clearPendingChanges()`.\n */ Ct() {\n let t = Es(), e = Es(), n = Es();\n return this.Rt.forEach(((s, i) => {\n switch (i) {\n case 0 /* ChangeType.Added */ :\n t = t.add(s);\n break;\n\n case 2 /* ChangeType.Modified */ :\n e = e.add(s);\n break;\n\n case 1 /* ChangeType.Removed */ :\n n = n.add(s);\n break;\n\n default:\n O();\n }\n })), new Ps(this.bt, this.Pt, t, e, n);\n }\n /**\n * Resets the document changes and sets `hasPendingChanges` to false.\n */ xt() {\n this.vt = !1, this.Rt = Ns();\n }\n Nt(t, e) {\n this.vt = !0, this.Rt = this.Rt.insert(t, e);\n }\n kt(t) {\n this.vt = !0, this.Rt = this.Rt.remove(t);\n }\n Ot() {\n this.At += 1;\n }\n Mt() {\n this.At -= 1;\n }\n Ft() {\n this.vt = !0, this.Pt = !0;\n }\n}\n\n/**\n * A helper class to accumulate watch changes into a RemoteEvent.\n */\nclass Cs {\n constructor(t) {\n this.$t = t, \n /** The internal state of all tracked targets. */\n this.Bt = new Map, \n /** Keeps track of the documents to update since the last raised snapshot. */\n this.Lt = ds(), \n /** A mapping of document keys to their set of target IDs. */\n this.qt = xs(), \n /**\n * A list of targets with existence filter mismatches. These targets are\n * known to be inconsistent and their listens needs to be re-established by\n * RemoteStore.\n */\n this.Ut = new We(Z);\n }\n /**\n * Processes and adds the DocumentWatchChange to the current set of changes.\n */ Kt(t) {\n for (const e of t.It) t.Tt && t.Tt.isFoundDocument() ? this.Gt(e, t.Tt) : this.Qt(e, t.key, t.Tt);\n for (const e of t.removedTargetIds) this.Qt(e, t.key, t.Tt);\n }\n /** Processes and adds the WatchTargetChange to the current set of changes. */ jt(t) {\n this.forEachTarget(t, (e => {\n const n = this.Wt(e);\n switch (t.state) {\n case 0 /* WatchTargetChangeState.NoChange */ :\n this.zt(e) && n.Dt(t.resumeToken);\n break;\n\n case 1 /* WatchTargetChangeState.Added */ :\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Mt(), n.Vt || \n // We have a freshly added target, so we need to reset any state\n // that we had previously. This can happen e.g. when remove and add\n // back a target for existence filter mismatches.\n n.xt(), n.Dt(t.resumeToken);\n break;\n\n case 2 /* WatchTargetChangeState.Removed */ :\n // We need to keep track of removed targets to we can post-filter and\n // remove any target changes.\n // We need to decrement the number of pending acks needed from watch\n // for this targetId.\n n.Mt(), n.Vt || this.removeTarget(e);\n break;\n\n case 3 /* WatchTargetChangeState.Current */ :\n this.zt(e) && (n.Ft(), n.Dt(t.resumeToken));\n break;\n\n case 4 /* WatchTargetChangeState.Reset */ :\n this.zt(e) && (\n // Reset the target and synthesizes removes for all existing\n // documents. The backend will re-add any documents that still\n // match the target before it sends the next global snapshot.\n this.Ht(e), n.Dt(t.resumeToken));\n break;\n\n default:\n O();\n }\n }));\n }\n /**\n * Iterates over all targetIds that the watch change applies to: either the\n * targetIds explicitly listed in the change or the targetIds of all currently\n * active targets.\n */ forEachTarget(t, e) {\n t.targetIds.length > 0 ? t.targetIds.forEach(e) : this.Bt.forEach(((t, n) => {\n this.zt(n) && e(n);\n }));\n }\n /**\n * Handles existence filters and synthesizes deletes for filter mismatches.\n * Targets that are invalidated by filter mismatches are added to\n * `pendingTargetResets`.\n */ Jt(t) {\n const e = t.targetId, n = t.Et.count, s = this.Yt(e);\n if (s) {\n const t = s.target;\n if (rn(t)) if (0 === n) {\n // The existence filter told us the document does not exist. We deduce\n // that this document does not exist and apply a deleted document to\n // our updates. Without applying this deleted document there might be\n // another query that will raise this document as part of a snapshot\n // until it is resolved, essentially exposing inconsistency between\n // queries.\n const n = new ct(t.path);\n this.Qt(e, n, Ze.newNoDocument(n, st.min()));\n } else M(1 === n); else {\n this.Xt(e) !== n && (\n // Existence filter mismatch: We reset the mapping and raise a new\n // snapshot with `isFromCache:true`.\n this.Ht(e), this.Ut = this.Ut.add(e));\n }\n }\n }\n /**\n * Converts the currently accumulated state into a remote event at the\n * provided snapshot version. Resets the accumulated changes before returning.\n */ Zt(t) {\n const e = new Map;\n this.Bt.forEach(((n, s) => {\n const i = this.Yt(s);\n if (i) {\n if (n.current && rn(i.target)) {\n // Document queries for document that don't exist can produce an empty\n // result set. To update our local cache, we synthesize a document\n // delete if we have not previously received the document. This\n // resolves the limbo state of the document, removing it from\n // limboDocumentRefs.\n // TODO(dimond): Ideally we would have an explicit lookup target\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n const e = new ct(i.target.path);\n null !== this.Lt.get(e) || this.te(s, e) || this.Qt(s, e, Ze.newNoDocument(e, t));\n }\n n.St && (e.set(s, n.Ct()), n.xt());\n }\n }));\n let n = Es();\n // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the target cache.\n \n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n this.qt.forEach(((t, e) => {\n let s = !0;\n e.forEachWhile((t => {\n const e = this.Yt(t);\n return !e || 2 /* TargetPurpose.LimboResolution */ === e.purpose || (s = !1, !1);\n })), s && (n = n.add(t));\n })), this.Lt.forEach(((e, n) => n.setReadTime(t)));\n const s = new bs(t, e, this.Ut, this.Lt, n);\n return this.Lt = ds(), this.qt = xs(), this.Ut = new We(Z), s;\n }\n /**\n * Adds the provided document to the internal list of document updates and\n * its document key to the given target's mapping.\n */\n // Visible for testing.\n Gt(t, e) {\n if (!this.zt(t)) return;\n const n = this.te(t, e.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */;\n this.Wt(t).Nt(e.key, n), this.Lt = this.Lt.insert(e.key, e), this.qt = this.qt.insert(e.key, this.ee(e.key).add(t));\n }\n /**\n * Removes the provided document from the target mapping. If the\n * document no longer matches the target, but the document's state is still\n * known (e.g. we know that the document was deleted or we received the change\n * that caused the filter mismatch), the new document can be provided\n * to update the remote document cache.\n */\n // Visible for testing.\n Qt(t, e, n) {\n if (!this.zt(t)) return;\n const s = this.Wt(t);\n this.te(t, e) ? s.Nt(e, 1 /* ChangeType.Removed */) : \n // The document may have entered and left the target before we raised a\n // snapshot, so we can just ignore the change.\n s.kt(e), this.qt = this.qt.insert(e, this.ee(e).delete(t)), n && (this.Lt = this.Lt.insert(e, n));\n }\n removeTarget(t) {\n this.Bt.delete(t);\n }\n /**\n * Returns the current count of documents in the target. This includes both\n * the number of documents that the LocalStore considers to be part of the\n * target as well as any accumulated changes.\n */ Xt(t) {\n const e = this.Wt(t).Ct();\n return this.$t.getRemoteKeysForTarget(t).size + e.addedDocuments.size - e.removedDocuments.size;\n }\n /**\n * Increment the number of acks needed from watch before we can consider the\n * server to be 'in-sync' with the client's active targets.\n */ Ot(t) {\n this.Wt(t).Ot();\n }\n Wt(t) {\n let e = this.Bt.get(t);\n return e || (e = new Ds, this.Bt.set(t, e)), e;\n }\n ee(t) {\n let e = this.qt.get(t);\n return e || (e = new We(Z), this.qt = this.qt.insert(t, e)), e;\n }\n /**\n * Verifies that the user is still interested in this target (by calling\n * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs\n * from watch.\n */ zt(t) {\n const e = null !== this.Yt(t);\n return e || C(\"WatchChangeAggregator\", \"Detected inactive target\", t), e;\n }\n /**\n * Returns the TargetData for an active target (i.e. a target that the user\n * is still interested in that has no outstanding target change requests).\n */ Yt(t) {\n const e = this.Bt.get(t);\n return e && e.Vt ? null : this.$t.ne(t);\n }\n /**\n * Resets the state of a Watch target to its initial state (e.g. sets\n * 'current' to false, clears the resume token and removes its target mapping\n * from all documents).\n */ Ht(t) {\n this.Bt.set(t, new Ds);\n this.$t.getRemoteKeysForTarget(t).forEach((e => {\n this.Qt(t, e, /*updatedDocument=*/ null);\n }));\n }\n /**\n * Returns whether the LocalStore considers the document to be part of the\n * specified target.\n */ te(t, e) {\n return this.$t.getRemoteKeysForTarget(t).has(e);\n }\n}\n\nfunction xs() {\n return new Ge(ct.comparator);\n}\n\nfunction Ns() {\n return new Ge(ct.comparator);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const ks = (() => {\n const t = {\n asc: \"ASCENDING\",\n desc: \"DESCENDING\"\n };\n return t;\n})(), Os = (() => {\n const t = {\n \"<\": \"LESS_THAN\",\n \"<=\": \"LESS_THAN_OR_EQUAL\",\n \">\": \"GREATER_THAN\",\n \">=\": \"GREATER_THAN_OR_EQUAL\",\n \"==\": \"EQUAL\",\n \"!=\": \"NOT_EQUAL\",\n \"array-contains\": \"ARRAY_CONTAINS\",\n in: \"IN\",\n \"not-in\": \"NOT_IN\",\n \"array-contains-any\": \"ARRAY_CONTAINS_ANY\"\n };\n return t;\n})(), Ms = (() => {\n const t = {\n and: \"AND\",\n or: \"OR\"\n };\n return t;\n})();\n\n/**\n * This class generates JsonObject values for the Datastore API suitable for\n * sending to either GRPC stub methods or via the JSON/HTTP REST API.\n *\n * The serializer supports both Protobuf.js and Proto3 JSON formats. By\n * setting `useProto3Json` to true, the serializer will use the Proto3 JSON\n * format.\n *\n * For a description of the Proto3 JSON format check\n * https://developers.google.com/protocol-buffers/docs/proto3#json\n *\n * TODO(klimt): We can remove the databaseId argument if we keep the full\n * resource name in documents.\n */\nclass Fs {\n constructor(t, e) {\n this.databaseId = t, this.wt = e;\n }\n}\n\n/**\n * Returns a value for a Date that's appropriate to put into a proto.\n */\nfunction $s(t, e) {\n if (t.wt) {\n return `${new Date(1e3 * e.seconds).toISOString().replace(/\\.\\d*/, \"\").replace(\"Z\", \"\")}.${(\"000000000\" + e.nanoseconds).slice(-9)}Z`;\n }\n return {\n seconds: \"\" + e.seconds,\n nanos: e.nanoseconds\n };\n}\n\n/**\n * Returns a value for bytes that's appropriate to put in a proto.\n *\n * Visible for testing.\n */\nfunction Bs(t, e) {\n return t.wt ? e.toBase64() : e.toUint8Array();\n}\n\n/**\n * Returns a ByteString based on the proto string value.\n */ function Ls(t, e) {\n return $s(t, e.toTimestamp());\n}\n\nfunction qs(t) {\n return M(!!t), st.fromTimestamp(function(t) {\n const e = Wt(t);\n return new nt(e.seconds, e.nanos);\n }(t));\n}\n\nfunction Us(t, e) {\n return function(t) {\n return new rt([ \"projects\", t.projectId, \"databases\", t.database ]);\n }(t).child(\"documents\").child(e).canonicalString();\n}\n\nfunction Ks(t) {\n const e = rt.fromString(t);\n return M(wi(e)), e;\n}\n\nfunction Gs(t, e) {\n return Us(t.databaseId, e.path);\n}\n\nfunction Qs(t, e) {\n const n = Ks(e);\n if (n.get(1) !== t.databaseId.projectId) throw new L(B.INVALID_ARGUMENT, \"Tried to deserialize key from different project: \" + n.get(1) + \" vs \" + t.databaseId.projectId);\n if (n.get(3) !== t.databaseId.database) throw new L(B.INVALID_ARGUMENT, \"Tried to deserialize key from different database: \" + n.get(3) + \" vs \" + t.databaseId.database);\n return new ct(Hs(n));\n}\n\nfunction js(t, e) {\n return Us(t.databaseId, e);\n}\n\nfunction Ws(t) {\n const e = Ks(t);\n // In v1beta1 queries for collections at the root did not have a trailing\n // \"/documents\". In v1 all resource paths contain \"/documents\". Preserve the\n // ability to read the v1beta1 form for compatibility with queries persisted\n // in the local target cache.\n return 4 === e.length ? rt.emptyPath() : Hs(e);\n}\n\nfunction zs(t) {\n return new rt([ \"projects\", t.databaseId.projectId, \"databases\", t.databaseId.database ]).canonicalString();\n}\n\nfunction Hs(t) {\n return M(t.length > 4 && \"documents\" === t.get(4)), t.popFirst(5);\n}\n\n/** Creates a Document proto from key and fields (but no create/update time) */ function Js(t, e, n) {\n return {\n name: Gs(t, e),\n fields: n.value.mapValue.fields\n };\n}\n\nfunction Ys(t, e, n) {\n const s = Qs(t, e.name), i = qs(e.updateTime), r = e.createTime ? qs(e.createTime) : st.min(), o = new Ye({\n mapValue: {\n fields: e.fields\n }\n }), u = Ze.newFoundDocument(s, i, r, o);\n return n && u.setHasCommittedMutations(), n ? u.setHasCommittedMutations() : u;\n}\n\nfunction Xs(t, e) {\n return \"found\" in e ? function(t, e) {\n M(!!e.found), e.found.name, e.found.updateTime;\n const n = Qs(t, e.found.name), s = qs(e.found.updateTime), i = e.found.createTime ? qs(e.found.createTime) : st.min(), r = new Ye({\n mapValue: {\n fields: e.found.fields\n }\n });\n return Ze.newFoundDocument(n, s, i, r);\n }(t, e) : \"missing\" in e ? function(t, e) {\n M(!!e.missing), M(!!e.readTime);\n const n = Qs(t, e.missing), s = qs(e.readTime);\n return Ze.newNoDocument(n, s);\n }(t, e) : O();\n}\n\nfunction Zs(t, e) {\n let n;\n if (\"targetChange\" in e) {\n e.targetChange;\n // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n const s = function(t) {\n return \"NO_CHANGE\" === t ? 0 /* WatchTargetChangeState.NoChange */ : \"ADD\" === t ? 1 /* WatchTargetChangeState.Added */ : \"REMOVE\" === t ? 2 /* WatchTargetChangeState.Removed */ : \"CURRENT\" === t ? 3 /* WatchTargetChangeState.Current */ : \"RESET\" === t ? 4 /* WatchTargetChangeState.Reset */ : O();\n }(e.targetChange.targetChangeType || \"NO_CHANGE\"), i = e.targetChange.targetIds || [], r = function(t, e) {\n return t.wt ? (M(void 0 === e || \"string\" == typeof e), Qt.fromBase64String(e || \"\")) : (M(void 0 === e || e instanceof Uint8Array), \n Qt.fromUint8Array(e || new Uint8Array));\n }(t, e.targetChange.resumeToken), o = e.targetChange.cause, u = o && function(t) {\n const e = void 0 === t.code ? B.UNKNOWN : hs(t.code);\n return new L(e, t.message || \"\");\n }\n /**\n * Returns a value for a number (or null) that's appropriate to put into\n * a google.protobuf.Int32Value proto.\n * DO NOT USE THIS FOR ANYTHING ELSE.\n * This method cheats. It's typed as returning \"number\" because that's what\n * our generated proto interfaces say Int32Value must be. But GRPC actually\n * expects a { value: <number> } struct.\n */ (o);\n n = new Ss(s, i, r, u || null);\n } else if (\"documentChange\" in e) {\n e.documentChange;\n const s = e.documentChange;\n s.document, s.document.name, s.document.updateTime;\n const i = Qs(t, s.document.name), r = qs(s.document.updateTime), o = s.document.createTime ? qs(s.document.createTime) : st.min(), u = new Ye({\n mapValue: {\n fields: s.document.fields\n }\n }), c = Ze.newFoundDocument(i, r, o, u), a = s.targetIds || [], h = s.removedTargetIds || [];\n n = new vs(a, h, c.key, c);\n } else if (\"documentDelete\" in e) {\n e.documentDelete;\n const s = e.documentDelete;\n s.document;\n const i = Qs(t, s.document), r = s.readTime ? qs(s.readTime) : st.min(), o = Ze.newNoDocument(i, r), u = s.removedTargetIds || [];\n n = new vs([], u, o.key, o);\n } else if (\"documentRemove\" in e) {\n e.documentRemove;\n const s = e.documentRemove;\n s.document;\n const i = Qs(t, s.document), r = s.removedTargetIds || [];\n n = new vs([], r, i, null);\n } else {\n if (!(\"filter\" in e)) return O();\n {\n e.filter;\n const t = e.filter;\n t.targetId;\n const s = t.count || 0, i = new os(s), r = t.targetId;\n n = new Vs(r, i);\n }\n }\n return n;\n}\n\nfunction ti(t, e) {\n let n;\n if (e instanceof Zn) n = {\n update: Js(t, e.key, e.value)\n }; else if (e instanceof is) n = {\n delete: Gs(t, e.key)\n }; else if (e instanceof ts) n = {\n update: Js(t, e.key, e.data),\n updateMask: _i(e.fieldMask)\n }; else {\n if (!(e instanceof rs)) return O();\n n = {\n verify: Gs(t, e.key)\n };\n }\n return e.fieldTransforms.length > 0 && (n.updateTransforms = e.fieldTransforms.map((t => function(t, e) {\n const n = e.transform;\n if (n instanceof kn) return {\n fieldPath: e.field.canonicalString(),\n setToServerValue: \"REQUEST_TIME\"\n };\n if (n instanceof On) return {\n fieldPath: e.field.canonicalString(),\n appendMissingElements: {\n values: n.elements\n }\n };\n if (n instanceof Fn) return {\n fieldPath: e.field.canonicalString(),\n removeAllFromArray: {\n values: n.elements\n }\n };\n if (n instanceof Bn) return {\n fieldPath: e.field.canonicalString(),\n increment: n.gt\n };\n throw O();\n }(0, t)))), e.precondition.isNone || (n.currentDocument = function(t, e) {\n return void 0 !== e.updateTime ? {\n updateTime: Ls(t, e.updateTime)\n } : void 0 !== e.exists ? {\n exists: e.exists\n } : O();\n }(t, e.precondition)), n;\n}\n\nfunction ei(t, e) {\n const n = e.currentDocument ? function(t) {\n return void 0 !== t.updateTime ? Qn.updateTime(qs(t.updateTime)) : void 0 !== t.exists ? Qn.exists(t.exists) : Qn.none();\n }(e.currentDocument) : Qn.none(), s = e.updateTransforms ? e.updateTransforms.map((e => function(t, e) {\n let n = null;\n if (\"setToServerValue\" in e) M(\"REQUEST_TIME\" === e.setToServerValue), n = new kn; else if (\"appendMissingElements\" in e) {\n const t = e.appendMissingElements.values || [];\n n = new On(t);\n } else if (\"removeAllFromArray\" in e) {\n const t = e.removeAllFromArray.values || [];\n n = new Fn(t);\n } else \"increment\" in e ? n = new Bn(t, e.increment) : O();\n const s = ut.fromServerFormat(e.fieldPath);\n return new Un(s, n);\n }(t, e))) : [];\n if (e.update) {\n e.update.name;\n const i = Qs(t, e.update.name), r = new Ye({\n mapValue: {\n fields: e.update.fields\n }\n });\n if (e.updateMask) {\n const t = function(t) {\n const e = t.fieldPaths || [];\n return new Je(e.map((t => ut.fromServerFormat(t))));\n }(e.updateMask);\n return new ts(i, r, t, n, s);\n }\n return new Zn(i, r, n, s);\n }\n if (e.delete) {\n const s = Qs(t, e.delete);\n return new is(s, n);\n }\n if (e.verify) {\n const s = Qs(t, e.verify);\n return new rs(s, n);\n }\n return O();\n}\n\nfunction ni(t, e) {\n return t && t.length > 0 ? (M(void 0 !== e), t.map((t => function(t, e) {\n // NOTE: Deletes don't have an updateTime.\n let n = t.updateTime ? qs(t.updateTime) : qs(e);\n return n.isEqual(st.min()) && (\n // The Firestore Emulator currently returns an update time of 0 for\n // deletes of non-existing documents (rather than null). This breaks the\n // test \"get deleted doc while offline with source=cache\" as NoDocuments\n // with version 0 are filtered by IndexedDb's RemoteDocumentCache.\n // TODO(#2149): Remove this when Emulator is fixed\n n = qs(e)), new Gn(n, t.transformResults || []);\n }(t, e)))) : [];\n}\n\nfunction si(t, e) {\n return {\n documents: [ js(t, e.path) ]\n };\n}\n\nfunction ii(t, e) {\n // Dissect the path into parent, collectionId, and optional key filter.\n const n = {\n structuredQuery: {}\n }, s = e.path;\n null !== e.collectionGroup ? (n.parent = js(t, s), n.structuredQuery.from = [ {\n collectionId: e.collectionGroup,\n allDescendants: !0\n } ]) : (n.parent = js(t, s.popLast()), n.structuredQuery.from = [ {\n collectionId: s.lastSegment()\n } ]);\n const i = function(t) {\n if (0 === t.length) return;\n return di(be.create(t, \"and\" /* CompositeOperator.AND */));\n }(e.filters);\n i && (n.structuredQuery.where = i);\n const r = function(t) {\n if (0 === t.length) return;\n return t.map((t => \n // visible for testing\n function(t) {\n return {\n field: li(t.field),\n direction: ci(t.dir)\n };\n }(t)));\n }(e.orderBy);\n r && (n.structuredQuery.orderBy = r);\n const o = function(t, e) {\n return t.wt || qt(e) ? e : {\n value: e\n };\n }\n /**\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\n */ (t, e.limit);\n var u;\n return null !== o && (n.structuredQuery.limit = o), e.startAt && (n.structuredQuery.startAt = {\n before: (u = e.startAt).inclusive,\n values: u.position\n }), e.endAt && (n.structuredQuery.endAt = function(t) {\n return {\n before: !t.inclusive,\n values: t.position\n };\n }(e.endAt)), n;\n}\n\nfunction ri(t) {\n let e = Ws(t.parent);\n const n = t.structuredQuery, s = n.from ? n.from.length : 0;\n let i = null;\n if (s > 0) {\n M(1 === s);\n const t = n.from[0];\n t.allDescendants ? i = t.collectionId : e = e.child(t.collectionId);\n }\n let r = [];\n n.where && (r = function(t) {\n const e = ui(t);\n if (e instanceof be && Ve(e)) return e.getFilters();\n return [ e ];\n }(n.where));\n let o = [];\n n.orderBy && (o = n.orderBy.map((t => function(t) {\n return new Ue(fi(t.field), \n // visible for testing\n function(t) {\n switch (t) {\n case \"ASCENDING\":\n return \"asc\" /* Direction.ASCENDING */;\n\n case \"DESCENDING\":\n return \"desc\" /* Direction.DESCENDING */;\n\n default:\n return;\n }\n }\n // visible for testing\n (t.direction));\n }\n // visible for testing\n (t))));\n let u = null;\n n.limit && (u = function(t) {\n let e;\n return e = \"object\" == typeof t ? t.value : t, qt(e) ? null : e;\n }(n.limit));\n let c = null;\n n.startAt && (c = function(t) {\n const e = !!t.before, n = t.values || [];\n return new Ie(n, e);\n }(n.startAt));\n let a = null;\n return n.endAt && (a = function(t) {\n const e = !t.before, n = t.values || [];\n return new Ie(n, e);\n }\n // visible for testing\n (n.endAt)), hn(e, i, o, r, u, \"F\" /* LimitType.First */ , c, a);\n}\n\nfunction oi(t, e) {\n const n = function(t, e) {\n switch (e) {\n case 0 /* TargetPurpose.Listen */ :\n return null;\n\n case 1 /* TargetPurpose.ExistenceFilterMismatch */ :\n return \"existence-filter-mismatch\";\n\n case 2 /* TargetPurpose.LimboResolution */ :\n return \"limbo-document\";\n\n default:\n return O();\n }\n }(0, e.purpose);\n return null == n ? null : {\n \"goog-listen-tags\": n\n };\n}\n\nfunction ui(t) {\n return void 0 !== t.unaryFilter ? function(t) {\n switch (t.unaryFilter.op) {\n case \"IS_NAN\":\n const e = fi(t.unaryFilter.field);\n return Re.create(e, \"==\" /* Operator.EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NULL\":\n const n = fi(t.unaryFilter.field);\n return Re.create(n, \"==\" /* Operator.EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n case \"IS_NOT_NAN\":\n const s = fi(t.unaryFilter.field);\n return Re.create(s, \"!=\" /* Operator.NOT_EQUAL */ , {\n doubleValue: NaN\n });\n\n case \"IS_NOT_NULL\":\n const i = fi(t.unaryFilter.field);\n return Re.create(i, \"!=\" /* Operator.NOT_EQUAL */ , {\n nullValue: \"NULL_VALUE\"\n });\n\n default:\n return O();\n }\n }(t) : void 0 !== t.fieldFilter ? function(t) {\n return Re.create(fi(t.fieldFilter.field), function(t) {\n switch (t) {\n case \"EQUAL\":\n return \"==\" /* Operator.EQUAL */;\n\n case \"NOT_EQUAL\":\n return \"!=\" /* Operator.NOT_EQUAL */;\n\n case \"GREATER_THAN\":\n return \">\" /* Operator.GREATER_THAN */;\n\n case \"GREATER_THAN_OR_EQUAL\":\n return \">=\" /* Operator.GREATER_THAN_OR_EQUAL */;\n\n case \"LESS_THAN\":\n return \"<\" /* Operator.LESS_THAN */;\n\n case \"LESS_THAN_OR_EQUAL\":\n return \"<=\" /* Operator.LESS_THAN_OR_EQUAL */;\n\n case \"ARRAY_CONTAINS\":\n return \"array-contains\" /* Operator.ARRAY_CONTAINS */;\n\n case \"IN\":\n return \"in\" /* Operator.IN */;\n\n case \"NOT_IN\":\n return \"not-in\" /* Operator.NOT_IN */;\n\n case \"ARRAY_CONTAINS_ANY\":\n return \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */;\n\n default:\n return O();\n }\n }(t.fieldFilter.op), t.fieldFilter.value);\n }(t) : void 0 !== t.compositeFilter ? function(t) {\n return be.create(t.compositeFilter.filters.map((t => ui(t))), function(t) {\n switch (t) {\n case \"AND\":\n return \"and\" /* CompositeOperator.AND */;\n\n case \"OR\":\n return \"or\" /* CompositeOperator.OR */;\n\n default:\n return O();\n }\n }(t.compositeFilter.op));\n }(t) : O();\n}\n\nfunction ci(t) {\n return ks[t];\n}\n\nfunction ai(t) {\n return Os[t];\n}\n\nfunction hi(t) {\n return Ms[t];\n}\n\nfunction li(t) {\n return {\n fieldPath: t.canonicalString()\n };\n}\n\nfunction fi(t) {\n return ut.fromServerFormat(t.fieldPath);\n}\n\nfunction di(t) {\n return t instanceof Re ? function(t) {\n if (\"==\" /* Operator.EQUAL */ === t.op) {\n if (fe(t.value)) return {\n unaryFilter: {\n field: li(t.field),\n op: \"IS_NAN\"\n }\n };\n if (le(t.value)) return {\n unaryFilter: {\n field: li(t.field),\n op: \"IS_NULL\"\n }\n };\n } else if (\"!=\" /* Operator.NOT_EQUAL */ === t.op) {\n if (fe(t.value)) return {\n unaryFilter: {\n field: li(t.field),\n op: \"IS_NOT_NAN\"\n }\n };\n if (le(t.value)) return {\n unaryFilter: {\n field: li(t.field),\n op: \"IS_NOT_NULL\"\n }\n };\n }\n return {\n fieldFilter: {\n field: li(t.field),\n op: ai(t.op),\n value: t.value\n }\n };\n }(t) : t instanceof be ? function(t) {\n const e = t.getFilters().map((t => di(t)));\n if (1 === e.length) return e[0];\n return {\n compositeFilter: {\n op: hi(t.op),\n filters: e\n }\n };\n }(t) : O();\n}\n\nfunction _i(t) {\n const e = [];\n return t.fields.forEach((t => e.push(t.canonicalString()))), {\n fieldPaths: e\n };\n}\n\nfunction wi(t) {\n // Resource names have at least 4 components (project ID, database ID)\n return t.length >= 4 && \"projects\" === t.get(0) && \"databases\" === t.get(2);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nfunction mi(t) {\n let e = \"\";\n for (let n = 0; n < t.length; n++) e.length > 0 && (e = yi(e)), e = gi(t.get(n), e);\n return yi(e);\n}\n\n/** Encodes a single segment of a resource path into the given result */ function gi(t, e) {\n let n = e;\n const s = t.length;\n for (let e = 0; e < s; e++) {\n const s = t.charAt(e);\n switch (s) {\n case \"\\0\":\n n += \"\u0001\u0010\";\n break;\n\n case \"\u0001\":\n n += \"\u0001\u0011\";\n break;\n\n default:\n n += s;\n }\n }\n return n;\n}\n\n/** Encodes a path separator into the given result */ function yi(t) {\n return t + \"\u0001\u0001\";\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */ function pi(t) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const e = t.length;\n if (M(e >= 2), 2 === e) return M(\"\u0001\" === t.charAt(0) && \"\u0001\" === t.charAt(1)), rt.emptyPath();\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const n = e - 2, s = [];\n let i = \"\";\n for (let r = 0; r < e; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const e = t.indexOf(\"\u0001\", r);\n (e < 0 || e > n) && O();\n switch (t.charAt(e + 1)) {\n case \"\u0001\":\n const n = t.substring(r, e);\n let o;\n 0 === i.length ? \n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n o = n : (i += n, o = i, i = \"\"), s.push(o);\n break;\n\n case \"\u0010\":\n i += t.substring(r, e), i += \"\\0\";\n break;\n\n case \"\u0011\":\n // The escape character can be used in the output to encode itself.\n i += t.substring(r, e + 1);\n break;\n\n default:\n O();\n }\n r = e + 2;\n }\n return new rt(s);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ii = [ \"userId\", \"batchId\" ];\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Name of the IndexedDb object store.\n *\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\n * older clients that only supported single locked access to the persistence\n * layer.\n */\n/**\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\n * index to iterate over all at document mutations for a given path or lower.\n */\nfunction Ti(t, e) {\n return [ t, mi(e) ];\n}\n\n/**\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\n * and deleting into the DbDocumentMutations index.\n */ function Ei(t, e, n) {\n return [ t, mi(e), n ];\n}\n\n/**\n * Because we store all the useful information for this store in the key,\n * there is no useful information to store as the value. The raw (unencoded)\n * path cannot be stored because IndexedDb doesn't store prototype\n * information.\n */ const Ai = {}, Ri = [ \"prefixPath\", \"collectionGroup\", \"readTime\", \"documentId\" ], bi = [ \"prefixPath\", \"collectionGroup\", \"documentId\" ], Pi = [ \"collectionGroup\", \"readTime\", \"prefixPath\", \"documentId\" ], vi = [ \"canonicalId\", \"targetId\" ], Vi = [ \"targetId\", \"path\" ], Si = [ \"path\", \"targetId\" ], Di = [ \"collectionId\", \"parent\" ], Ci = [ \"indexId\", \"uid\" ], xi = [ \"uid\", \"sequenceNumber\" ], Ni = [ \"indexId\", \"uid\", \"arrayValue\", \"directionalValue\", \"orderedDocumentKey\", \"documentKey\" ], ki = [ \"indexId\", \"uid\", \"orderedDocumentKey\" ], Oi = [ \"userId\", \"collectionPath\", \"documentId\" ], Mi = [ \"userId\", \"collectionPath\", \"largestBatchId\" ], Fi = [ \"userId\", \"collectionGroup\", \"largestBatchId\" ], $i = [ ...[ ...[ ...[ ...[ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocuments\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\" ], \"clientMetadata\" ], \"remoteDocumentGlobal\" ], \"collectionParents\" ], \"bundles\", \"namedQueries\" ], Bi = [ ...$i, \"documentOverlays\" ], Li = [ \"mutationQueues\", \"mutations\", \"documentMutations\", \"remoteDocumentsV14\", \"targets\", \"owner\", \"targetGlobal\", \"targetDocuments\", \"clientMetadata\", \"remoteDocumentGlobal\", \"collectionParents\", \"bundles\", \"namedQueries\", \"documentOverlays\" ], qi = Li, Ui = [ ...qi, \"indexConfiguration\", \"indexState\", \"indexEntries\" ];\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass Ki extends Tt {\n constructor(t, e) {\n super(), this.se = t, this.currentSequenceNumber = e;\n }\n}\n\nfunction Gi(t, e) {\n const n = $(t);\n return bt.M(n.se, e);\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A batch of mutations that will be sent as one unit to the backend.\n */ class Qi {\n /**\n * @param batchId - The unique ID of this mutation batch.\n * @param localWriteTime - The original write time of this mutation.\n * @param baseMutations - Mutations that are used to populate the base\n * values when this mutation is applied locally. This can be used to locally\n * overwrite values that are persisted in the remote document cache. Base\n * mutations are never sent to the backend.\n * @param mutations - The user-provided mutations in this mutation batch.\n * User-provided mutations are applied both locally and remotely on the\n * backend.\n */\n constructor(t, e, n, s) {\n this.batchId = t, this.localWriteTime = e, this.baseMutations = n, this.mutations = s;\n }\n /**\n * Applies all the mutations in this MutationBatch to the specified document\n * to compute the state of the remote document\n *\n * @param document - The document to apply mutations to.\n * @param batchResult - The result of applying the MutationBatch to the\n * backend.\n */ applyToRemoteDocument(t, e) {\n const n = e.mutationResults;\n for (let e = 0; e < this.mutations.length; e++) {\n const s = this.mutations[e];\n if (s.key.isEqual(t.key)) {\n Hn(s, t, n[e]);\n }\n }\n }\n /**\n * Computes the local view of a document given all the mutations in this\n * batch.\n *\n * @param document - The document to apply mutations to.\n * @param mutatedFields - Fields that have been updated before applying this mutation batch.\n * @returns A `FieldMask` representing all the fields that are mutated.\n */ applyToLocalView(t, e) {\n // First, apply the base state. This allows us to apply non-idempotent\n // transform against a consistent set of values.\n for (const n of this.baseMutations) n.key.isEqual(t.key) && (e = Jn(n, t, e, this.localWriteTime));\n // Second, apply all user-provided mutations.\n for (const n of this.mutations) n.key.isEqual(t.key) && (e = Jn(n, t, e, this.localWriteTime));\n return e;\n }\n /**\n * Computes the local view for all provided documents given the mutations in\n * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to\n * replace all the mutation applications.\n */ applyToLocalDocumentSet(t, e) {\n // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations\n // directly (as done in `applyToLocalView()`), we can reduce the complexity\n // to O(n).\n const n = ys();\n return this.mutations.forEach((s => {\n const i = t.get(s.key), r = i.overlayedDocument;\n // TODO(mutabledocuments): This method should take a MutableDocumentMap\n // and we should remove this cast.\n let o = this.applyToLocalView(r, i.mutatedFields);\n // Set mutatedFields to null if the document is only from local mutations.\n // This creates a Set or Delete mutation, instead of trying to create a\n // patch mutation as the overlay.\n o = e.has(s.key) ? null : o;\n const u = zn(r, o);\n null !== u && n.set(s.key, u), r.isValidDocument() || r.convertToNoDocument(st.min());\n })), n;\n }\n keys() {\n return this.mutations.reduce(((t, e) => t.add(e.key)), Es());\n }\n isEqual(t) {\n return this.batchId === t.batchId && tt(this.mutations, t.mutations, ((t, e) => Xn(t, e))) && tt(this.baseMutations, t.baseMutations, ((t, e) => Xn(t, e)));\n }\n}\n\n/** The result of applying a mutation batch to the backend. */ class ji {\n constructor(t, e, n, \n /**\n * A pre-computed mapping from each mutated document to the resulting\n * version.\n */\n s) {\n this.batch = t, this.commitVersion = e, this.mutationResults = n, this.docVersions = s;\n }\n /**\n * Creates a new MutationBatchResult for the given batch and results. There\n * must be one result for each mutation in the batch. This static factory\n * caches a document=&gt;version mapping (docVersions).\n */ static from(t, e, n) {\n M(t.mutations.length === n.length);\n let s = Is;\n const i = t.mutations;\n for (let t = 0; t < i.length; t++) s = s.insert(i[t].key, n[t].version);\n return new ji(t, e, n, s);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Representation of an overlay computed by Firestore.\n *\n * Holds information about a mutation and the largest batch id in Firestore when\n * the mutation was created.\n */ class Wi {\n constructor(t, e) {\n this.largestBatchId = t, this.mutation = e;\n }\n getKey() {\n return this.mutation.key;\n }\n isEqual(t) {\n return null !== t && this.mutation === t.mutation;\n }\n toString() {\n return `Overlay{\\n largestBatchId: ${this.largestBatchId},\\n mutation: ${this.mutation.toString()}\\n }`;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable set of metadata that the local store tracks for each target.\n */ class zi {\n constructor(\n /** The target being listened to. */\n t, \n /**\n * The target ID to which the target corresponds; Assigned by the\n * LocalStore for user listens and by the SyncEngine for limbo watches.\n */\n e, \n /** The purpose of the target. */\n n, \n /**\n * The sequence number of the last transaction during which this target data\n * was modified.\n */\n s, \n /** The latest snapshot version seen for this target. */\n i = st.min()\n /**\n * The maximum snapshot version at which the associated view\n * contained no limbo documents.\n */ , r = st.min()\n /**\n * An opaque, server-assigned token that allows watching a target to be\n * resumed after disconnecting without retransmitting all the data that\n * matches the target. The resume token essentially identifies a point in\n * time from which the server should resume sending results.\n */ , o = Qt.EMPTY_BYTE_STRING) {\n this.target = t, this.targetId = e, this.purpose = n, this.sequenceNumber = s, this.snapshotVersion = i, \n this.lastLimboFreeSnapshotVersion = r, this.resumeToken = o;\n }\n /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(t) {\n return new zi(this.target, this.targetId, this.purpose, t, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken);\n }\n /**\n * Creates a new target data instance with an updated resume token and\n * snapshot version.\n */ withResumeToken(t, e) {\n return new zi(this.target, this.targetId, this.purpose, this.sequenceNumber, e, this.lastLimboFreeSnapshotVersion, t);\n }\n /**\n * Creates a new target data instance with an updated last limbo free\n * snapshot version number.\n */ withLastLimboFreeSnapshotVersion(t) {\n return new zi(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, t, this.resumeToken);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Serializer for values stored in the LocalStore. */ class Hi {\n constructor(t) {\n this.ie = t;\n }\n}\n\n/** Decodes a remote document from storage locally to a Document. */ function Ji(t, e) {\n let n;\n if (e.document) n = Ys(t.ie, e.document, !!e.hasCommittedMutations); else if (e.noDocument) {\n const t = ct.fromSegments(e.noDocument.path), s = tr(e.noDocument.readTime);\n n = Ze.newNoDocument(t, s), e.hasCommittedMutations && n.setHasCommittedMutations();\n } else {\n if (!e.unknownDocument) return O();\n {\n const t = ct.fromSegments(e.unknownDocument.path), s = tr(e.unknownDocument.version);\n n = Ze.newUnknownDocument(t, s);\n }\n }\n return e.readTime && n.setReadTime(function(t) {\n const e = new nt(t[0], t[1]);\n return st.fromTimestamp(e);\n }(e.readTime)), n;\n}\n\n/** Encodes a document for storage locally. */ function Yi(t, e) {\n const n = e.key, s = {\n prefixPath: n.getCollectionPath().popLast().toArray(),\n collectionGroup: n.collectionGroup,\n documentId: n.path.lastSegment(),\n readTime: Xi(e.readTime),\n hasCommittedMutations: e.hasCommittedMutations\n };\n if (e.isFoundDocument()) s.document = function(t, e) {\n return {\n name: Gs(t, e.key),\n fields: e.data.value.mapValue.fields,\n updateTime: $s(t, e.version.toTimestamp()),\n createTime: $s(t, e.createTime.toTimestamp())\n };\n }(t.ie, e); else if (e.isNoDocument()) s.noDocument = {\n path: n.path.toArray(),\n readTime: Zi(e.version)\n }; else {\n if (!e.isUnknownDocument()) return O();\n s.unknownDocument = {\n path: n.path.toArray(),\n version: Zi(e.version)\n };\n }\n return s;\n}\n\nfunction Xi(t) {\n const e = t.toTimestamp();\n return [ e.seconds, e.nanoseconds ];\n}\n\nfunction Zi(t) {\n const e = t.toTimestamp();\n return {\n seconds: e.seconds,\n nanoseconds: e.nanoseconds\n };\n}\n\nfunction tr(t) {\n const e = new nt(t.seconds, t.nanoseconds);\n return st.fromTimestamp(e);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n/** Decodes a DbMutationBatch into a MutationBatch */\nfunction er(t, e) {\n const n = (e.baseMutations || []).map((e => ei(t.ie, e)));\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let t = 0; t < e.mutations.length - 1; ++t) {\n const n = e.mutations[t];\n if (t + 1 < e.mutations.length && void 0 !== e.mutations[t + 1].transform) {\n const s = e.mutations[t + 1];\n n.updateTransforms = s.transform.fieldTransforms, e.mutations.splice(t + 1, 1), \n ++t;\n }\n }\n const s = e.mutations.map((e => ei(t.ie, e))), i = nt.fromMillis(e.localWriteTimeMs);\n return new Qi(e.batchId, i, n, s);\n}\n\n/** Decodes a DbTarget into TargetData */ function nr(t) {\n const e = tr(t.readTime), n = void 0 !== t.lastLimboFreeSnapshotVersion ? tr(t.lastLimboFreeSnapshotVersion) : st.min();\n let s;\n var i;\n return void 0 !== t.query.documents ? (M(1 === (i = t.query).documents.length), \n s = gn(ln(Ws(i.documents[0])))) : s = function(t) {\n return gn(ri(t));\n }(t.query), new zi(s, t.targetId, 0 /* TargetPurpose.Listen */ , t.lastListenSequenceNumber, e, n, Qt.fromBase64String(t.resumeToken));\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */ function sr(t, e) {\n const n = Zi(e.snapshotVersion), s = Zi(e.lastLimboFreeSnapshotVersion);\n let i;\n i = rn(e.target) ? si(t.ie, e.target) : ii(t.ie, e.target);\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const r = e.resumeToken.toBase64();\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: e.targetId,\n canonicalId: nn(e.target),\n readTime: n,\n resumeToken: r,\n lastListenSequenceNumber: e.sequenceNumber,\n lastLimboFreeSnapshotVersion: s,\n query: i\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nfunction ir(t) {\n const e = ri({\n parent: t.parent,\n structuredQuery: t.structuredQuery\n });\n return \"LAST\" === t.limitType ? pn(e, e.limit, \"L\" /* LimitType.Last */) : e;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nfunction rr(t, e) {\n return new Wi(e.largestBatchId, ei(t.ie, e.overlayMutation));\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nfunction or(t, e) {\n const n = e.path.lastSegment();\n return [ t, mi(e.path.popLast()), n ];\n}\n\nfunction ur(t, e, n, s) {\n return {\n indexId: t,\n uid: e.uid || \"\",\n sequenceNumber: n,\n readTime: Zi(s.readTime),\n documentKey: mi(s.documentKey.path),\n largestBatchId: s.largestBatchId\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class cr {\n getBundleMetadata(t, e) {\n return ar(t).get(e).next((t => {\n if (t) return {\n id: (e = t).bundleId,\n createTime: tr(e.createTime),\n version: e.version\n };\n /** Encodes a DbBundle to a BundleMetadata object. */\n var e;\n /** Encodes a BundleMetadata to a DbBundle. */ }));\n }\n saveBundleMetadata(t, e) {\n return ar(t).put({\n bundleId: (n = e).id,\n createTime: Zi(qs(n.createTime)),\n version: n.version\n });\n var n;\n /** Encodes a DbNamedQuery to a NamedQuery. */ }\n getNamedQuery(t, e) {\n return hr(t).get(e).next((t => {\n if (t) return {\n name: (e = t).name,\n query: ir(e.bundledQuery),\n readTime: tr(e.readTime)\n };\n var e;\n /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ }));\n }\n saveNamedQuery(t, e) {\n return hr(t).put(function(t) {\n return {\n name: t.name,\n readTime: Zi(qs(t.readTime)),\n bundledQuery: t.bundledQuery\n };\n }(e));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */ function ar(t) {\n return Gi(t, \"bundles\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */ function hr(t) {\n return Gi(t, \"namedQueries\");\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */ class lr {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(t, e) {\n this.yt = t, this.userId = e;\n }\n static re(t, e) {\n const n = e.uid || \"\";\n return new lr(t, n);\n }\n getOverlay(t, e) {\n return fr(t).get(or(this.userId, e)).next((t => t ? rr(this.yt, t) : null));\n }\n getOverlays(t, e) {\n const n = gs();\n return At.forEach(e, (e => this.getOverlay(t, e).next((t => {\n null !== t && n.set(e, t);\n })))).next((() => n));\n }\n saveOverlays(t, e, n) {\n const s = [];\n return n.forEach(((n, i) => {\n const r = new Wi(e, i);\n s.push(this.oe(t, r));\n })), At.waitFor(s);\n }\n removeOverlaysForBatchId(t, e, n) {\n const s = new Set;\n // Get the set of unique collection paths.\n e.forEach((t => s.add(mi(t.getCollectionPath()))));\n const i = [];\n return s.forEach((e => {\n const s = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, n + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n i.push(fr(t).Y(\"collectionPathOverlayIndex\", s));\n })), At.waitFor(i);\n }\n getOverlaysForCollection(t, e, n) {\n const s = gs(), i = mi(e), r = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return fr(t).W(\"collectionPathOverlayIndex\", r).next((t => {\n for (const e of t) {\n const t = rr(this.yt, e);\n s.set(t.getKey(), t);\n }\n return s;\n }));\n }\n getOverlaysForCollectionGroup(t, e, n, s) {\n const i = gs();\n let r;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const o = IDBKeyRange.bound([ this.userId, e, n ], [ this.userId, e, Number.POSITIVE_INFINITY ], \n /*lowerOpen=*/ !0);\n return fr(t).Z({\n index: \"collectionGroupOverlayIndex\",\n range: o\n }, ((t, e, n) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const o = rr(this.yt, e);\n i.size() < s || o.largestBatchId === r ? (i.set(o.getKey(), o), r = o.largestBatchId) : n.done();\n })).next((() => i));\n }\n oe(t, e) {\n return fr(t).put(function(t, e, n) {\n const [s, i, r] = or(e, n.mutation.key);\n return {\n userId: e,\n collectionPath: i,\n documentId: r,\n collectionGroup: n.mutation.key.getCollectionGroup(),\n largestBatchId: n.largestBatchId,\n overlayMutation: ti(t.ie, n.mutation)\n };\n }(this.yt, this.userId, e));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */ function fr(t) {\n return Gi(t, \"documentOverlays\");\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// Note: This code is copied from the backend. Code that is not used by\n// Firestore was removed.\n/** Firestore index value writer. */\nclass dr {\n constructor() {}\n // The write methods below short-circuit writing terminators for values\n // containing a (terminating) truncated value.\n // As an example, consider the resulting encoding for:\n // [\"bar\", [2, \"foo\"]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TERM, TERM, TERM)\n // [\"bar\", [2, truncated(\"foo\")]] -> (STRING, \"bar\", TERM, ARRAY, NUMBER, 2, STRING, \"foo\", TRUNC)\n // [\"bar\", truncated([\"foo\"])] -> (STRING, \"bar\", TERM, ARRAY. STRING, \"foo\", TERM, TRUNC)\n /** Writes an index value. */\n ue(t, e) {\n this.ce(t, e), \n // Write separator to split index values\n // (see go/firestore-storage-format#encodings).\n e.ae();\n }\n ce(t, e) {\n if (\"nullValue\" in t) this.he(e, 5); else if (\"booleanValue\" in t) this.he(e, 10), \n e.le(t.booleanValue ? 1 : 0); else if (\"integerValue\" in t) this.he(e, 15), e.le(zt(t.integerValue)); else if (\"doubleValue\" in t) {\n const n = zt(t.doubleValue);\n isNaN(n) ? this.he(e, 13) : (this.he(e, 15), Ut(n) ? \n // -0.0, 0 and 0.0 are all considered the same\n e.le(0) : e.le(n));\n } else if (\"timestampValue\" in t) {\n const n = t.timestampValue;\n this.he(e, 20), \"string\" == typeof n ? e.fe(n) : (e.fe(`${n.seconds || \"\"}`), e.le(n.nanos || 0));\n } else if (\"stringValue\" in t) this.de(t.stringValue, e), this._e(e); else if (\"bytesValue\" in t) this.he(e, 30), \n e.we(Ht(t.bytesValue)), this._e(e); else if (\"referenceValue\" in t) this.me(t.referenceValue, e); else if (\"geoPointValue\" in t) {\n const n = t.geoPointValue;\n this.he(e, 45), e.le(n.latitude || 0), e.le(n.longitude || 0);\n } else \"mapValue\" in t ? we(t) ? this.he(e, Number.MAX_SAFE_INTEGER) : (this.ge(t.mapValue, e), \n this._e(e)) : \"arrayValue\" in t ? (this.ye(t.arrayValue, e), this._e(e)) : O();\n }\n de(t, e) {\n this.he(e, 25), this.pe(t, e);\n }\n pe(t, e) {\n e.fe(t);\n }\n ge(t, e) {\n const n = t.fields || {};\n this.he(e, 55);\n for (const t of Object.keys(n)) this.de(t, e), this.ce(n[t], e);\n }\n ye(t, e) {\n const n = t.values || [];\n this.he(e, 50);\n for (const t of n) this.ce(t, e);\n }\n me(t, e) {\n this.he(e, 37);\n ct.fromName(t).path.forEach((t => {\n this.he(e, 60), this.pe(t, e);\n }));\n }\n he(t, e) {\n t.le(e);\n }\n _e(t) {\n // While the SDK does not implement truncation, the truncation marker is\n // used to terminate all variable length values (which are strings, bytes,\n // references, arrays and maps).\n t.le(2);\n }\n}\n\ndr.Ie = new dr;\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nfunction _r(t) {\n if (0 === t) return 8;\n let e = 0;\n return t >> 4 == 0 && (\n // Test if the first four bits are zero.\n e += 4, t <<= 4), t >> 6 == 0 && (\n // Test if the first two (or next two) bits are zero.\n e += 2, t <<= 2), t >> 7 == 0 && (\n // Test if the remaining bit is zero.\n e += 1), e;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction wr(t) {\n // This is just the number of bytes for the unsigned representation of the number.\n const e = 64 - function(t) {\n let e = 0;\n for (let n = 0; n < 8; ++n) {\n const s = _r(255 & t[n]);\n if (e += s, 8 !== s) break;\n }\n return e;\n }(t);\n return Math.ceil(e / 8);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */ class mr {\n constructor() {\n this.buffer = new Uint8Array(1024), this.position = 0;\n }\n Te(t) {\n const e = t[Symbol.iterator]();\n let n = e.next();\n for (;!n.done; ) this.Ee(n.value), n = e.next();\n this.Ae();\n }\n Re(t) {\n const e = t[Symbol.iterator]();\n let n = e.next();\n for (;!n.done; ) this.be(n.value), n = e.next();\n this.Pe();\n }\n /** Writes utf8 bytes into this byte sequence, ascending. */ ve(t) {\n for (const e of t) {\n const t = e.charCodeAt(0);\n if (t < 128) this.Ee(t); else if (t < 2048) this.Ee(960 | t >>> 6), this.Ee(128 | 63 & t); else if (e < \"\\ud800\" || \"\\udbff\" < e) this.Ee(480 | t >>> 12), \n this.Ee(128 | 63 & t >>> 6), this.Ee(128 | 63 & t); else {\n const t = e.codePointAt(0);\n this.Ee(240 | t >>> 18), this.Ee(128 | 63 & t >>> 12), this.Ee(128 | 63 & t >>> 6), \n this.Ee(128 | 63 & t);\n }\n }\n this.Ae();\n }\n /** Writes utf8 bytes into this byte sequence, descending */ Ve(t) {\n for (const e of t) {\n const t = e.charCodeAt(0);\n if (t < 128) this.be(t); else if (t < 2048) this.be(960 | t >>> 6), this.be(128 | 63 & t); else if (e < \"\\ud800\" || \"\\udbff\" < e) this.be(480 | t >>> 12), \n this.be(128 | 63 & t >>> 6), this.be(128 | 63 & t); else {\n const t = e.codePointAt(0);\n this.be(240 | t >>> 18), this.be(128 | 63 & t >>> 12), this.be(128 | 63 & t >>> 6), \n this.be(128 | 63 & t);\n }\n }\n this.Pe();\n }\n Se(t) {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const e = this.De(t), n = wr(e);\n this.Ce(1 + n), this.buffer[this.position++] = 255 & n;\n // Write the length\n for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = 255 & e[t];\n }\n xe(t) {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const e = this.De(t), n = wr(e);\n this.Ce(1 + n), this.buffer[this.position++] = ~(255 & n);\n // Write the length\n for (let t = e.length - n; t < e.length; ++t) this.buffer[this.position++] = ~(255 & e[t]);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */ Ne() {\n this.ke(255), this.ke(255);\n }\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */ Oe() {\n this.Me(255), this.Me(255);\n }\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */ reset() {\n this.position = 0;\n }\n seed(t) {\n this.Ce(t.length), this.buffer.set(t, this.position), this.position += t.length;\n }\n /** Makes a copy of the encoded bytes in this buffer. */ Fe() {\n return this.buffer.slice(0, this.position);\n }\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */ De(t) {\n const e = \n /** Converts a JavaScript number to a byte array (using big endian encoding). */\n function(t) {\n const e = new DataView(new ArrayBuffer(8));\n return e.setFloat64(0, t, /* littleEndian= */ !1), new Uint8Array(e.buffer);\n }(t), n = 0 != (128 & e[0]);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n // Revert the two complement to get natural ordering\n e[0] ^= n ? 255 : 128;\n for (let t = 1; t < e.length; ++t) e[t] ^= n ? 255 : 0;\n return e;\n }\n /** Writes a single byte ascending to the buffer. */ Ee(t) {\n const e = 255 & t;\n 0 === e ? (this.ke(0), this.ke(255)) : 255 === e ? (this.ke(255), this.ke(0)) : this.ke(e);\n }\n /** Writes a single byte descending to the buffer. */ be(t) {\n const e = 255 & t;\n 0 === e ? (this.Me(0), this.Me(255)) : 255 === e ? (this.Me(255), this.Me(0)) : this.Me(t);\n }\n Ae() {\n this.ke(0), this.ke(1);\n }\n Pe() {\n this.Me(0), this.Me(1);\n }\n ke(t) {\n this.Ce(1), this.buffer[this.position++] = t;\n }\n Me(t) {\n this.Ce(1), this.buffer[this.position++] = ~t;\n }\n Ce(t) {\n const e = t + this.position;\n if (e <= this.buffer.length) return;\n // Try doubling.\n let n = 2 * this.buffer.length;\n // Still not big enough? Just allocate the right size.\n n < e && (n = e);\n // Create the new buffer.\n const s = new Uint8Array(n);\n s.set(this.buffer), // copy old data\n this.buffer = s;\n }\n}\n\nclass gr {\n constructor(t) {\n this.$e = t;\n }\n we(t) {\n this.$e.Te(t);\n }\n fe(t) {\n this.$e.ve(t);\n }\n le(t) {\n this.$e.Se(t);\n }\n ae() {\n this.$e.Ne();\n }\n}\n\nclass yr {\n constructor(t) {\n this.$e = t;\n }\n we(t) {\n this.$e.Re(t);\n }\n fe(t) {\n this.$e.Ve(t);\n }\n le(t) {\n this.$e.xe(t);\n }\n ae() {\n this.$e.Oe();\n }\n}\n\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */ class pr {\n constructor() {\n this.$e = new mr, this.Be = new gr(this.$e), this.Le = new yr(this.$e);\n }\n seed(t) {\n this.$e.seed(t);\n }\n qe(t) {\n return 0 /* IndexKind.ASCENDING */ === t ? this.Be : this.Le;\n }\n Fe() {\n return this.$e.Fe();\n }\n reset() {\n this.$e.reset();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Represents an index entry saved by the SDK in persisted storage. */ class Ir {\n constructor(t, e, n, s) {\n this.indexId = t, this.documentKey = e, this.arrayValue = n, this.directionalValue = s;\n }\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */ Ue() {\n const t = this.directionalValue.length, e = 0 === t || 255 === this.directionalValue[t - 1] ? t + 1 : t, n = new Uint8Array(e);\n return n.set(this.directionalValue, 0), e !== t ? n.set([ 0 ], this.directionalValue.length) : ++n[n.length - 1], \n new Ir(this.indexId, this.documentKey, this.arrayValue, n);\n }\n}\n\nfunction Tr(t, e) {\n let n = t.indexId - e.indexId;\n return 0 !== n ? n : (n = Er(t.arrayValue, e.arrayValue), 0 !== n ? n : (n = Er(t.directionalValue, e.directionalValue), \n 0 !== n ? n : ct.comparator(t.documentKey, e.documentKey)));\n}\n\nfunction Er(t, e) {\n for (let n = 0; n < t.length && n < e.length; ++n) {\n const s = t[n] - e[n];\n if (0 !== s) return s;\n }\n return t.length - e.length;\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */ class Ar {\n constructor(t) {\n this.collectionId = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(), \n this.Ke = t.orderBy, this.Ge = [];\n for (const e of t.filters) {\n const t = e;\n t.isInequality() ? this.Qe = t : this.Ge.push(t);\n }\n }\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */ je(t) {\n M(t.collectionGroup === this.collectionId);\n // If there is an array element, find a matching filter.\n const e = ht(t);\n if (void 0 !== e && !this.We(e)) return !1;\n const n = lt(t);\n let s = 0, i = 0;\n // Process all equalities first. Equalities can appear out of order.\n for (;s < n.length && this.We(n[s]); ++s) ;\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (s === n.length) return !0;\n // If there is an inequality filter, the next segment must match both the\n // filter and the first orderBy clause.\n if (void 0 !== this.Qe) {\n const t = n[s];\n if (!this.ze(this.Qe, t) || !this.He(this.Ke[i++], t)) return !1;\n ++s;\n }\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (;s < n.length; ++s) {\n const t = n[s];\n if (i >= this.Ke.length || !this.He(this.Ke[i++], t)) return !1;\n }\n return !0;\n }\n We(t) {\n for (const e of this.Ge) if (this.ze(e, t)) return !0;\n return !1;\n }\n ze(t, e) {\n if (void 0 === t || !t.field.isEqual(e.fieldPath)) return !1;\n const n = \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t.op;\n return 2 /* IndexKind.CONTAINS */ === e.kind === n;\n }\n He(t, e) {\n return !!t.field.isEqual(e.fieldPath) && (0 /* IndexKind.ASCENDING */ === e.kind && \"asc\" /* Direction.ASCENDING */ === t.dir || 1 /* IndexKind.DESCENDING */ === e.kind && \"desc\" /* Direction.DESCENDING */ === t.dir);\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */ function Rr(t) {\n var e, n;\n if (M(t instanceof Re || t instanceof be), t instanceof Re) {\n if (t instanceof Be) {\n const s = (null === (n = null === (e = t.value.arrayValue) || void 0 === e ? void 0 : e.values) || void 0 === n ? void 0 : n.map((e => Re.create(t.field, \"==\" /* Operator.EQUAL */ , e)))) || [];\n return be.create(s, \"or\" /* CompositeOperator.OR */);\n }\n // We have reached other kinds of field filters.\n return t;\n }\n // We have a composite filter.\n const s = t.filters.map((t => Rr(t)));\n return be.create(s, t.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n * <p>Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */ function br(t) {\n if (0 === t.getFilters().length) return [];\n const e = Sr(Rr(t));\n return M(Vr(e)), Pr(e) || vr(e) ? [ e ] : e.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function Pr(t) {\n return t instanceof Re;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */ function vr(t) {\n return t instanceof be && Ve(t);\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n * <p>In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */ function Vr(t) {\n return Pr(t) || vr(t) || \n /**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\n function(t) {\n if (t instanceof be && ve(t)) {\n for (const e of t.getFilters()) if (!Pr(e) && !vr(e)) return !1;\n return !0;\n }\n return !1;\n }(t);\n}\n\nfunction Sr(t) {\n if (M(t instanceof Re || t instanceof be), t instanceof Re) return t;\n if (1 === t.filters.length) return Sr(t.filters[0]);\n // Compute DNF for each of the subfilters first\n const e = t.filters.map((t => Sr(t)));\n let n = be.create(e, t.op);\n return n = xr(n), Vr(n) ? n : (M(n instanceof be), M(Pe(n)), M(n.filters.length > 1), \n n.filters.reduce(((t, e) => Dr(t, e))));\n}\n\nfunction Dr(t, e) {\n let n;\n return M(t instanceof Re || t instanceof be), M(e instanceof Re || e instanceof be), \n // FieldFilter FieldFilter\n n = t instanceof Re ? e instanceof Re ? function(t, e) {\n // Conjunction distribution for two field filters is the conjunction of them.\n return be.create([ t, e ], \"and\" /* CompositeOperator.AND */);\n }(t, e) : Cr(t, e) : e instanceof Re ? Cr(e, t) : function(t, e) {\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n // Case 1 is a merge.\n if (M(t.filters.length > 0 && e.filters.length > 0), Pe(t) && Pe(e)) return xe(t, e.getFilters());\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const n = ve(t) ? t : e, s = ve(t) ? e : t, i = n.filters.map((t => Dr(t, s)));\n return be.create(i, \"or\" /* CompositeOperator.OR */);\n }(t, e), xr(n);\n}\n\nfunction Cr(t, e) {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (Pe(e)) \n // Case 1\n return xe(e, t.getFilters());\n {\n // Case 2\n const n = e.filters.map((e => Dr(t, e)));\n return be.create(n, \"or\" /* CompositeOperator.OR */);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n * <ul>\n * <li>A | (B | C) == (A | B) | C == (A | B | C)\n * <li>A & (B & C) == (A & B) & C == (A & B & C)\n * </ul>\n *\n * <p>For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */ function xr(t) {\n if (M(t instanceof Re || t instanceof be), t instanceof Re) return t;\n const e = t.getFilters();\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (1 === e.length) return xr(e[0]);\n // Associativity applied to a flat composite filter results is itself.\n if (Se(t)) return t;\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const n = e.map((t => xr(t))), s = [];\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n return n.forEach((e => {\n e instanceof Re ? s.push(e) : e instanceof be && (e.op === t.op ? \n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n s.push(...e.filters) : \n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n s.push(e));\n })), 1 === s.length ? s[0] : be.create(s, t.op);\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of IndexManager.\n */ class Nr {\n constructor() {\n this.Je = new kr;\n }\n addToCollectionParentIndex(t, e) {\n return this.Je.add(e), At.resolve();\n }\n getCollectionParents(t, e) {\n return At.resolve(this.Je.getEntries(e));\n }\n addFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve();\n }\n deleteFieldIndex(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve();\n }\n getDocumentsMatchingTarget(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve(null);\n }\n getIndexType(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve(0 /* IndexType.NONE */);\n }\n getFieldIndexes(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve([]);\n }\n getNextCollectionGroupToUpdate(t) {\n // Field indices are not supported with memory persistence.\n return At.resolve(null);\n }\n getMinOffset(t, e) {\n return At.resolve(yt.min());\n }\n getMinOffsetFromCollectionGroup(t, e) {\n return At.resolve(yt.min());\n }\n updateCollectionGroup(t, e, n) {\n // Field indices are not supported with memory persistence.\n return At.resolve();\n }\n updateIndexEntries(t, e) {\n // Field indices are not supported with memory persistence.\n return At.resolve();\n }\n}\n\n/**\n * Internal implementation of the collection-parent index exposed by MemoryIndexManager.\n * Also used for in-memory caching by IndexedDbIndexManager and initial index population\n * in indexeddb_schema.ts\n */ class kr {\n constructor() {\n this.index = {};\n }\n // Returns false if the entry already existed.\n add(t) {\n const e = t.lastSegment(), n = t.popLast(), s = this.index[e] || new We(rt.comparator), i = !s.has(n);\n return this.index[e] = s.add(n), i;\n }\n has(t) {\n const e = t.lastSegment(), n = t.popLast(), s = this.index[e];\n return s && s.has(n);\n }\n getEntries(t) {\n return (this.index[t] || new We(rt.comparator)).toArray();\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Or = new Uint8Array(0);\n\n/**\n * A persisted implementation of IndexManager.\n *\n * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index\n * data as it supports multi-tab access.\n */\nclass Mr {\n constructor(t, e) {\n this.user = t, this.databaseId = e, \n /**\n * An in-memory copy of the index entries we've already written since the SDK\n * launched. Used to avoid re-writing the same entry repeatedly.\n *\n * This is *NOT* a complete cache of what's in persistence and so can never be\n * used to satisfy reads.\n */\n this.Ye = new kr, \n /**\n * Maps from a target to its equivalent list of sub-targets. Each sub-target\n * contains only one term from the target's disjunctive normal form (DNF).\n */\n this.Xe = new ls((t => nn(t)), ((t, e) => sn(t, e))), this.uid = t.uid || \"\";\n }\n /**\n * Adds a new entry to the collection parent index.\n *\n * Repeated calls for the same collectionPath should be avoided within a\n * transaction as IndexedDbIndexManager only caches writes once a transaction\n * has been committed.\n */ addToCollectionParentIndex(t, e) {\n if (!this.Ye.has(e)) {\n const n = e.lastSegment(), s = e.popLast();\n t.addOnCommittedListener((() => {\n // Add the collection to the in memory cache only if the transaction was\n // successfully committed.\n this.Ye.add(e);\n }));\n const i = {\n collectionId: n,\n parent: mi(s)\n };\n return Fr(t).put(i);\n }\n return At.resolve();\n }\n getCollectionParents(t, e) {\n const n = [], s = IDBKeyRange.bound([ e, \"\" ], [ et(e), \"\" ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return Fr(t).W(s).next((t => {\n for (const s of t) {\n // This collectionId guard shouldn't be necessary (and isn't as long\n // as we're running in a real browser), but there's a bug in\n // indexeddbshim that breaks our range in our tests running in node:\n // https://github.com/axemclion/IndexedDBShim/issues/334\n if (s.collectionId !== e) break;\n n.push(pi(s.parent));\n }\n return n;\n }));\n }\n addFieldIndex(t, e) {\n // TODO(indexing): Verify that the auto-incrementing index ID works in\n // Safari & Firefox.\n const n = Br(t), s = function(t) {\n return {\n indexId: t.indexId,\n collectionGroup: t.collectionGroup,\n fields: t.fields.map((t => [ t.fieldPath.canonicalString(), t.kind ]))\n };\n }(e);\n delete s.indexId;\n // `indexId` is auto-populated by IndexedDb\n const i = n.add(s);\n if (e.indexState) {\n const n = Lr(t);\n return i.next((t => {\n n.put(ur(t, this.user, e.indexState.sequenceNumber, e.indexState.offset));\n }));\n }\n return i.next();\n }\n deleteFieldIndex(t, e) {\n const n = Br(t), s = Lr(t), i = $r(t);\n return n.delete(e.indexId).next((() => s.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ e.indexId ], [ e.indexId + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0))));\n }\n getDocumentsMatchingTarget(t, e) {\n const n = $r(t);\n let s = !0;\n const i = new Map;\n return At.forEach(this.Ze(e), (e => this.tn(t, e).next((t => {\n s && (s = !!t), i.set(e, t);\n })))).next((() => {\n if (s) {\n let t = Es();\n const s = [];\n return At.forEach(i, ((i, r) => {\n var o;\n C(\"IndexedDbIndexManager\", `Using index ${o = i, `id=${o.indexId}|cg=${o.collectionGroup}|f=${o.fields.map((t => `${t.fieldPath}:${t.kind}`)).join(\",\")}`} to execute ${nn(e)}`);\n const u = function(t, e) {\n const n = ht(e);\n if (void 0 === n) return null;\n for (const e of on(t, n.fieldPath)) switch (e.op) {\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n return e.value.arrayValue.values || [];\n\n case \"array-contains\" /* Operator.ARRAY_CONTAINS */ :\n return [ e.value ];\n // Remaining filters are not array filters.\n }\n return null;\n }\n /**\n * Returns the list of values that are used in != or NOT_IN filters. Returns\n * `null` if there are no such filters.\n */ (r, i), c = function(t, e) {\n const n = new Map;\n for (const s of lt(e)) for (const e of on(t, s.fieldPath)) switch (e.op) {\n case \"==\" /* Operator.EQUAL */ :\n case \"in\" /* Operator.IN */ :\n // Encode equality prefix, which is encoded in the index value before\n // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to\n // `value != 'ab'`).\n n.set(s.fieldPath.canonicalString(), e.value);\n break;\n\n case \"not-in\" /* Operator.NOT_IN */ :\n case \"!=\" /* Operator.NOT_EQUAL */ :\n // NotIn/NotEqual is always a suffix. There cannot be any remaining\n // segments and hence we can return early here.\n return n.set(s.fieldPath.canonicalString(), e.value), Array.from(n.values());\n // Remaining filters cannot be used as notIn bounds.\n }\n return null;\n }\n /**\n * Returns a lower bound of field values that can be used as a starting point to\n * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound\n * exists.\n */ (r, i), a = function(t, e) {\n const n = [];\n let s = !0;\n // For each segment, retrieve a lower bound if there is a suitable filter or\n // startAt.\n for (const i of lt(e)) {\n const e = 0 /* IndexKind.ASCENDING */ === i.kind ? un(t, i.fieldPath, t.startAt) : cn(t, i.fieldPath, t.startAt);\n n.push(e.value), s && (s = e.inclusive);\n }\n return new Ie(n, s);\n }\n /**\n * Returns an upper bound of field values that can be used as an ending point\n * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no\n * upper bound exists.\n */ (r, i), h = function(t, e) {\n const n = [];\n let s = !0;\n // For each segment, retrieve an upper bound if there is a suitable filter or\n // endAt.\n for (const i of lt(e)) {\n const e = 0 /* IndexKind.ASCENDING */ === i.kind ? cn(t, i.fieldPath, t.endAt) : un(t, i.fieldPath, t.endAt);\n n.push(e.value), s && (s = e.inclusive);\n }\n return new Ie(n, s);\n }(r, i), l = this.en(i, r, a), f = this.en(i, r, h), d = this.nn(i, r, c), _ = this.sn(i.indexId, u, l, a.inclusive, f, h.inclusive, d);\n return At.forEach(_, (i => n.J(i, e.limit).next((e => {\n e.forEach((e => {\n const n = ct.fromSegments(e.documentKey);\n t.has(n) || (t = t.add(n), s.push(n));\n }));\n }))));\n })).next((() => s));\n }\n return At.resolve(null);\n }));\n }\n Ze(t) {\n let e = this.Xe.get(t);\n if (e) return e;\n if (0 === t.filters.length) e = [ t ]; else {\n e = br(be.create(t.filters, \"and\" /* CompositeOperator.AND */)).map((e => en(t.path, t.collectionGroup, t.orderBy, e.getFilters(), t.limit, t.startAt, t.endAt)));\n }\n return this.Xe.set(t, e), e;\n }\n /**\n * Constructs a key range query on `DbIndexEntryStore` that unions all\n * bounds.\n */ sn(t, e, n, s, i, r, o) {\n // The number of total index scans we union together. This is similar to a\n // distributed normal form, but adapted for array values. We create a single\n // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter\n // combined with the values from the query bounds.\n const u = (null != e ? e.length : 1) * Math.max(n.length, i.length), c = u / (null != e ? e.length : 1), a = [];\n for (let h = 0; h < u; ++h) {\n const u = e ? this.rn(e[h / c]) : Or, l = this.on(t, u, n[h % c], s), f = this.un(t, u, i[h % c], r), d = o.map((e => this.on(t, u, e, \n /* inclusive= */ !0)));\n a.push(...this.createRange(l, f, d));\n }\n return a;\n }\n /** Generates the lower bound for `arrayValue` and `directionalValue`. */ on(t, e, n, s) {\n const i = new Ir(t, ct.empty(), e, n);\n return s ? i : i.Ue();\n }\n /** Generates the upper bound for `arrayValue` and `directionalValue`. */ un(t, e, n, s) {\n const i = new Ir(t, ct.empty(), e, n);\n return s ? i.Ue() : i;\n }\n tn(t, e) {\n const n = new Ar(e), s = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment();\n return this.getFieldIndexes(t, s).next((t => {\n // Return the index with the most number of segments.\n let e = null;\n for (const s of t) {\n n.je(s) && (!e || s.fields.length > e.fields.length) && (e = s);\n }\n return e;\n }));\n }\n getIndexType(t, e) {\n let n = 2 /* IndexType.FULL */;\n const s = this.Ze(e);\n return At.forEach(s, (e => this.tn(t, e).next((t => {\n t ? 0 /* IndexType.NONE */ !== n && t.fields.length < function(t) {\n let e = new We(ut.comparator), n = !1;\n for (const s of t.filters) for (const t of s.getFlattenedFilters()) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n t.field.isKeyField() || (\n // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately.\n // For instance, it is possible to have an index for \"a ARRAY a ASC\". Even\n // though these are on the same field, they should be counted as two\n // separate segments in an index.\n \"array-contains\" /* Operator.ARRAY_CONTAINS */ === t.op || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === t.op ? n = !0 : e = e.add(t.field));\n for (const n of t.orderBy) \n // __name__ is not an explicit segment of any index, so we don't need to\n // count it.\n n.field.isKeyField() || (e = e.add(n.field));\n return e.size + (n ? 1 : 0);\n }(e) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */;\n })))).next((() => \n // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider\n // OR queries that have a `limit` to have a partial index. For such queries we perform sorting\n // and apply the limit in memory as a post-processing step.\n function(t) {\n return null !== t.limit;\n }(e) && s.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n));\n }\n /**\n * Returns the byte encoded form of the directional values in the field index.\n * Returns `null` if the document does not have all fields specified in the\n * index.\n */ cn(t, e) {\n const n = new pr;\n for (const s of lt(t)) {\n const t = e.data.field(s.fieldPath);\n if (null == t) return null;\n const i = n.qe(s.kind);\n dr.Ie.ue(t, i);\n }\n return n.Fe();\n }\n /** Encodes a single value to the ascending index format. */ rn(t) {\n const e = new pr;\n return dr.Ie.ue(t, e.qe(0 /* IndexKind.ASCENDING */)), e.Fe();\n }\n /**\n * Returns an encoded form of the document key that sorts based on the key\n * ordering of the field index.\n */ an(t, e) {\n const n = new pr;\n return dr.Ie.ue(ce(this.databaseId, e), n.qe(function(t) {\n const e = lt(t);\n return 0 === e.length ? 0 /* IndexKind.ASCENDING */ : e[e.length - 1].kind;\n }(t))), n.Fe();\n }\n /**\n * Encodes the given field values according to the specification in `target`.\n * For IN queries, a list of possible values is returned.\n */ nn(t, e, n) {\n if (null === n) return [];\n let s = [];\n s.push(new pr);\n let i = 0;\n for (const r of lt(t)) {\n const t = n[i++];\n for (const n of s) if (this.hn(e, r.fieldPath) && he(t)) s = this.ln(s, r, t); else {\n const e = n.qe(r.kind);\n dr.Ie.ue(t, e);\n }\n }\n return this.fn(s);\n }\n /**\n * Encodes the given bounds according to the specification in `target`. For IN\n * queries, a list of possible values is returned.\n */ en(t, e, n) {\n return this.nn(t, e, n.position);\n }\n /** Returns the byte representation for the provided encoders. */ fn(t) {\n const e = [];\n for (let n = 0; n < t.length; ++n) e[n] = t[n].Fe();\n return e;\n }\n /**\n * Creates a separate encoder for each element of an array.\n *\n * The method appends each value to all existing encoders (e.g. filter(\"a\",\n * \"==\", \"a1\").filter(\"b\", \"in\", [\"b1\", \"b2\"]) becomes [\"a1,b1\", \"a1,b2\"]). A\n * list of new encoders is returned.\n */ ln(t, e, n) {\n const s = [ ...t ], i = [];\n for (const t of n.arrayValue.values || []) for (const n of s) {\n const s = new pr;\n s.seed(n.Fe()), dr.Ie.ue(t, s.qe(e.kind)), i.push(s);\n }\n return i;\n }\n hn(t, e) {\n return !!t.filters.find((t => t instanceof Re && t.field.isEqual(e) && (\"in\" /* Operator.IN */ === t.op || \"not-in\" /* Operator.NOT_IN */ === t.op)));\n }\n getFieldIndexes(t, e) {\n const n = Br(t), s = Lr(t);\n return (e ? n.W(\"collectionGroupIndex\", IDBKeyRange.bound(e, e)) : n.W()).next((t => {\n const e = [];\n return At.forEach(t, (t => s.get([ t.indexId, this.uid ]).next((n => {\n e.push(function(t, e) {\n const n = e ? new wt(e.sequenceNumber, new yt(tr(e.readTime), new ct(pi(e.documentKey)), e.largestBatchId)) : wt.empty(), s = t.fields.map((([t, e]) => new dt(ut.fromServerFormat(t), e)));\n return new at(t.indexId, t.collectionGroup, s, n);\n }(t, n));\n })))).next((() => e));\n }));\n }\n getNextCollectionGroupToUpdate(t) {\n return this.getFieldIndexes(t).next((t => 0 === t.length ? null : (t.sort(((t, e) => {\n const n = t.indexState.sequenceNumber - e.indexState.sequenceNumber;\n return 0 !== n ? n : Z(t.collectionGroup, e.collectionGroup);\n })), t[0].collectionGroup)));\n }\n updateCollectionGroup(t, e, n) {\n const s = Br(t), i = Lr(t);\n return this.dn(t).next((t => s.W(\"collectionGroupIndex\", IDBKeyRange.bound(e, e)).next((e => At.forEach(e, (e => i.put(ur(e.indexId, this.user, t, n))))))));\n }\n updateIndexEntries(t, e) {\n // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as\n // it could be used across different IndexedDB transactions. As any cached\n // data might be invalidated by other multi-tab clients, we can only trust\n // data within a single IndexedDB transaction. We therefore add a cache\n // here.\n const n = new Map;\n return At.forEach(e, ((e, s) => {\n const i = n.get(e.collectionGroup);\n return (i ? At.resolve(i) : this.getFieldIndexes(t, e.collectionGroup)).next((i => (n.set(e.collectionGroup, i), \n At.forEach(i, (n => this._n(t, e, n).next((e => {\n const i = this.wn(s, n);\n return e.isEqual(i) ? At.resolve() : this.mn(t, s, n, e, i);\n })))))));\n }));\n }\n gn(t, e, n, s) {\n return $r(t).put({\n indexId: s.indexId,\n uid: this.uid,\n arrayValue: s.arrayValue,\n directionalValue: s.directionalValue,\n orderedDocumentKey: this.an(n, e.key),\n documentKey: e.key.path.toArray()\n });\n }\n yn(t, e, n, s) {\n return $r(t).delete([ s.indexId, this.uid, s.arrayValue, s.directionalValue, this.an(n, e.key), e.key.path.toArray() ]);\n }\n _n(t, e, n) {\n const s = $r(t);\n let i = new We(Tr);\n return s.Z({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only([ n.indexId, this.uid, this.an(n, e) ])\n }, ((t, s) => {\n i = i.add(new Ir(n.indexId, e, s.arrayValue, s.directionalValue));\n })).next((() => i));\n }\n /** Creates the index entries for the given document. */ wn(t, e) {\n let n = new We(Tr);\n const s = this.cn(e, t);\n if (null == s) return n;\n const i = ht(e);\n if (null != i) {\n const r = t.data.field(i.fieldPath);\n if (he(r)) for (const i of r.arrayValue.values || []) n = n.add(new Ir(e.indexId, t.key, this.rn(i), s));\n } else n = n.add(new Ir(e.indexId, t.key, Or, s));\n return n;\n }\n /**\n * Updates the index entries for the provided document by deleting entries\n * that are no longer referenced in `newEntries` and adding all newly added\n * entries.\n */ mn(t, e, n, s, i) {\n C(\"IndexedDbIndexManager\", \"Updating index entries for document '%s'\", e.key);\n const r = [];\n return function(t, e, n, s, i) {\n const r = t.getIterator(), o = e.getIterator();\n let u = He(r), c = He(o);\n // Walk through the two sets at the same time, using the ordering defined by\n // `comparator`.\n for (;u || c; ) {\n let t = !1, e = !1;\n if (u && c) {\n const s = n(u, c);\n s < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n e = !0 : s > 0 && (\n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n t = !0);\n } else null != u ? e = !0 : t = !0;\n t ? (s(c), c = He(o)) : e ? (i(u), u = He(r)) : (u = He(r), c = He(o));\n }\n }(s, i, Tr, (\n /* onAdd= */ s => {\n r.push(this.gn(t, e, n, s));\n }), (\n /* onRemove= */ s => {\n r.push(this.yn(t, e, n, s));\n })), At.waitFor(r);\n }\n dn(t) {\n let e = 1;\n return Lr(t).Z({\n index: \"sequenceNumberIndex\",\n reverse: !0,\n range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ])\n }, ((t, n, s) => {\n s.done(), e = n.sequenceNumber + 1;\n })).next((() => e));\n }\n /**\n * Returns a new set of IDB ranges that splits the existing range and excludes\n * any values that match the `notInValue` from these ranges. As an example,\n * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`.\n */ createRange(t, e, n) {\n // The notIn values need to be sorted and unique so that we can return a\n // sorted set of non-overlapping ranges.\n n = n.sort(((t, e) => Tr(t, e))).filter(((t, e, n) => !e || 0 !== Tr(t, n[e - 1])));\n const s = [];\n s.push(t);\n for (const i of n) {\n const n = Tr(i, t), r = Tr(i, e);\n if (0 === n) \n // `notInValue` is the lower bound. We therefore need to raise the bound\n // to the next value.\n s[0] = t.Ue(); else if (n > 0 && r < 0) \n // `notInValue` is in the middle of the range\n s.push(i), s.push(i.Ue()); else if (r > 0) \n // `notInValue` (and all following values) are out of the range\n break;\n }\n s.push(e);\n const i = [];\n for (let t = 0; t < s.length; t += 2) {\n // If we encounter two bounds that will create an unmatchable key range,\n // then we return an empty set of key ranges.\n if (this.pn(s[t], s[t + 1])) return [];\n const e = [ s[t].indexId, this.uid, s[t].arrayValue, s[t].directionalValue, Or, [] ], n = [ s[t + 1].indexId, this.uid, s[t + 1].arrayValue, s[t + 1].directionalValue, Or, [] ];\n i.push(IDBKeyRange.bound(e, n));\n }\n return i;\n }\n pn(t, e) {\n // If lower bound is greater than the upper bound, then the key\n // range can never be matched.\n return Tr(t, e) > 0;\n }\n getMinOffsetFromCollectionGroup(t, e) {\n return this.getFieldIndexes(t, e).next(qr);\n }\n getMinOffset(t, e) {\n return At.mapArray(this.Ze(e), (e => this.tn(t, e).next((t => t || O())))).next(qr);\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the collectionParents\n * document store.\n */ function Fr(t) {\n return Gi(t, \"collectionParents\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index entry object store.\n */ function $r(t) {\n return Gi(t, \"indexEntries\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index configuration object store.\n */ function Br(t) {\n return Gi(t, \"indexConfiguration\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the index state object store.\n */ function Lr(t) {\n return Gi(t, \"indexState\");\n}\n\nfunction qr(t) {\n M(0 !== t.length);\n let e = t[0].indexState.offset, n = e.largestBatchId;\n for (let s = 1; s < t.length; s++) {\n const i = t[s].indexState.offset;\n pt(i, e) < 0 && (e = i), n < i.largestBatchId && (n = i.largestBatchId);\n }\n return new yt(e.readTime, e.documentKey, n);\n}\n\n/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Ur = {\n didRun: !1,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nclass Kr {\n constructor(\n // When we attempt to collect, we will only do so if the cache size is greater than this\n // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped.\n t, \n // The percentage of sequence numbers that we will attempt to collect\n e, \n // A cap on the total number of sequence numbers that will be collected. This prevents\n // us from collecting a huge number of sequence numbers if the cache has grown very large.\n n) {\n this.cacheSizeCollectionThreshold = t, this.percentileToCollect = e, this.maximumSequenceNumbersToCollect = n;\n }\n static withCacheSize(t) {\n return new Kr(t, Kr.DEFAULT_COLLECTION_PERCENTILE, Kr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nfunction Gr(t, e, n) {\n const s = t.store(\"mutations\"), i = t.store(\"documentMutations\"), r = [], o = IDBKeyRange.only(n.batchId);\n let u = 0;\n const c = s.Z({\n range: o\n }, ((t, e, n) => (u++, n.delete())));\n r.push(c.next((() => {\n M(1 === u);\n })));\n const a = [];\n for (const t of n.mutations) {\n const s = Ei(e, t.key.path, n.batchId);\n r.push(i.delete(s)), a.push(t.key);\n }\n return At.waitFor(r).next((() => a));\n}\n\n/**\n * Returns an approximate size for the given document.\n */ function Qr(t) {\n if (!t) return 0;\n let e;\n if (t.document) e = t.document; else if (t.unknownDocument) e = t.unknownDocument; else {\n if (!t.noDocument) throw O();\n e = t.noDocument;\n }\n return JSON.stringify(e).length;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** A mutation queue for a specific user, backed by IndexedDB. */ Kr.DEFAULT_COLLECTION_PERCENTILE = 10, \nKr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, Kr.DEFAULT = new Kr(41943040, Kr.DEFAULT_COLLECTION_PERCENTILE, Kr.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), \nKr.DISABLED = new Kr(-1, 0, 0);\n\nclass jr {\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n t, e, n, s) {\n this.userId = t, this.yt = e, this.indexManager = n, this.referenceDelegate = s, \n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n this.In = {};\n }\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */ static re(t, e, n, s) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n M(\"\" !== t.uid);\n const i = t.isAuthenticated() ? t.uid : \"\";\n return new jr(i, e, n, s);\n }\n checkEmpty(t) {\n let e = !0;\n const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return zr(t).Z({\n index: \"userMutationsIndex\",\n range: n\n }, ((t, n, s) => {\n e = !1, s.done();\n })).next((() => e));\n }\n addMutationBatch(t, e, n, s) {\n const i = Hr(t), r = zr(t);\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return r.add({}).next((o => {\n M(\"number\" == typeof o);\n const u = new Qi(o, e, n, s), c = function(t, e, n) {\n const s = n.baseMutations.map((e => ti(t.ie, e))), i = n.mutations.map((e => ti(t.ie, e)));\n return {\n userId: e,\n batchId: n.batchId,\n localWriteTimeMs: n.localWriteTime.toMillis(),\n baseMutations: s,\n mutations: i\n };\n }(this.yt, this.userId, u), a = [];\n let h = new We(((t, e) => Z(t.canonicalString(), e.canonicalString())));\n for (const t of s) {\n const e = Ei(this.userId, t.key.path, o);\n h = h.add(t.key.path.popLast()), a.push(r.put(c)), a.push(i.put(e, Ai));\n }\n return h.forEach((e => {\n a.push(this.indexManager.addToCollectionParentIndex(t, e));\n })), t.addOnCommittedListener((() => {\n this.In[o] = u.keys();\n })), At.waitFor(a).next((() => u));\n }));\n }\n lookupMutationBatch(t, e) {\n return zr(t).get(e).next((t => t ? (M(t.userId === this.userId), er(this.yt, t)) : null));\n }\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n Tn(t, e) {\n return this.In[e] ? At.resolve(this.In[e]) : this.lookupMutationBatch(t, e).next((t => {\n if (t) {\n const n = t.keys();\n return this.In[e] = n, n;\n }\n return null;\n }));\n }\n getNextMutationBatchAfterBatchId(t, e) {\n const n = e + 1, s = IDBKeyRange.lowerBound([ this.userId, n ]);\n let i = null;\n return zr(t).Z({\n index: \"userMutationsIndex\",\n range: s\n }, ((t, e, s) => {\n e.userId === this.userId && (M(e.batchId >= n), i = er(this.yt, e)), s.done();\n })).next((() => i));\n }\n getHighestUnacknowledgedBatchId(t) {\n const e = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]);\n let n = -1;\n return zr(t).Z({\n index: \"userMutationsIndex\",\n range: e,\n reverse: !0\n }, ((t, e, s) => {\n n = e.batchId, s.done();\n })).next((() => n));\n }\n getAllMutationBatches(t) {\n const e = IDBKeyRange.bound([ this.userId, -1 ], [ this.userId, Number.POSITIVE_INFINITY ]);\n return zr(t).W(\"userMutationsIndex\", e).next((t => t.map((t => er(this.yt, t)))));\n }\n getAllMutationBatchesAffectingDocumentKey(t, e) {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const n = Ti(this.userId, e.path), s = IDBKeyRange.lowerBound(n), i = [];\n return Hr(t).Z({\n range: s\n }, ((n, s, r) => {\n const [o, u, c] = n, a = pi(u);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n if (o === this.userId && e.path.isEqual(a)) \n // Look up the mutation batch in the store.\n return zr(t).get(c).next((t => {\n if (!t) throw O();\n M(t.userId === this.userId), i.push(er(this.yt, t));\n }));\n r.done();\n })).next((() => i));\n }\n getAllMutationBatchesAffectingDocumentKeys(t, e) {\n let n = new We(Z);\n const s = [];\n return e.forEach((e => {\n const i = Ti(this.userId, e.path), r = IDBKeyRange.lowerBound(i), o = Hr(t).Z({\n range: r\n }, ((t, s, i) => {\n const [r, o, u] = t, c = pi(o);\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n r === this.userId && e.path.isEqual(c) ? n = n.add(u) : i.done();\n }));\n s.push(o);\n })), At.waitFor(s).next((() => this.En(t, n)));\n }\n getAllMutationBatchesAffectingQuery(t, e) {\n const n = e.path, s = n.length + 1, i = Ti(this.userId, n), r = IDBKeyRange.lowerBound(i);\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let o = new We(Z);\n return Hr(t).Z({\n range: r\n }, ((t, e, i) => {\n const [r, u, c] = t, a = pi(u);\n r === this.userId && n.isPrefixOf(a) ? \n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n a.length === s && (o = o.add(c)) : i.done();\n })).next((() => this.En(t, o)));\n }\n En(t, e) {\n const n = [], s = [];\n // TODO(rockwood): Implement this using iterate.\n return e.forEach((e => {\n s.push(zr(t).get(e).next((t => {\n if (null === t) throw O();\n M(t.userId === this.userId), n.push(er(this.yt, t));\n })));\n })), At.waitFor(s).next((() => n));\n }\n removeMutationBatch(t, e) {\n return Gr(t.se, this.userId, e).next((n => (t.addOnCommittedListener((() => {\n this.An(e.batchId);\n })), At.forEach(n, (e => this.referenceDelegate.markPotentiallyOrphaned(t, e))))));\n }\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n An(t) {\n delete this.In[t];\n }\n performConsistencyCheck(t) {\n return this.checkEmpty(t).next((e => {\n if (!e) return At.resolve();\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const n = IDBKeyRange.lowerBound([ this.userId ]);\n const s = [];\n return Hr(t).Z({\n range: n\n }, ((t, e, n) => {\n if (t[0] === this.userId) {\n const e = pi(t[1]);\n s.push(e);\n } else n.done();\n })).next((() => {\n M(0 === s.length);\n }));\n }));\n }\n containsKey(t, e) {\n return Wr(t, this.userId, e);\n }\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n Rn(t) {\n return Jr(t).get(this.userId).next((t => t || {\n userId: this.userId,\n lastAcknowledgedBatchId: -1,\n lastStreamToken: \"\"\n }));\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */ function Wr(t, e, n) {\n const s = Ti(e, n.path), i = s[1], r = IDBKeyRange.lowerBound(s);\n let o = !1;\n return Hr(t).Z({\n range: r,\n X: !0\n }, ((t, n, s) => {\n const [r, u, /*batchID*/ c] = t;\n r === e && u === i && (o = !0), s.done();\n })).next((() => o));\n}\n\n/** Returns true if any mutation queue contains the given document. */\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction zr(t) {\n return Gi(t, \"mutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function Hr(t) {\n return Gi(t, \"documentMutations\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */ function Jr(t) {\n return Gi(t, \"mutationQueues\");\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Offset to ensure non-overlapping target ids. */\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nclass Yr {\n constructor(t) {\n this.bn = t;\n }\n next() {\n return this.bn += 2, this.bn;\n }\n static Pn() {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new Yr(0);\n }\n static vn() {\n // Sync engine assigns target IDs for limbo document detection.\n return new Yr(-1);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Xr {\n constructor(t, e) {\n this.referenceDelegate = t, this.yt = e;\n }\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n allocateTargetId(t) {\n return this.Vn(t).next((e => {\n const n = new Yr(e.highestTargetId);\n return e.highestTargetId = n.next(), this.Sn(t, e).next((() => e.highestTargetId));\n }));\n }\n getLastRemoteSnapshotVersion(t) {\n return this.Vn(t).next((t => st.fromTimestamp(new nt(t.lastRemoteSnapshotVersion.seconds, t.lastRemoteSnapshotVersion.nanoseconds))));\n }\n getHighestSequenceNumber(t) {\n return this.Vn(t).next((t => t.highestListenSequenceNumber));\n }\n setTargetsMetadata(t, e, n) {\n return this.Vn(t).next((s => (s.highestListenSequenceNumber = e, n && (s.lastRemoteSnapshotVersion = n.toTimestamp()), \n e > s.highestListenSequenceNumber && (s.highestListenSequenceNumber = e), this.Sn(t, s))));\n }\n addTargetData(t, e) {\n return this.Dn(t, e).next((() => this.Vn(t).next((n => (n.targetCount += 1, this.Cn(e, n), \n this.Sn(t, n))))));\n }\n updateTargetData(t, e) {\n return this.Dn(t, e);\n }\n removeTargetData(t, e) {\n return this.removeMatchingKeysForTargetId(t, e.targetId).next((() => Zr(t).delete(e.targetId))).next((() => this.Vn(t))).next((e => (M(e.targetCount > 0), \n e.targetCount -= 1, this.Sn(t, e))));\n }\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */ removeTargets(t, e, n) {\n let s = 0;\n const i = [];\n return Zr(t).Z(((r, o) => {\n const u = nr(o);\n u.sequenceNumber <= e && null === n.get(u.targetId) && (s++, i.push(this.removeTargetData(t, u)));\n })).next((() => At.waitFor(i))).next((() => s));\n }\n /**\n * Call provided function with each `TargetData` that we have cached.\n */ forEachTarget(t, e) {\n return Zr(t).Z(((t, n) => {\n const s = nr(n);\n e(s);\n }));\n }\n Vn(t) {\n return to(t).get(\"targetGlobalKey\").next((t => (M(null !== t), t)));\n }\n Sn(t, e) {\n return to(t).put(\"targetGlobalKey\", e);\n }\n Dn(t, e) {\n return Zr(t).put(sr(this.yt, e));\n }\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */ Cn(t, e) {\n let n = !1;\n return t.targetId > e.highestTargetId && (e.highestTargetId = t.targetId, n = !0), \n t.sequenceNumber > e.highestListenSequenceNumber && (e.highestListenSequenceNumber = t.sequenceNumber, \n n = !0), n;\n }\n getTargetCount(t) {\n return this.Vn(t).next((t => t.targetCount));\n }\n getTargetData(t, e) {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const n = nn(e), s = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]);\n let i = null;\n return Zr(t).Z({\n range: s,\n index: \"queryTargetsIndex\"\n }, ((t, n, s) => {\n const r = nr(n);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n sn(e, r.target) && (i = r, s.done());\n })).next((() => i));\n }\n addMatchingKeys(t, e, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const s = [], i = eo(t);\n return e.forEach((e => {\n const r = mi(e.path);\n s.push(i.put({\n targetId: n,\n path: r\n })), s.push(this.referenceDelegate.addReference(t, n, e));\n })), At.waitFor(s);\n }\n removeMatchingKeys(t, e, n) {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const s = eo(t);\n return At.forEach(e, (e => {\n const i = mi(e.path);\n return At.waitFor([ s.delete([ n, i ]), this.referenceDelegate.removeReference(t, n, e) ]);\n }));\n }\n removeMatchingKeysForTargetId(t, e) {\n const n = eo(t), s = IDBKeyRange.bound([ e ], [ e + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n return n.delete(s);\n }\n getMatchingKeysForTargetId(t, e) {\n const n = IDBKeyRange.bound([ e ], [ e + 1 ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0), s = eo(t);\n let i = Es();\n return s.Z({\n range: n,\n X: !0\n }, ((t, e, n) => {\n const s = pi(t[1]), r = new ct(s);\n i = i.add(r);\n })).next((() => i));\n }\n containsKey(t, e) {\n const n = mi(e.path), s = IDBKeyRange.bound([ n ], [ et(n) ], \n /*lowerOpen=*/ !1, \n /*upperOpen=*/ !0);\n let i = 0;\n return eo(t).Z({\n index: \"documentTargetsIndex\",\n X: !0,\n range: s\n }, (([t, e], n, s) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n 0 !== t && (i++, s.done());\n })).next((() => i > 0));\n }\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n ne(t, e) {\n return Zr(t).get(e).next((t => t ? nr(t) : null));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */ function Zr(t) {\n return Gi(t, \"targets\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */ function to(t) {\n return Gi(t, \"targetGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */ function eo(t) {\n return Gi(t, \"targetDocuments\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function no([t, e], [n, s]) {\n const i = Z(t, n);\n return 0 === i ? Z(e, s) : i;\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */ class so {\n constructor(t) {\n this.xn = t, this.buffer = new We(no), this.Nn = 0;\n }\n kn() {\n return ++this.Nn;\n }\n On(t) {\n const e = [ t, this.kn() ];\n if (this.buffer.size < this.xn) this.buffer = this.buffer.add(e); else {\n const t = this.buffer.last();\n no(e, t) < 0 && (this.buffer = this.buffer.delete(t).add(e));\n }\n }\n get maxValue() {\n // Guaranteed to be non-empty. If we decide we are not collecting any\n // sequence numbers, nthSequenceNumber below short-circuits. If we have\n // decided that we are collecting n sequence numbers, it's because n is some\n // percentage of the existing sequence numbers. That means we should never\n // be in a situation where we are collecting sequence numbers but don't\n // actually have any.\n return this.buffer.last()[0];\n }\n}\n\n/**\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\n * whether or not GC is enabled, as well as which delay to use before the next run.\n */ class io {\n constructor(t, e, n) {\n this.garbageCollector = t, this.asyncQueue = e, this.localStore = n, this.Mn = null;\n }\n start() {\n -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Fn(6e4);\n }\n stop() {\n this.Mn && (this.Mn.cancel(), this.Mn = null);\n }\n get started() {\n return null !== this.Mn;\n }\n Fn(t) {\n C(\"LruGarbageCollector\", `Garbage collection scheduled in ${t}ms`), this.Mn = this.asyncQueue.enqueueAfterDelay(\"lru_garbage_collection\" /* TimerId.LruGarbageCollection */ , t, (async () => {\n this.Mn = null;\n try {\n await this.localStore.collectGarbage(this.garbageCollector);\n } catch (t) {\n Vt(t) ? C(\"LruGarbageCollector\", \"Ignoring IndexedDB error during garbage collection: \", t) : await Et(t);\n }\n await this.Fn(3e5);\n }));\n }\n}\n\n/** Implements the steps for LRU garbage collection. */ class ro {\n constructor(t, e) {\n this.$n = t, this.params = e;\n }\n calculateTargetCount(t, e) {\n return this.$n.Bn(t).next((t => Math.floor(e / 100 * t)));\n }\n nthSequenceNumber(t, e) {\n if (0 === e) return At.resolve(Ot.at);\n const n = new so(e);\n return this.$n.forEachTarget(t, (t => n.On(t.sequenceNumber))).next((() => this.$n.Ln(t, (t => n.On(t))))).next((() => n.maxValue));\n }\n removeTargets(t, e, n) {\n return this.$n.removeTargets(t, e, n);\n }\n removeOrphanedDocuments(t, e) {\n return this.$n.removeOrphanedDocuments(t, e);\n }\n collect(t, e) {\n return -1 === this.params.cacheSizeCollectionThreshold ? (C(\"LruGarbageCollector\", \"Garbage collection skipped; disabled\"), \n At.resolve(Ur)) : this.getCacheSize(t).next((n => n < this.params.cacheSizeCollectionThreshold ? (C(\"LruGarbageCollector\", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), \n Ur) : this.qn(t, e)));\n }\n getCacheSize(t) {\n return this.$n.getCacheSize(t);\n }\n qn(t, e) {\n let n, s, i, r, o, c, a;\n const h = Date.now();\n return this.calculateTargetCount(t, this.params.percentileToCollect).next((e => (\n // Cap at the configured max\n e > this.params.maximumSequenceNumbersToCollect ? (C(\"LruGarbageCollector\", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${e}`), \n s = this.params.maximumSequenceNumbersToCollect) : s = e, r = Date.now(), this.nthSequenceNumber(t, s)))).next((s => (n = s, \n o = Date.now(), this.removeTargets(t, n, e)))).next((e => (i = e, c = Date.now(), \n this.removeOrphanedDocuments(t, n)))).next((t => {\n if (a = Date.now(), S() <= u.DEBUG) {\n C(\"LruGarbageCollector\", `LRU Garbage Collection\\n\\tCounted targets in ${r - h}ms\\n\\tDetermined least recently used ${s} in ` + (o - r) + \"ms\\n\" + `\\tRemoved ${i} targets in ` + (c - o) + \"ms\\n\" + `\\tRemoved ${t} documents in ` + (a - c) + \"ms\\n\" + `Total Duration: ${a - h}ms`);\n }\n return At.resolve({\n didRun: !0,\n sequenceNumbersCollected: s,\n targetsRemoved: i,\n documentsRemoved: t\n });\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Provides LRU functionality for IndexedDB persistence. */\nclass oo {\n constructor(t, e) {\n this.db = t, this.garbageCollector = function(t, e) {\n return new ro(t, e);\n }(this, e);\n }\n Bn(t) {\n const e = this.Un(t);\n return this.db.getTargetCache().getTargetCount(t).next((t => e.next((e => t + e))));\n }\n Un(t) {\n let e = 0;\n return this.Ln(t, (t => {\n e++;\n })).next((() => e));\n }\n forEachTarget(t, e) {\n return this.db.getTargetCache().forEachTarget(t, e);\n }\n Ln(t, e) {\n return this.Kn(t, ((t, n) => e(n)));\n }\n addReference(t, e, n) {\n return uo(t, n);\n }\n removeReference(t, e, n) {\n return uo(t, n);\n }\n removeTargets(t, e, n) {\n return this.db.getTargetCache().removeTargets(t, e, n);\n }\n markPotentiallyOrphaned(t, e) {\n return uo(t, e);\n }\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */ Gn(t, e) {\n return function(t, e) {\n let n = !1;\n return Jr(t).tt((s => Wr(t, s, e).next((t => (t && (n = !0), At.resolve(!t)))))).next((() => n));\n }(t, e);\n }\n removeOrphanedDocuments(t, e) {\n const n = this.db.getRemoteDocumentCache().newChangeBuffer(), s = [];\n let i = 0;\n return this.Kn(t, ((r, o) => {\n if (o <= e) {\n const e = this.Gn(t, r).next((e => {\n if (!e) \n // Our size accounting requires us to read all documents before\n // removing them.\n return i++, n.getEntry(t, r).next((() => (n.removeEntry(r, st.min()), eo(t).delete([ 0, mi(r.path) ]))));\n }));\n s.push(e);\n }\n })).next((() => At.waitFor(s))).next((() => n.apply(t))).next((() => i));\n }\n removeTarget(t, e) {\n const n = e.withSequenceNumber(t.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(t, n);\n }\n updateLimboDocument(t, e) {\n return uo(t, e);\n }\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */ Kn(t, e) {\n const n = eo(t);\n let s, i = Ot.at;\n return n.Z({\n index: \"documentTargetsIndex\"\n }, (([t, n], {path: r, sequenceNumber: o}) => {\n 0 === t ? (\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n i !== Ot.at && e(new ct(pi(s)), i), \n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n i = o, s = r) : \n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n i = Ot.at;\n })).next((() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n i !== Ot.at && e(new ct(pi(s)), i);\n }));\n }\n getCacheSize(t) {\n return this.db.getRemoteDocumentCache().getSize(t);\n }\n}\n\nfunction uo(t, e) {\n return eo(t).put(\n /**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\n function(t, e) {\n return {\n targetId: 0,\n path: mi(t.path),\n sequenceNumber: e\n };\n }(e, t.currentSequenceNumber));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */ class co {\n constructor() {\n // A mapping of document key to the new cache entry that should be written.\n this.changes = new ls((t => t.toString()), ((t, e) => t.isEqual(e))), this.changesApplied = !1;\n }\n /**\n * Buffers a `RemoteDocumentCache.addEntry()` call.\n *\n * You can only modify documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ addEntry(t) {\n this.assertNotApplied(), this.changes.set(t.key, t);\n }\n /**\n * Buffers a `RemoteDocumentCache.removeEntry()` call.\n *\n * You can only remove documents that have already been retrieved via\n * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`).\n */ removeEntry(t, e) {\n this.assertNotApplied(), this.changes.set(t, Ze.newInvalidDocument(t).setReadTime(e));\n }\n /**\n * Looks up an entry in the cache. The buffered changes will first be checked,\n * and if no buffered change applies, this will forward to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document or an invalid document if we have nothing\n * cached.\n */ getEntry(t, e) {\n this.assertNotApplied();\n const n = this.changes.get(e);\n return void 0 !== n ? At.resolve(n) : this.getFromCache(t, e);\n }\n /**\n * Looks up several entries in the cache, forwarding to\n * `RemoteDocumentCache.getEntry()`.\n *\n * @param transaction - The transaction in which to perform any persistence\n * operations.\n * @param documentKeys - The keys of the entries to look up.\n * @returns A map of cached documents, indexed by key. If an entry cannot be\n * found, the corresponding key will be mapped to an invalid document.\n */ getEntries(t, e) {\n return this.getAllFromCache(t, e);\n }\n /**\n * Applies buffered changes to the underlying RemoteDocumentCache, using\n * the provided transaction.\n */ apply(t) {\n return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(t);\n }\n /** Helper to assert this.changes is not null */ assertNotApplied() {}\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */ class ao {\n constructor(t) {\n this.yt = t;\n }\n setIndexManager(t) {\n this.indexManager = t;\n }\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ addEntry(t, e, n) {\n return _o(t).put(n);\n }\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */ removeEntry(t, e, n) {\n return _o(t).delete(\n /**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\n function(t, e) {\n const n = t.path.toArray();\n return [ \n /* prefix path */ n.slice(0, n.length - 2), \n /* collection id */ n[n.length - 2], Xi(e), \n /* document id */ n[n.length - 1] ];\n }\n /**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */ (e, n));\n }\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */ updateMetadata(t, e) {\n return this.getMetadata(t).next((n => (n.byteSize += e, this.Qn(t, n))));\n }\n getEntry(t, e) {\n let n = Ze.newInvalidDocument(e);\n return _o(t).Z({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(wo(e))\n }, ((t, s) => {\n n = this.jn(e, s);\n })).next((() => n));\n }\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */ Wn(t, e) {\n let n = {\n size: 0,\n document: Ze.newInvalidDocument(e)\n };\n return _o(t).Z({\n index: \"documentKeyIndex\",\n range: IDBKeyRange.only(wo(e))\n }, ((t, s) => {\n n = {\n document: this.jn(e, s),\n size: Qr(s)\n };\n })).next((() => n));\n }\n getEntries(t, e) {\n let n = ds();\n return this.zn(t, e, ((t, e) => {\n const s = this.jn(t, e);\n n = n.insert(t, s);\n })).next((() => n));\n }\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */ Hn(t, e) {\n let n = ds(), s = new Ge(ct.comparator);\n return this.zn(t, e, ((t, e) => {\n const i = this.jn(t, e);\n n = n.insert(t, i), s = s.insert(t, Qr(e));\n })).next((() => ({\n documents: n,\n Jn: s\n })));\n }\n zn(t, e, n) {\n if (e.isEmpty()) return At.resolve();\n let s = new We(go);\n e.forEach((t => s = s.add(t)));\n const i = IDBKeyRange.bound(wo(s.first()), wo(s.last())), r = s.getIterator();\n let o = r.getNext();\n return _o(t).Z({\n index: \"documentKeyIndex\",\n range: i\n }, ((t, e, s) => {\n const i = ct.fromSegments([ ...e.prefixPath, e.collectionGroup, e.documentId ]);\n // Go through keys not found in cache.\n for (;o && go(o, i) < 0; ) n(o, null), o = r.getNext();\n o && o.isEqual(i) && (\n // Key found in cache.\n n(o, e), o = r.hasNext() ? r.getNext() : null), \n // Skip to the next key (if there is one).\n o ? s.j(wo(o)) : s.done();\n })).next((() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n for (;o; ) n(o, null), o = r.hasNext() ? r.getNext() : null;\n }));\n }\n getAllFromCollection(t, e, n) {\n const s = [ e.popLast().toArray(), e.lastSegment(), Xi(n.readTime), n.documentKey.path.isEmpty() ? \"\" : n.documentKey.path.lastSegment() ], i = [ e.popLast().toArray(), e.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], \"\" ];\n return _o(t).W(IDBKeyRange.bound(s, i, !0)).next((t => {\n let e = ds();\n for (const n of t) {\n const t = this.jn(ct.fromSegments(n.prefixPath.concat(n.collectionGroup, n.documentId)), n);\n e = e.insert(t.key, t);\n }\n return e;\n }));\n }\n getAllFromCollectionGroup(t, e, n, s) {\n let i = ds();\n const r = mo(e, n), o = mo(e, yt.max());\n return _o(t).Z({\n index: \"collectionGroupIndex\",\n range: IDBKeyRange.bound(r, o, !0)\n }, ((t, e, n) => {\n const r = this.jn(ct.fromSegments(e.prefixPath.concat(e.collectionGroup, e.documentId)), e);\n i = i.insert(r.key, r), i.size === s && n.done();\n })).next((() => i));\n }\n newChangeBuffer(t) {\n return new lo(this, !!t && t.trackRemovals);\n }\n getSize(t) {\n return this.getMetadata(t).next((t => t.byteSize));\n }\n getMetadata(t) {\n return fo(t).get(\"remoteDocumentGlobalKey\").next((t => (M(!!t), t)));\n }\n Qn(t, e) {\n return fo(t).put(\"remoteDocumentGlobalKey\", e);\n }\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */ jn(t, e) {\n if (e) {\n const t = Ji(this.yt, e);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n if (!(t.isNoDocument() && t.version.isEqual(st.min()))) return t;\n }\n return Ze.newInvalidDocument(t);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */ function ho(t) {\n return new ao(t);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */ class lo extends co {\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(t, e) {\n super(), this.Yn = t, this.trackRemovals = e, \n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n this.Xn = new ls((t => t.toString()), ((t, e) => t.isEqual(e)));\n }\n applyChanges(t) {\n const e = [];\n let n = 0, s = new We(((t, e) => Z(t.canonicalString(), e.canonicalString())));\n return this.changes.forEach(((i, r) => {\n const o = this.Xn.get(i);\n if (e.push(this.Yn.removeEntry(t, i, o.readTime)), r.isValidDocument()) {\n const u = Yi(this.Yn.yt, r);\n s = s.add(i.path.popLast());\n const c = Qr(u);\n n += c - o.size, e.push(this.Yn.addEntry(t, i, u));\n } else if (n -= o.size, this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const n = Yi(this.Yn.yt, r.convertToNoDocument(st.min()));\n e.push(this.Yn.addEntry(t, i, n));\n }\n })), s.forEach((n => {\n e.push(this.Yn.indexManager.addToCollectionParentIndex(t, n));\n })), e.push(this.Yn.updateMetadata(t, n)), At.waitFor(e);\n }\n getFromCache(t, e) {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.Yn.Wn(t, e).next((t => (this.Xn.set(e, {\n size: t.size,\n readTime: t.document.readTime\n }), t.document)));\n }\n getAllFromCache(t, e) {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.Yn.Hn(t, e).next((({documents: t, Jn: e}) => (\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n e.forEach(((e, n) => {\n this.Xn.set(e, {\n size: n,\n readTime: t.get(e).readTime\n });\n })), t)));\n }\n}\n\nfunction fo(t) {\n return Gi(t, \"remoteDocumentGlobal\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */ function _o(t) {\n return Gi(t, \"remoteDocumentsV14\");\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */ function wo(t) {\n const e = t.path.toArray();\n return [ \n /* prefix path */ e.slice(0, e.length - 2), \n /* collection id */ e[e.length - 2], \n /* document id */ e[e.length - 1] ];\n}\n\nfunction mo(t, e) {\n const n = e.documentKey.path.toArray();\n return [ \n /* collection id */ t, Xi(e.readTime), \n /* prefix path */ n.slice(0, n.length - 2), \n /* document id */ n.length > 0 ? n[n.length - 1] : \"\" ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */ function go(t, e) {\n const n = t.path.toArray(), s = e.path.toArray();\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let i = 0;\n for (let t = 0; t < n.length - 2 && t < s.length - 2; ++t) if (i = Z(n[t], s[t]), \n i) return i;\n return i = Z(n.length, s.length), i || (i = Z(n[n.length - 2], s[s.length - 2]), \n i || Z(n[n.length - 1], s[s.length - 1]));\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n */\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nclass yo {\n constructor(t, \n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n e) {\n this.overlayedDocument = t, this.mutatedFields = e;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */ class po {\n constructor(t, e, n, s) {\n this.remoteDocumentCache = t, this.mutationQueue = e, this.documentOverlayCache = n, \n this.indexManager = s;\n }\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */ getDocument(t, e) {\n let n = null;\n return this.documentOverlayCache.getOverlay(t, e).next((s => (n = s, this.remoteDocumentCache.getEntry(t, e)))).next((t => (null !== n && Jn(n.mutation, t, Je.empty(), nt.now()), \n t)));\n }\n /**\n * Gets the local view of the documents identified by `keys`.\n *\n * If we don't have cached state for a document in `keys`, a NoDocument will\n * be stored for that key in the resulting set.\n */ getDocuments(t, e) {\n return this.remoteDocumentCache.getEntries(t, e).next((e => this.getLocalViewOfDocuments(t, e, Es()).next((() => e))));\n }\n /**\n * Similar to `getDocuments`, but creates the local view from the given\n * `baseDocs` without retrieving documents from the local store.\n *\n * @param transaction - The transaction this operation is scoped to.\n * @param docs - The documents to apply local mutations to get the local views.\n * @param existenceStateChanged - The set of document keys whose existence state\n * is changed. This is useful to determine if some documents overlay needs\n * to be recalculated.\n */ getLocalViewOfDocuments(t, e, n = Es()) {\n const s = gs();\n return this.populateOverlays(t, s, e).next((() => this.computeViews(t, e, s, n).next((t => {\n let e = ws();\n return t.forEach(((t, n) => {\n e = e.insert(t, n.overlayedDocument);\n })), e;\n }))));\n }\n /**\n * Gets the overlayed documents for the given document map, which will include\n * the local view of those documents and a `FieldMask` indicating which fields\n * are mutated locally, `null` if overlay is a Set or Delete mutation.\n */ getOverlayedDocuments(t, e) {\n const n = gs();\n return this.populateOverlays(t, n, e).next((() => this.computeViews(t, e, n, Es())));\n }\n /**\n * Fetches the overlays for {@code docs} and adds them to provided overlay map\n * if the map does not already contain an entry for the given document key.\n */ populateOverlays(t, e, n) {\n const s = [];\n return n.forEach((t => {\n e.has(t) || s.push(t);\n })), this.documentOverlayCache.getOverlays(t, s).next((t => {\n t.forEach(((t, n) => {\n e.set(t, n);\n }));\n }));\n }\n /**\n * Computes the local view for the given documents.\n *\n * @param docs - The documents to compute views for. It also has the base\n * version of the documents.\n * @param overlays - The overlays that need to be applied to the given base\n * version of the documents.\n * @param existenceStateChanged - A set of documents whose existence states\n * might have changed. This is used to determine if we need to re-calculate\n * overlays from mutation queues.\n * @return A map represents the local documents view.\n */ computeViews(t, e, n, s) {\n let i = ds();\n const r = ps(), o = ps();\n return e.forEach(((t, e) => {\n const o = n.get(e.key);\n // Recalculate an overlay if the document's existence state changed due to\n // a remote event *and* the overlay is a PatchMutation. This is because\n // document existence state can change if some patch mutation's\n // preconditions are met.\n // NOTE: we recalculate when `overlay` is undefined as well, because there\n // might be a patch mutation whose precondition does not match before the\n // change (hence overlay is undefined), but would now match.\n s.has(e.key) && (void 0 === o || o.mutation instanceof ts) ? i = i.insert(e.key, e) : void 0 !== o ? (r.set(e.key, o.mutation.getFieldMask()), \n Jn(o.mutation, e, o.mutation.getFieldMask(), nt.now())) : \n // no overlay exists\n // Using EMPTY to indicate there is no overlay for the document.\n r.set(e.key, Je.empty());\n })), this.recalculateAndSaveOverlays(t, i).next((t => (t.forEach(((t, e) => r.set(t, e))), \n e.forEach(((t, e) => {\n var n;\n return o.set(t, new yo(e, null !== (n = r.get(t)) && void 0 !== n ? n : null));\n })), o)));\n }\n recalculateAndSaveOverlays(t, e) {\n const n = ps();\n // A reverse lookup map from batch id to the documents within that batch.\n let s = new Ge(((t, e) => t - e)), i = Es();\n return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(t, e).next((t => {\n for (const i of t) i.keys().forEach((t => {\n const r = e.get(t);\n if (null === r) return;\n let o = n.get(t) || Je.empty();\n o = i.applyToLocalView(r, o), n.set(t, o);\n const u = (s.get(i.batchId) || Es()).add(t);\n s = s.insert(i.batchId, u);\n }));\n })).next((() => {\n const r = [], o = s.getReverseIterator();\n // Iterate in descending order of batch IDs, and skip documents that are\n // already saved.\n for (;o.hasNext(); ) {\n const s = o.getNext(), u = s.key, c = s.value, a = ys();\n c.forEach((t => {\n if (!i.has(t)) {\n const s = zn(e.get(t), n.get(t));\n null !== s && a.set(t, s), i = i.add(t);\n }\n })), r.push(this.documentOverlayCache.saveOverlays(t, u, a));\n }\n return At.waitFor(r);\n })).next((() => n));\n }\n /**\n * Recalculates overlays by reading the documents from remote document cache\n * first, and saves them after they are calculated.\n */ recalculateAndSaveOverlaysForDocumentKeys(t, e) {\n return this.remoteDocumentCache.getEntries(t, e).next((e => this.recalculateAndSaveOverlays(t, e)));\n }\n /**\n * Performs a query against the local view of all documents.\n *\n * @param transaction - The persistence transaction.\n * @param query - The query to match documents against.\n * @param offset - Read time and key to start scanning by (exclusive).\n */ getDocumentsMatchingQuery(t, e, n) {\n /**\n * Returns whether the query matches a single document by path (rather than a\n * collection).\n */\n return function(t) {\n return ct.isDocumentKey(t.path) && null === t.collectionGroup && 0 === t.filters.length;\n }(e) ? this.getDocumentsMatchingDocumentQuery(t, e.path) : wn(e) ? this.getDocumentsMatchingCollectionGroupQuery(t, e, n) : this.getDocumentsMatchingCollectionQuery(t, e, n);\n }\n /**\n * Given a collection group, returns the next documents that follow the provided offset, along\n * with an updated batch ID.\n *\n * <p>The documents returned by this method are ordered by remote version from the provided\n * offset. If there are no more remote documents after the provided offset, documents with\n * mutations in order of batch id from the offset are returned. Since all documents in a batch are\n * returned together, the total number of documents returned can exceed {@code count}.\n *\n * @param transaction\n * @param collectionGroup The collection group for the documents.\n * @param offset The offset to index into.\n * @param count The number of documents to return\n * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id.\n */ getNextDocuments(t, e, n, s) {\n return this.remoteDocumentCache.getAllFromCollectionGroup(t, e, n, s).next((i => {\n const r = s - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(t, e, n.largestBatchId, s - i.size) : At.resolve(gs());\n // The callsite will use the largest batch ID together with the latest read time to create\n // a new index offset. Since we only process batch IDs if all remote documents have been read,\n // no overlay will increase the overall read time. This is why we only need to special case\n // the batch id.\n let o = -1, u = i;\n return r.next((e => At.forEach(e, ((e, n) => (o < n.largestBatchId && (o = n.largestBatchId), \n i.get(e) ? At.resolve() : this.remoteDocumentCache.getEntry(t, e).next((t => {\n u = u.insert(e, t);\n }))))).next((() => this.populateOverlays(t, e, i))).next((() => this.computeViews(t, u, e, Es()))).next((t => ({\n batchId: o,\n changes: ms(t)\n })))));\n }));\n }\n getDocumentsMatchingDocumentQuery(t, e) {\n // Just do a simple document lookup.\n return this.getDocument(t, new ct(e)).next((t => {\n let e = ws();\n return t.isFoundDocument() && (e = e.insert(t.key, t)), e;\n }));\n }\n getDocumentsMatchingCollectionGroupQuery(t, e, n) {\n const s = e.collectionGroup;\n let i = ws();\n return this.indexManager.getCollectionParents(t, s).next((r => At.forEach(r, (r => {\n const o = function(t, e) {\n return new an(e, \n /*collectionGroup=*/ null, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);\n }(e, r.child(s));\n return this.getDocumentsMatchingCollectionQuery(t, o, n).next((t => {\n t.forEach(((t, e) => {\n i = i.insert(t, e);\n }));\n }));\n })).next((() => i))));\n }\n getDocumentsMatchingCollectionQuery(t, e, n) {\n // Query the remote documents and overlay mutations.\n let s;\n return this.remoteDocumentCache.getAllFromCollection(t, e.path, n).next((i => (s = i, \n this.documentOverlayCache.getOverlaysForCollection(t, e.path, n.largestBatchId)))).next((t => {\n // As documents might match the query because of their overlay we need to\n // include documents for all overlays in the initial document set.\n t.forEach(((t, e) => {\n const n = e.getKey();\n null === s.get(n) && (s = s.insert(n, Ze.newInvalidDocument(n)));\n }));\n // Apply the overlays and match against the query.\n let n = ws();\n return s.forEach(((s, i) => {\n const r = t.get(s);\n void 0 !== r && Jn(r.mutation, i, Je.empty(), nt.now()), \n // Finally, insert the documents that still match the query\n An(e, i) && (n = n.insert(s, i));\n })), n;\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Io {\n constructor(t) {\n this.yt = t, this.Zn = new Map, this.ts = new Map;\n }\n getBundleMetadata(t, e) {\n return At.resolve(this.Zn.get(e));\n }\n saveBundleMetadata(t, e) {\n /** Decodes a BundleMetadata proto into a BundleMetadata object. */\n var n;\n return this.Zn.set(e.id, {\n id: (n = e).id,\n version: n.version,\n createTime: qs(n.createTime)\n }), At.resolve();\n }\n getNamedQuery(t, e) {\n return At.resolve(this.ts.get(e));\n }\n saveNamedQuery(t, e) {\n return this.ts.set(e.name, function(t) {\n return {\n name: t.name,\n query: ir(t.bundledQuery),\n readTime: qs(t.readTime)\n };\n }(e)), At.resolve();\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An in-memory implementation of DocumentOverlayCache.\n */ class To {\n constructor() {\n // A map sorted by DocumentKey, whose value is a pair of the largest batch id\n // for the overlay and the overlay itself.\n this.overlays = new Ge(ct.comparator), this.es = new Map;\n }\n getOverlay(t, e) {\n return At.resolve(this.overlays.get(e));\n }\n getOverlays(t, e) {\n const n = gs();\n return At.forEach(e, (e => this.getOverlay(t, e).next((t => {\n null !== t && n.set(e, t);\n })))).next((() => n));\n }\n saveOverlays(t, e, n) {\n return n.forEach(((n, s) => {\n this.oe(t, e, s);\n })), At.resolve();\n }\n removeOverlaysForBatchId(t, e, n) {\n const s = this.es.get(n);\n return void 0 !== s && (s.forEach((t => this.overlays = this.overlays.remove(t))), \n this.es.delete(n)), At.resolve();\n }\n getOverlaysForCollection(t, e, n) {\n const s = gs(), i = e.length + 1, r = new ct(e.child(\"\")), o = this.overlays.getIteratorFrom(r);\n for (;o.hasNext(); ) {\n const t = o.getNext().value, r = t.getKey();\n if (!e.isPrefixOf(r.path)) break;\n // Documents from sub-collections\n r.path.length === i && (t.largestBatchId > n && s.set(t.getKey(), t));\n }\n return At.resolve(s);\n }\n getOverlaysForCollectionGroup(t, e, n, s) {\n let i = new Ge(((t, e) => t - e));\n const r = this.overlays.getIterator();\n for (;r.hasNext(); ) {\n const t = r.getNext().value;\n if (t.getKey().getCollectionGroup() === e && t.largestBatchId > n) {\n let e = i.get(t.largestBatchId);\n null === e && (e = gs(), i = i.insert(t.largestBatchId, e)), e.set(t.getKey(), t);\n }\n }\n const o = gs(), u = i.getIterator();\n for (;u.hasNext(); ) {\n if (u.getNext().value.forEach(((t, e) => o.set(t, e))), o.size() >= s) break;\n }\n return At.resolve(o);\n }\n oe(t, e, n) {\n // Remove the association of the overlay to its batch id.\n const s = this.overlays.get(n.key);\n if (null !== s) {\n const t = this.es.get(s.largestBatchId).delete(n.key);\n this.es.set(s.largestBatchId, t);\n }\n this.overlays = this.overlays.insert(n.key, new Wi(e, n));\n // Create the association of this overlay to the given largestBatchId.\n let i = this.es.get(e);\n void 0 === i && (i = Es(), this.es.set(e, i)), this.es.set(e, i.add(n.key));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A collection of references to a document from some kind of numbered entity\n * (either a target ID or batch ID). As references are added to or removed from\n * the set corresponding events are emitted to a registered garbage collector.\n *\n * Each reference is represented by a DocumentReference object. Each of them\n * contains enough information to uniquely identify the reference. They are all\n * stored primarily in a set sorted by key. A document is considered garbage if\n * there's no references in that set (this can be efficiently checked thanks to\n * sorting by key).\n *\n * ReferenceSet also keeps a secondary set that contains references sorted by\n * IDs. This one is used to efficiently implement removal of all references by\n * some target ID.\n */ class Eo {\n constructor() {\n // A set of outstanding references to a document sorted by key.\n this.ns = new We(Ao.ss), \n // A set of outstanding references to a document sorted by target id.\n this.rs = new We(Ao.os);\n }\n /** Returns true if the reference set contains no references. */ isEmpty() {\n return this.ns.isEmpty();\n }\n /** Adds a reference to the given document key for the given ID. */ addReference(t, e) {\n const n = new Ao(t, e);\n this.ns = this.ns.add(n), this.rs = this.rs.add(n);\n }\n /** Add references to the given document keys for the given ID. */ us(t, e) {\n t.forEach((t => this.addReference(t, e)));\n }\n /**\n * Removes a reference to the given document key for the given\n * ID.\n */ removeReference(t, e) {\n this.cs(new Ao(t, e));\n }\n hs(t, e) {\n t.forEach((t => this.removeReference(t, e)));\n }\n /**\n * Clears all references with a given ID. Calls removeRef() for each key\n * removed.\n */ ls(t) {\n const e = new ct(new rt([])), n = new Ao(e, t), s = new Ao(e, t + 1), i = [];\n return this.rs.forEachInRange([ n, s ], (t => {\n this.cs(t), i.push(t.key);\n })), i;\n }\n fs() {\n this.ns.forEach((t => this.cs(t)));\n }\n cs(t) {\n this.ns = this.ns.delete(t), this.rs = this.rs.delete(t);\n }\n ds(t) {\n const e = new ct(new rt([])), n = new Ao(e, t), s = new Ao(e, t + 1);\n let i = Es();\n return this.rs.forEachInRange([ n, s ], (t => {\n i = i.add(t.key);\n })), i;\n }\n containsKey(t) {\n const e = new Ao(t, 0), n = this.ns.firstAfterOrEqual(e);\n return null !== n && t.isEqual(n.key);\n }\n}\n\nclass Ao {\n constructor(t, e) {\n this.key = t, this._s = e;\n }\n /** Compare by key then by ID */ static ss(t, e) {\n return ct.comparator(t.key, e.key) || Z(t._s, e._s);\n }\n /** Compare by ID then by key */ static os(t, e) {\n return Z(t._s, e._s) || ct.comparator(t.key, e.key);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class Ro {\n constructor(t, e) {\n this.indexManager = t, this.referenceDelegate = e, \n /**\n * The set of all mutations that have been sent but not yet been applied to\n * the backend.\n */\n this.mutationQueue = [], \n /** Next value to use when assigning sequential IDs to each mutation batch. */\n this.ws = 1, \n /** An ordered mapping between documents and the mutations batch IDs. */\n this.gs = new We(Ao.ss);\n }\n checkEmpty(t) {\n return At.resolve(0 === this.mutationQueue.length);\n }\n addMutationBatch(t, e, n, s) {\n const i = this.ws;\n this.ws++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1];\n const r = new Qi(i, e, n, s);\n this.mutationQueue.push(r);\n // Track references by document key and index collection parents.\n for (const e of s) this.gs = this.gs.add(new Ao(e.key, i)), this.indexManager.addToCollectionParentIndex(t, e.key.path.popLast());\n return At.resolve(r);\n }\n lookupMutationBatch(t, e) {\n return At.resolve(this.ys(e));\n }\n getNextMutationBatchAfterBatchId(t, e) {\n const n = e + 1, s = this.ps(n), i = s < 0 ? 0 : s;\n // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n return At.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null);\n }\n getHighestUnacknowledgedBatchId() {\n return At.resolve(0 === this.mutationQueue.length ? -1 : this.ws - 1);\n }\n getAllMutationBatches(t) {\n return At.resolve(this.mutationQueue.slice());\n }\n getAllMutationBatchesAffectingDocumentKey(t, e) {\n const n = new Ao(e, 0), s = new Ao(e, Number.POSITIVE_INFINITY), i = [];\n return this.gs.forEachInRange([ n, s ], (t => {\n const e = this.ys(t._s);\n i.push(e);\n })), At.resolve(i);\n }\n getAllMutationBatchesAffectingDocumentKeys(t, e) {\n let n = new We(Z);\n return e.forEach((t => {\n const e = new Ao(t, 0), s = new Ao(t, Number.POSITIVE_INFINITY);\n this.gs.forEachInRange([ e, s ], (t => {\n n = n.add(t._s);\n }));\n })), At.resolve(this.Is(n));\n }\n getAllMutationBatchesAffectingQuery(t, e) {\n // Use the query path as a prefix for testing if a document matches the\n // query.\n const n = e.path, s = n.length + 1;\n // Construct a document reference for actually scanning the index. Unlike\n // the prefix the document key in this reference must have an even number of\n // segments. The empty segment can be used a suffix of the query path\n // because it precedes all other segments in an ordered traversal.\n let i = n;\n ct.isDocumentKey(i) || (i = i.child(\"\"));\n const r = new Ao(new ct(i), 0);\n // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n let o = new We(Z);\n return this.gs.forEachWhile((t => {\n const e = t.key.path;\n return !!n.isPrefixOf(e) && (\n // Rows with document keys more than one segment longer than the query\n // path can't be matches. For example, a query on 'rooms' can't match\n // the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n e.length === s && (o = o.add(t._s)), !0);\n }), r), At.resolve(this.Is(o));\n }\n Is(t) {\n // Construct an array of matching batches, sorted by batchID to ensure that\n // multiple mutations affecting the same document key are applied in order.\n const e = [];\n return t.forEach((t => {\n const n = this.ys(t);\n null !== n && e.push(n);\n })), e;\n }\n removeMutationBatch(t, e) {\n M(0 === this.Ts(e.batchId, \"removed\")), this.mutationQueue.shift();\n let n = this.gs;\n return At.forEach(e.mutations, (s => {\n const i = new Ao(s.key, e.batchId);\n return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(t, s.key);\n })).next((() => {\n this.gs = n;\n }));\n }\n An(t) {\n // No-op since the memory mutation queue does not maintain a separate cache.\n }\n containsKey(t, e) {\n const n = new Ao(e, 0), s = this.gs.firstAfterOrEqual(n);\n return At.resolve(e.isEqual(s && s.key));\n }\n performConsistencyCheck(t) {\n return this.mutationQueue.length, At.resolve();\n }\n /**\n * Finds the index of the given batchId in the mutation queue and asserts that\n * the resulting index is within the bounds of the queue.\n *\n * @param batchId - The batchId to search for\n * @param action - A description of what the caller is doing, phrased in passive\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\n */ Ts(t, e) {\n return this.ps(t);\n }\n /**\n * Finds the index of the given batchId in the mutation queue. This operation\n * is O(1).\n *\n * @returns The computed index of the batch with the given batchId, based on\n * the state of the queue. Note this index can be negative if the requested\n * batchId has already been remvoed from the queue or past the end of the\n * queue if the batchId is larger than the last added batch.\n */ ps(t) {\n if (0 === this.mutationQueue.length) \n // As an index this is past the end of the queue\n return 0;\n // Examine the front of the queue to figure out the difference between the\n // batchId and indexes in the array. Note that since the queue is ordered\n // by batchId, if the first batch has a larger batchId then the requested\n // batchId doesn't exist in the queue.\n return t - this.mutationQueue[0].batchId;\n }\n /**\n * A version of lookupMutationBatch that doesn't return a promise, this makes\n * other functions that uses this code easier to read and more efficent.\n */ ys(t) {\n const e = this.ps(t);\n if (e < 0 || e >= this.mutationQueue.length) return null;\n return this.mutationQueue[e];\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newMemoryRemoteDocumentCache()`.\n */\nclass bo {\n /**\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n constructor(t) {\n this.Es = t, \n /** Underlying cache of documents and their read times. */\n this.docs = new Ge(ct.comparator), \n /** Size of all cached documents. */\n this.size = 0;\n }\n setIndexManager(t) {\n this.indexManager = t;\n }\n /**\n * Adds the supplied entry to the cache and updates the cache size as appropriate.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ addEntry(t, e) {\n const n = e.key, s = this.docs.get(n), i = s ? s.size : 0, r = this.Es(e);\n return this.docs = this.docs.insert(n, {\n document: e.mutableCopy(),\n size: r\n }), this.size += r - i, this.indexManager.addToCollectionParentIndex(t, n.path.popLast());\n }\n /**\n * Removes the specified entry from the cache and updates the cache size as appropriate.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()`.\n */ removeEntry(t) {\n const e = this.docs.get(t);\n e && (this.docs = this.docs.remove(t), this.size -= e.size);\n }\n getEntry(t, e) {\n const n = this.docs.get(e);\n return At.resolve(n ? n.document.mutableCopy() : Ze.newInvalidDocument(e));\n }\n getEntries(t, e) {\n let n = ds();\n return e.forEach((t => {\n const e = this.docs.get(t);\n n = n.insert(t, e ? e.document.mutableCopy() : Ze.newInvalidDocument(t));\n })), At.resolve(n);\n }\n getAllFromCollection(t, e, n) {\n let s = ds();\n // Documents are ordered by key, so we can use a prefix scan to narrow down\n // the documents we need to match the query against.\n const i = new ct(e.child(\"\")), r = this.docs.getIteratorFrom(i);\n for (;r.hasNext(); ) {\n const {key: t, value: {document: i}} = r.getNext();\n if (!e.isPrefixOf(t.path)) break;\n t.path.length > e.length + 1 || (pt(gt(i), n) <= 0 || (s = s.insert(i.key, i.mutableCopy())));\n }\n return At.resolve(s);\n }\n getAllFromCollectionGroup(t, e, n, s) {\n // This method should only be called from the IndexBackfiller if persistence\n // is enabled.\n O();\n }\n As(t, e) {\n return At.forEach(this.docs, (t => e(t)));\n }\n newChangeBuffer(t) {\n // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps\n // a separate changelog and does not need special handling for removals.\n return new Po(this);\n }\n getSize(t) {\n return At.resolve(this.size);\n }\n}\n\n/**\n * Creates a new memory-only RemoteDocumentCache.\n *\n * @param sizer - Used to assess the size of a document. For eager GC, this is\n * expected to just return 0 to avoid unnecessarily doing the work of\n * calculating the size.\n */\n/**\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\n */\nclass Po extends co {\n constructor(t) {\n super(), this.Yn = t;\n }\n applyChanges(t) {\n const e = [];\n return this.changes.forEach(((n, s) => {\n s.isValidDocument() ? e.push(this.Yn.addEntry(t, s)) : this.Yn.removeEntry(n);\n })), At.waitFor(e);\n }\n getFromCache(t, e) {\n return this.Yn.getEntry(t, e);\n }\n getAllFromCache(t, e) {\n return this.Yn.getEntries(t, e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class vo {\n constructor(t) {\n this.persistence = t, \n /**\n * Maps a target to the data about that target\n */\n this.Rs = new ls((t => nn(t)), sn), \n /** The last received snapshot version. */\n this.lastRemoteSnapshotVersion = st.min(), \n /** The highest numbered target ID encountered. */\n this.highestTargetId = 0, \n /** The highest sequence number encountered. */\n this.bs = 0, \n /**\n * A ordered bidirectional mapping between documents and the remote target\n * IDs.\n */\n this.Ps = new Eo, this.targetCount = 0, this.vs = Yr.Pn();\n }\n forEachTarget(t, e) {\n return this.Rs.forEach(((t, n) => e(n))), At.resolve();\n }\n getLastRemoteSnapshotVersion(t) {\n return At.resolve(this.lastRemoteSnapshotVersion);\n }\n getHighestSequenceNumber(t) {\n return At.resolve(this.bs);\n }\n allocateTargetId(t) {\n return this.highestTargetId = this.vs.next(), At.resolve(this.highestTargetId);\n }\n setTargetsMetadata(t, e, n) {\n return n && (this.lastRemoteSnapshotVersion = n), e > this.bs && (this.bs = e), \n At.resolve();\n }\n Dn(t) {\n this.Rs.set(t.target, t);\n const e = t.targetId;\n e > this.highestTargetId && (this.vs = new Yr(e), this.highestTargetId = e), t.sequenceNumber > this.bs && (this.bs = t.sequenceNumber);\n }\n addTargetData(t, e) {\n return this.Dn(e), this.targetCount += 1, At.resolve();\n }\n updateTargetData(t, e) {\n return this.Dn(e), At.resolve();\n }\n removeTargetData(t, e) {\n return this.Rs.delete(e.target), this.Ps.ls(e.targetId), this.targetCount -= 1, \n At.resolve();\n }\n removeTargets(t, e, n) {\n let s = 0;\n const i = [];\n return this.Rs.forEach(((r, o) => {\n o.sequenceNumber <= e && null === n.get(o.targetId) && (this.Rs.delete(r), i.push(this.removeMatchingKeysForTargetId(t, o.targetId)), \n s++);\n })), At.waitFor(i).next((() => s));\n }\n getTargetCount(t) {\n return At.resolve(this.targetCount);\n }\n getTargetData(t, e) {\n const n = this.Rs.get(e) || null;\n return At.resolve(n);\n }\n addMatchingKeys(t, e, n) {\n return this.Ps.us(e, n), At.resolve();\n }\n removeMatchingKeys(t, e, n) {\n this.Ps.hs(e, n);\n const s = this.persistence.referenceDelegate, i = [];\n return s && e.forEach((e => {\n i.push(s.markPotentiallyOrphaned(t, e));\n })), At.waitFor(i);\n }\n removeMatchingKeysForTargetId(t, e) {\n return this.Ps.ls(e), At.resolve();\n }\n getMatchingKeysForTargetId(t, e) {\n const n = this.Ps.ds(e);\n return At.resolve(n);\n }\n containsKey(t, e) {\n return At.resolve(this.Ps.containsKey(e));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A memory-backed instance of Persistence. Data is stored only in RAM and\n * not persisted across sessions.\n */\nclass Vo {\n /**\n * The constructor accepts a factory for creating a reference delegate. This\n * allows both the delegate and this instance to have strong references to\n * each other without having nullable fields that would then need to be\n * checked or asserted on every access.\n */\n constructor(t, e) {\n this.Vs = {}, this.overlays = {}, this.Ss = new Ot(0), this.Ds = !1, this.Ds = !0, \n this.referenceDelegate = t(this), this.Cs = new vo(this);\n this.indexManager = new Nr, this.remoteDocumentCache = function(t) {\n return new bo(t);\n }((t => this.referenceDelegate.xs(t))), this.yt = new Hi(e), this.Ns = new Io(this.yt);\n }\n start() {\n return Promise.resolve();\n }\n shutdown() {\n // No durable state to ensure is closed on shutdown.\n return this.Ds = !1, Promise.resolve();\n }\n get started() {\n return this.Ds;\n }\n setDatabaseDeletedListener() {\n // No op.\n }\n setNetworkEnabled() {\n // No op.\n }\n getIndexManager(t) {\n // We do not currently support indices for memory persistence, so we can\n // return the same shared instance of the memory index manager.\n return this.indexManager;\n }\n getDocumentOverlayCache(t) {\n let e = this.overlays[t.toKey()];\n return e || (e = new To, this.overlays[t.toKey()] = e), e;\n }\n getMutationQueue(t, e) {\n let n = this.Vs[t.toKey()];\n return n || (n = new Ro(e, this.referenceDelegate), this.Vs[t.toKey()] = n), n;\n }\n getTargetCache() {\n return this.Cs;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getBundleCache() {\n return this.Ns;\n }\n runTransaction(t, e, n) {\n C(\"MemoryPersistence\", \"Starting transaction:\", t);\n const s = new So(this.Ss.next());\n return this.referenceDelegate.ks(), n(s).next((t => this.referenceDelegate.Os(s).next((() => t)))).toPromise().then((t => (s.raiseOnCommittedEvent(), \n t)));\n }\n Ms(t, e) {\n return At.or(Object.values(this.Vs).map((n => () => n.containsKey(t, e))));\n }\n}\n\n/**\n * Memory persistence is not actually transactional, but future implementations\n * may have transaction-scoped state.\n */ class So extends Tt {\n constructor(t) {\n super(), this.currentSequenceNumber = t;\n }\n}\n\nclass Do {\n constructor(t) {\n this.persistence = t, \n /** Tracks all documents that are active in Query views. */\n this.Fs = new Eo, \n /** The list of documents that are potentially GCed after each transaction. */\n this.$s = null;\n }\n static Bs(t) {\n return new Do(t);\n }\n get Ls() {\n if (this.$s) return this.$s;\n throw O();\n }\n addReference(t, e, n) {\n return this.Fs.addReference(n, e), this.Ls.delete(n.toString()), At.resolve();\n }\n removeReference(t, e, n) {\n return this.Fs.removeReference(n, e), this.Ls.add(n.toString()), At.resolve();\n }\n markPotentiallyOrphaned(t, e) {\n return this.Ls.add(e.toString()), At.resolve();\n }\n removeTarget(t, e) {\n this.Fs.ls(e.targetId).forEach((t => this.Ls.add(t.toString())));\n const n = this.persistence.getTargetCache();\n return n.getMatchingKeysForTargetId(t, e.targetId).next((t => {\n t.forEach((t => this.Ls.add(t.toString())));\n })).next((() => n.removeTargetData(t, e)));\n }\n ks() {\n this.$s = new Set;\n }\n Os(t) {\n // Remove newly orphaned documents.\n const e = this.persistence.getRemoteDocumentCache().newChangeBuffer();\n return At.forEach(this.Ls, (n => {\n const s = ct.fromPath(n);\n return this.qs(t, s).next((t => {\n t || e.removeEntry(s, st.min());\n }));\n })).next((() => (this.$s = null, e.apply(t))));\n }\n updateLimboDocument(t, e) {\n return this.qs(t, e).next((t => {\n t ? this.Ls.delete(e.toString()) : this.Ls.add(e.toString());\n }));\n }\n xs(t) {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n }\n qs(t, e) {\n return At.or([ () => At.resolve(this.Fs.containsKey(e)), () => this.persistence.getTargetCache().containsKey(t, e), () => this.persistence.Ms(t, e) ]);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Performs database creation and schema upgrades. */ class Co {\n constructor(t) {\n this.yt = t;\n }\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */ $(t, e, n, s) {\n const i = new Rt(\"createOrUpgrade\", e);\n n < 1 && s >= 1 && (function(t) {\n t.createObjectStore(\"owner\");\n }(t), function(t) {\n t.createObjectStore(\"mutationQueues\", {\n keyPath: \"userId\"\n });\n t.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", Ii, {\n unique: !0\n }), t.createObjectStore(\"documentMutations\");\n }\n /**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */ (t), xo(t), function(t) {\n t.createObjectStore(\"remoteDocuments\");\n }(t));\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n let r = At.resolve();\n return n < 3 && s >= 3 && (\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n 0 !== n && (!function(t) {\n t.deleteObjectStore(\"targetDocuments\"), t.deleteObjectStore(\"targets\"), t.deleteObjectStore(\"targetGlobal\");\n }(t), xo(t)), r = r.next((() => \n /**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\n function(t) {\n const e = t.store(\"targetGlobal\"), n = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: st.min().toTimestamp(),\n targetCount: 0\n };\n return e.put(\"targetGlobalKey\", n);\n }(i)))), n < 4 && s >= 4 && (0 !== n && (\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n r = r.next((() => function(t, e) {\n return e.store(\"mutations\").W().next((n => {\n t.deleteObjectStore(\"mutations\");\n t.createObjectStore(\"mutations\", {\n keyPath: \"batchId\",\n autoIncrement: !0\n }).createIndex(\"userMutationsIndex\", Ii, {\n unique: !0\n });\n const s = e.store(\"mutations\"), i = n.map((t => s.put(t)));\n return At.waitFor(i);\n }));\n }(t, i)))), r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"clientMetadata\", {\n keyPath: \"clientId\"\n });\n }(t);\n }))), n < 5 && s >= 5 && (r = r.next((() => this.Us(i)))), n < 6 && s >= 6 && (r = r.next((() => (function(t) {\n t.createObjectStore(\"remoteDocumentGlobal\");\n }(t), this.Ks(i))))), n < 7 && s >= 7 && (r = r.next((() => this.Gs(i)))), n < 8 && s >= 8 && (r = r.next((() => this.Qs(t, i)))), \n n < 9 && s >= 9 && (r = r.next((() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n !function(t) {\n t.objectStoreNames.contains(\"remoteDocumentChanges\") && t.deleteObjectStore(\"remoteDocumentChanges\");\n }(t);\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n }))), n < 10 && s >= 10 && (r = r.next((() => this.js(i)))), n < 11 && s >= 11 && (r = r.next((() => {\n !function(t) {\n t.createObjectStore(\"bundles\", {\n keyPath: \"bundleId\"\n });\n }(t), function(t) {\n t.createObjectStore(\"namedQueries\", {\n keyPath: \"name\"\n });\n }(t);\n }))), n < 12 && s >= 12 && (r = r.next((() => {\n !function(t) {\n const e = t.createObjectStore(\"documentOverlays\", {\n keyPath: Oi\n });\n e.createIndex(\"collectionPathOverlayIndex\", Mi, {\n unique: !1\n }), e.createIndex(\"collectionGroupOverlayIndex\", Fi, {\n unique: !1\n });\n }(t);\n }))), n < 13 && s >= 13 && (r = r.next((() => function(t) {\n const e = t.createObjectStore(\"remoteDocumentsV14\", {\n keyPath: Ri\n });\n e.createIndex(\"documentKeyIndex\", bi), e.createIndex(\"collectionGroupIndex\", Pi);\n }(t))).next((() => this.Ws(t, i))).next((() => t.deleteObjectStore(\"remoteDocuments\")))), \n n < 14 && s >= 14 && (r = r.next((() => this.zs(t, i)))), n < 15 && s >= 15 && (r = r.next((() => function(t) {\n t.createObjectStore(\"indexConfiguration\", {\n keyPath: \"indexId\",\n autoIncrement: !0\n }).createIndex(\"collectionGroupIndex\", \"collectionGroup\", {\n unique: !1\n });\n t.createObjectStore(\"indexState\", {\n keyPath: Ci\n }).createIndex(\"sequenceNumberIndex\", xi, {\n unique: !1\n });\n t.createObjectStore(\"indexEntries\", {\n keyPath: Ni\n }).createIndex(\"documentKeyIndex\", ki, {\n unique: !1\n });\n }(t)))), r;\n }\n Ks(t) {\n let e = 0;\n return t.store(\"remoteDocuments\").Z(((t, n) => {\n e += Qr(n);\n })).next((() => {\n const n = {\n byteSize: e\n };\n return t.store(\"remoteDocumentGlobal\").put(\"remoteDocumentGlobalKey\", n);\n }));\n }\n Us(t) {\n const e = t.store(\"mutationQueues\"), n = t.store(\"mutations\");\n return e.W().next((e => At.forEach(e, (e => {\n const s = IDBKeyRange.bound([ e.userId, -1 ], [ e.userId, e.lastAcknowledgedBatchId ]);\n return n.W(\"userMutationsIndex\", s).next((n => At.forEach(n, (n => {\n M(n.userId === e.userId);\n const s = er(this.yt, n);\n return Gr(t, e.userId, s).next((() => {}));\n }))));\n }))));\n }\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */ Gs(t) {\n const e = t.store(\"targetDocuments\"), n = t.store(\"remoteDocuments\");\n return t.store(\"targetGlobal\").get(\"targetGlobalKey\").next((t => {\n const s = [];\n return n.Z(((n, i) => {\n const r = new rt(n), o = function(t) {\n return [ 0, mi(t) ];\n }(r);\n s.push(e.get(o).next((n => n ? At.resolve() : (n => e.put({\n targetId: 0,\n path: mi(n),\n sequenceNumber: t.highestListenSequenceNumber\n }))(r))));\n })).next((() => At.waitFor(s)));\n }));\n }\n Qs(t, e) {\n // Create the index.\n t.createObjectStore(\"collectionParents\", {\n keyPath: Di\n });\n const n = e.store(\"collectionParents\"), s = new kr, i = t => {\n if (s.add(t)) {\n const e = t.lastSegment(), s = t.popLast();\n return n.put({\n collectionId: e,\n parent: mi(s)\n });\n }\n };\n // Helper to add an index entry iff we haven't already written it.\n // Index existing remote documents.\n return e.store(\"remoteDocuments\").Z({\n X: !0\n }, ((t, e) => {\n const n = new rt(t);\n return i(n.popLast());\n })).next((() => e.store(\"documentMutations\").Z({\n X: !0\n }, (([t, e, n], s) => {\n const r = pi(e);\n return i(r.popLast());\n }))));\n }\n js(t) {\n const e = t.store(\"targets\");\n return e.Z(((t, n) => {\n const s = nr(n), i = sr(this.yt, s);\n return e.put(i);\n }));\n }\n Ws(t, e) {\n const n = e.store(\"remoteDocuments\"), s = [];\n return n.Z(((t, n) => {\n const i = e.store(\"remoteDocumentsV14\"), r = (o = n, o.document ? new ct(rt.fromString(o.document.name).popFirst(5)) : o.noDocument ? ct.fromSegments(o.noDocument.path) : o.unknownDocument ? ct.fromSegments(o.unknownDocument.path) : O()).path.toArray();\n var o;\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const u = {\n prefixPath: r.slice(0, r.length - 2),\n collectionGroup: r[r.length - 2],\n documentId: r[r.length - 1],\n readTime: n.readTime || [ 0, 0 ],\n unknownDocument: n.unknownDocument,\n noDocument: n.noDocument,\n document: n.document,\n hasCommittedMutations: !!n.hasCommittedMutations\n };\n s.push(i.put(u));\n })).next((() => At.waitFor(s)));\n }\n zs(t, e) {\n const n = e.store(\"mutations\"), s = ho(this.yt), i = new Vo(Do.Bs, this.yt.ie);\n return n.W().next((t => {\n const n = new Map;\n return t.forEach((t => {\n var e;\n let s = null !== (e = n.get(t.userId)) && void 0 !== e ? e : Es();\n er(this.yt, t).keys().forEach((t => s = s.add(t))), n.set(t.userId, s);\n })), At.forEach(n, ((t, n) => {\n const r = new P(n), o = lr.re(this.yt, r), u = i.getIndexManager(r), c = jr.re(r, this.yt, u, i.referenceDelegate);\n return new po(s, c, o, u).recalculateAndSaveOverlaysForDocumentKeys(new Ki(e, Ot.at), t).next();\n }));\n }));\n }\n}\n\nfunction xo(t) {\n t.createObjectStore(\"targetDocuments\", {\n keyPath: Vi\n }).createIndex(\"documentTargetsIndex\", Si, {\n unique: !0\n });\n // NOTE: This is unique only because the TargetId is the suffix.\n t.createObjectStore(\"targets\", {\n keyPath: \"targetId\"\n }).createIndex(\"queryTargetsIndex\", vi, {\n unique: !0\n }), t.createObjectStore(\"targetGlobal\");\n}\n\nconst No = \"Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.\";\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the “primary client”. An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s “owner” store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nclass ko {\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n t, e, n, s, i, r, o, u, c, \n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n a, h = 15) {\n if (this.allowTabSynchronization = t, this.persistenceKey = e, this.clientId = n, \n this.Hs = i, this.window = r, this.document = o, this.Js = c, this.Ys = a, this.Xs = h, \n this.Ss = null, this.Ds = !1, this.isPrimary = !1, this.networkEnabled = !0, \n /** Our window.unload handler, if registered. */\n this.Zs = null, this.inForeground = !1, \n /** Our 'visibilitychange' listener if registered. */\n this.ti = null, \n /** The client metadata refresh task. */\n this.ei = null, \n /** The last time we garbage collected the client metadata object store. */\n this.ni = Number.NEGATIVE_INFINITY, \n /** A listener to notify on primary state changes. */\n this.si = t => Promise.resolve(), !ko.C()) throw new L(B.UNIMPLEMENTED, \"This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled.\");\n this.referenceDelegate = new oo(this, s), this.ii = e + \"main\", this.yt = new Hi(u), \n this.ri = new bt(this.ii, this.Xs, new Co(this.yt)), this.Cs = new Xr(this.referenceDelegate, this.yt), \n this.remoteDocumentCache = ho(this.yt), this.Ns = new cr, this.window && this.window.localStorage ? this.oi = this.window.localStorage : (this.oi = null, \n !1 === a && x(\"IndexedDbPersistence\", \"LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.\"));\n }\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */ start() {\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.ui().then((() => {\n if (!this.isPrimary && !this.allowTabSynchronization) \n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new L(B.FAILED_PRECONDITION, No);\n return this.ci(), this.ai(), this.hi(), this.runTransaction(\"getHighestListenSequenceNumber\", \"readonly\", (t => this.Cs.getHighestSequenceNumber(t)));\n })).then((t => {\n this.Ss = new Ot(t, this.Js);\n })).then((() => {\n this.Ds = !0;\n })).catch((t => (this.ri && this.ri.close(), Promise.reject(t))));\n }\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ li(t) {\n return this.si = async e => {\n if (this.started) return t(e);\n }, t(this.isPrimary);\n }\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setDatabaseDeletedListener(t) {\n this.ri.L((async e => {\n // Check if an attempt is made to delete IndexedDB.\n null === e.newVersion && await t();\n }));\n }\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ setNetworkEnabled(t) {\n this.networkEnabled !== t && (this.networkEnabled = t, \n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.Hs.enqueueAndForget((async () => {\n this.started && await this.ui();\n })));\n }\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */ ui() {\n return this.runTransaction(\"updateClientMetadataAndTryBecomePrimary\", \"readwrite\", (t => Mo(t).put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n }).next((() => {\n if (this.isPrimary) return this.fi(t).next((t => {\n t || (this.isPrimary = !1, this.Hs.enqueueRetryable((() => this.si(!1))));\n }));\n })).next((() => this.di(t))).next((e => this.isPrimary && !e ? this._i(t).next((() => !1)) : !!e && this.wi(t).next((() => !0)))))).catch((t => {\n if (Vt(t)) \n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return C(\"IndexedDbPersistence\", \"Failed to extend owner lease: \", t), this.isPrimary;\n if (!this.allowTabSynchronization) throw t;\n return C(\"IndexedDbPersistence\", \"Releasing owner lease after error during lease refresh\", t), \n /* isPrimary= */ !1;\n })).then((t => {\n this.isPrimary !== t && this.Hs.enqueueRetryable((() => this.si(t))), this.isPrimary = t;\n }));\n }\n fi(t) {\n return Oo(t).get(\"owner\").next((t => At.resolve(this.mi(t))));\n }\n gi(t) {\n return Mo(t).delete(this.clientId);\n }\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */ async yi() {\n if (this.isPrimary && !this.pi(this.ni, 18e5)) {\n this.ni = Date.now();\n const t = await this.runTransaction(\"maybeGarbageCollectMultiClientState\", \"readwrite-primary\", (t => {\n const e = Gi(t, \"clientMetadata\");\n return e.W().next((t => {\n const n = this.Ii(t, 18e5), s = t.filter((t => -1 === n.indexOf(t)));\n // Delete metadata for clients that are no longer considered active.\n return At.forEach(s, (t => e.delete(t.clientId))).next((() => s));\n }));\n })).catch((() => []));\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.oi) for (const e of t) this.oi.removeItem(this.Ti(e.clientId));\n }\n }\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */ hi() {\n this.ei = this.Hs.enqueueAfterDelay(\"client_metadata_refresh\" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.ui().then((() => this.yi())).then((() => this.hi()))));\n }\n /** Checks whether `client` is the local client. */ mi(t) {\n return !!t && t.ownerId === this.clientId;\n }\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */ di(t) {\n if (this.Ys) return At.resolve(!0);\n return Oo(t).get(\"owner\").next((e => {\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (null !== e && this.pi(e.leaseTimestampMs, 5e3) && !this.Ei(e.ownerId)) {\n if (this.mi(e) && this.networkEnabled) return !0;\n if (!this.mi(e)) {\n if (!e.allowTabSynchronization) \n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new L(B.FAILED_PRECONDITION, No);\n return !1;\n }\n }\n return !(!this.networkEnabled || !this.inForeground) || Mo(t).W().next((t => void 0 === this.Ii(t, 5e3).find((t => {\n if (this.clientId !== t.clientId) {\n const e = !this.networkEnabled && t.networkEnabled, n = !this.inForeground && t.inForeground, s = this.networkEnabled === t.networkEnabled;\n if (e || n && s) return !0;\n }\n return !1;\n }))));\n })).next((t => (this.isPrimary !== t && C(\"IndexedDbPersistence\", `Client ${t ? \"is\" : \"is not\"} eligible for a primary lease.`), \n t)));\n }\n async shutdown() {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this.Ds = !1, this.Ai(), this.ei && (this.ei.cancel(), this.ei = null), this.Ri(), \n this.bi(), \n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.ri.runTransaction(\"shutdown\", \"readwrite\", [ \"owner\", \"clientMetadata\" ], (t => {\n const e = new Ki(t, Ot.at);\n return this._i(e).next((() => this.gi(e)));\n })), this.ri.close(), \n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.Pi();\n }\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */ Ii(t, e) {\n return t.filter((t => this.pi(t.updateTimeMs, e) && !this.Ei(t.clientId)));\n }\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */ vi() {\n return this.runTransaction(\"getActiveClients\", \"readonly\", (t => Mo(t).W().next((t => this.Ii(t, 18e5).map((t => t.clientId))))));\n }\n get started() {\n return this.Ds;\n }\n getMutationQueue(t, e) {\n return jr.re(t, this.yt, e, this.referenceDelegate);\n }\n getTargetCache() {\n return this.Cs;\n }\n getRemoteDocumentCache() {\n return this.remoteDocumentCache;\n }\n getIndexManager(t) {\n return new Mr(t, this.yt.ie.databaseId);\n }\n getDocumentOverlayCache(t) {\n return lr.re(this.yt, t);\n }\n getBundleCache() {\n return this.Ns;\n }\n runTransaction(t, e, n) {\n C(\"IndexedDbPersistence\", \"Starting transaction:\", t);\n const s = \"readonly\" === e ? \"readonly\" : \"readwrite\", i = 15 === (r = this.Xs) ? Ui : 14 === r ? qi : 13 === r ? Li : 12 === r ? Bi : 11 === r ? $i : void O();\n /** Returns the object stores for the provided schema. */\n var r;\n let o;\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.ri.runTransaction(t, s, i, (s => (o = new Ki(s, this.Ss ? this.Ss.next() : Ot.at), \n \"readwrite-primary\" === e ? this.fi(o).next((t => !!t || this.di(o))).next((e => {\n if (!e) throw x(`Failed to obtain primary lease for action '${t}'.`), this.isPrimary = !1, \n this.Hs.enqueueRetryable((() => this.si(!1))), new L(B.FAILED_PRECONDITION, It);\n return n(o);\n })).next((t => this.wi(o).next((() => t)))) : this.Vi(o).next((() => n(o)))))).then((t => (o.raiseOnCommittedEvent(), \n t)));\n }\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n Vi(t) {\n return Oo(t).get(\"owner\").next((t => {\n if (null !== t && this.pi(t.leaseTimestampMs, 5e3) && !this.Ei(t.ownerId) && !this.mi(t) && !(this.Ys || this.allowTabSynchronization && t.allowTabSynchronization)) throw new L(B.FAILED_PRECONDITION, No);\n }));\n }\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */ wi(t) {\n const e = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return Oo(t).put(\"owner\", e);\n }\n static C() {\n return bt.C();\n }\n /** Checks the primary lease and removes it if we are the current primary. */ _i(t) {\n const e = Oo(t);\n return e.get(\"owner\").next((t => this.mi(t) ? (C(\"IndexedDbPersistence\", \"Releasing primary lease.\"), \n e.delete(\"owner\")) : At.resolve()));\n }\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ pi(t, e) {\n const n = Date.now();\n return !(t < n - e) && (!(t > n) || (x(`Detected an update time that is in the future: ${t} > ${n}`), \n !1));\n }\n ci() {\n null !== this.document && \"function\" == typeof this.document.addEventListener && (this.ti = () => {\n this.Hs.enqueueAndForget((() => (this.inForeground = \"visible\" === this.document.visibilityState, \n this.ui())));\n }, this.document.addEventListener(\"visibilitychange\", this.ti), this.inForeground = \"visible\" === this.document.visibilityState);\n }\n Ri() {\n this.ti && (this.document.removeEventListener(\"visibilitychange\", this.ti), this.ti = null);\n }\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */ ai() {\n var t;\n \"function\" == typeof (null === (t = this.window) || void 0 === t ? void 0 : t.addEventListener) && (this.Zs = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.Ai(), l() && navigator.appVersion.match(/Version\\/1[45]/) && \n // On Safari 14 and 15, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.Hs.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.Hs.enqueueAndForget((() => this.shutdown()));\n }, this.window.addEventListener(\"pagehide\", this.Zs));\n }\n bi() {\n this.Zs && (this.window.removeEventListener(\"pagehide\", this.Zs), this.Zs = null);\n }\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */ Ei(t) {\n var e;\n try {\n const n = null !== (null === (e = this.oi) || void 0 === e ? void 0 : e.getItem(this.Ti(t)));\n return C(\"IndexedDbPersistence\", `Client '${t}' ${n ? \"is\" : \"is not\"} zombied in LocalStorage`), \n n;\n } catch (t) {\n // Gracefully handle if LocalStorage isn't working.\n return x(\"IndexedDbPersistence\", \"Failed to get zombied client id.\", t), !1;\n }\n }\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */ Ai() {\n if (this.oi) try {\n this.oi.setItem(this.Ti(this.clientId), String(Date.now()));\n } catch (t) {\n // Gracefully handle if LocalStorage isn't available / working.\n x(\"Failed to set zombie client id.\", t);\n }\n }\n /** Removes the zombied client entry if it exists. */ Pi() {\n if (this.oi) try {\n this.oi.removeItem(this.Ti(this.clientId));\n } catch (t) {\n // Ignore\n }\n }\n Ti(t) {\n return `firestore_zombie_${this.persistenceKey}_${t}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */ function Oo(t) {\n return Gi(t, \"owner\");\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */ function Mo(t) {\n return Gi(t, \"clientMetadata\");\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */ function Fo(t, e) {\n // Use two different prefix formats:\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let n = t.projectId;\n return t.isDefaultDatabase || (n += \".\" + t.database), \"firestore/\" + e + \"/\" + n + \"/\";\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A set of changes to what documents are currently in view and out of view for\n * a given query. These changes are sent to the LocalStore by the View (via\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\n */\nclass $o {\n constructor(t, e, n, s) {\n this.targetId = t, this.fromCache = e, this.Si = n, this.Di = s;\n }\n static Ci(t, e) {\n let n = Es(), s = Es();\n for (const t of e.docChanges) switch (t.type) {\n case 0 /* ChangeType.Added */ :\n n = n.add(t.doc.key);\n break;\n\n case 1 /* ChangeType.Removed */ :\n s = s.add(t.doc.key);\n // do nothing\n }\n return new $o(t, e.fromCache, n, s);\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Firestore query engine.\n *\n * Firestore queries can be executed in three modes. The Query Engine determines\n * what mode to use based on what data is persisted. The mode only determines\n * the runtime complexity of the query - the result set is equivalent across all\n * implementations.\n *\n * The Query engine will use indexed-based execution if a user has configured\n * any index that can be used to execute query (via `setIndexConfiguration()`).\n * Otherwise, the engine will try to optimize the query by re-using a previously\n * persisted query result. If that is not possible, the query will be executed\n * via a full collection scan.\n *\n * Index-based execution is the default when available. The query engine\n * supports partial indexed execution and merges the result from the index\n * lookup with documents that have not yet been indexed. The index evaluation\n * matches the backend's format and as such, the SDK can use indexing for all\n * queries that the backend supports.\n *\n * If no index exists, the query engine tries to take advantage of the target\n * document mapping in the TargetCache. These mappings exists for all queries\n * that have been synced with the backend at least once and allow the query\n * engine to only read documents that previously matched a query plus any\n * documents that were edited after the query was last listened to.\n *\n * There are some cases when this optimization is not guaranteed to produce\n * the same results as full collection scans. In these cases, query\n * processing falls back to full scans. These cases are:\n *\n * - Limit queries where a document that matched the query previously no longer\n * matches the query.\n *\n * - Limit queries where a document edit may cause the document to sort below\n * another document that is in the local cache.\n *\n * - Queries that have never been CURRENT or free of limbo documents.\n */ class Bo {\n constructor() {\n this.xi = !1;\n }\n /** Sets the document view to query against. */ initialize(t, e) {\n this.Ni = t, this.indexManager = e, this.xi = !0;\n }\n /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(t, e, n, s) {\n return this.ki(t, e).next((i => i || this.Oi(t, e, s, n))).next((n => n || this.Mi(t, e)));\n }\n /**\n * Performs an indexed query that evaluates the query based on a collection's\n * persisted index values. Returns `null` if an index is not available.\n */ ki(t, e) {\n if (fn(e)) \n // Queries that match all documents don't benefit from using\n // key-based lookups. It is more efficient to scan all documents in a\n // collection, rather than to perform individual lookups.\n return At.resolve(null);\n let n = gn(e);\n return this.indexManager.getIndexType(t, n).next((s => 0 /* IndexType.NONE */ === s ? null : (null !== e.limit && 1 /* IndexType.PARTIAL */ === s && (\n // We cannot apply a limit for targets that are served using a partial\n // index. If a partial index will be used to serve the target, the\n // query may return a superset of documents that match the target\n // (e.g. if the index doesn't include all the target's filters), or\n // may return the correct set of documents in the wrong order (e.g. if\n // the index doesn't include a segment for one of the orderBys).\n // Therefore, a limit should not be applied in such cases.\n e = pn(e, null, \"F\" /* LimitType.First */), n = gn(e)), this.indexManager.getDocumentsMatchingTarget(t, n).next((s => {\n const i = Es(...s);\n return this.Ni.getDocuments(t, i).next((s => this.indexManager.getMinOffset(t, n).next((n => {\n const r = this.Fi(e, s);\n return this.$i(e, r, i, n.readTime) ? this.ki(t, pn(e, null, \"F\" /* LimitType.First */)) : this.Bi(t, r, e, n);\n }))));\n })))));\n }\n /**\n * Performs a query based on the target's persisted query mapping. Returns\n * `null` if the mapping is not available or cannot be used.\n */ Oi(t, e, n, s) {\n return fn(e) || s.isEqual(st.min()) ? this.Mi(t, e) : this.Ni.getDocuments(t, n).next((i => {\n const r = this.Fi(e, i);\n return this.$i(e, r, n, s) ? this.Mi(t, e) : (S() <= u.DEBUG && C(\"QueryEngine\", \"Re-using previous result from %s to execute query: %s\", s.toString(), En(e)), \n this.Bi(t, r, e, mt(s, -1)));\n }));\n // Queries that have never seen a snapshot without limbo free documents\n // should also be run as a full collection scan.\n }\n /** Applies the query filter and sorting to the provided documents. */ Fi(t, e) {\n // Sort the documents and re-apply the query filter since previously\n // matching documents do not necessarily still match the query.\n let n = new We(bn(t));\n return e.forEach(((e, s) => {\n An(t, s) && (n = n.add(s));\n })), n;\n }\n /**\n * Determines if a limit query needs to be refilled from cache, making it\n * ineligible for index-free execution.\n *\n * @param query - The query.\n * @param sortedPreviousResults - The documents that matched the query when it\n * was last synchronized, sorted by the query's comparator.\n * @param remoteKeys - The document keys that matched the query at the last\n * snapshot.\n * @param limboFreeSnapshotVersion - The version of the snapshot when the\n * query was last synchronized.\n */ $i(t, e, n, s) {\n if (null === t.limit) \n // Queries without limits do not need to be refilled.\n return !1;\n if (n.size !== e.size) \n // The query needs to be refilled if a previously matching document no\n // longer matches.\n return !0;\n // Limit queries are not eligible for index-free query execution if there is\n // a potential that an older document from cache now sorts before a document\n // that was previously part of the limit. This, however, can only happen if\n // the document at the edge of the limit goes out of limit.\n // If a document that is not the limit boundary sorts differently,\n // the boundary of the limit itself did not change and documents from cache\n // will continue to be \"rejected\" by this boundary. Therefore, we can ignore\n // any modifications that don't affect the last document.\n const i = \"F\" /* LimitType.First */ === t.limitType ? e.last() : e.first();\n return !!i && (i.hasPendingWrites || i.version.compareTo(s) > 0);\n }\n Mi(t, e) {\n return S() <= u.DEBUG && C(\"QueryEngine\", \"Using full collection scan to execute query:\", En(e)), \n this.Ni.getDocumentsMatchingQuery(t, e, yt.min());\n }\n /**\n * Combines the results from an indexed execution with the remaining documents\n * that have not yet been indexed.\n */ Bi(t, e, n, s) {\n // Retrieve all results for documents that were updated since the offset.\n return this.Ni.getDocumentsMatchingQuery(t, n, s).next((t => (\n // Merge with existing results\n e.forEach((e => {\n t = t.insert(e.key, e);\n })), t)));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Implements `LocalStore` interface.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */\nclass Lo {\n constructor(\n /** Manages our in-memory or durable persistence. */\n t, e, n, s) {\n this.persistence = t, this.Li = e, this.yt = s, \n /**\n * Maps a targetID to data about its target.\n *\n * PORTING NOTE: We are using an immutable data structure on Web to make re-runs\n * of `applyRemoteEvent()` idempotent.\n */\n this.qi = new Ge(Z), \n /** Maps a target to its targetID. */\n // TODO(wuandy): Evaluate if TargetId can be part of Target.\n this.Ui = new ls((t => nn(t)), sn), \n /**\n * A per collection group index of the last read time processed by\n * `getNewDocumentChanges()`.\n *\n * PORTING NOTE: This is only used for multi-tab synchronization.\n */\n this.Ki = new Map, this.Gi = t.getRemoteDocumentCache(), this.Cs = t.getTargetCache(), \n this.Ns = t.getBundleCache(), this.Qi(n);\n }\n Qi(t) {\n // TODO(indexing): Add spec tests that test these components change after a\n // user change\n this.documentOverlayCache = this.persistence.getDocumentOverlayCache(t), this.indexManager = this.persistence.getIndexManager(t), \n this.mutationQueue = this.persistence.getMutationQueue(t, this.indexManager), this.localDocuments = new po(this.Gi, this.mutationQueue, this.documentOverlayCache, this.indexManager), \n this.Gi.setIndexManager(this.indexManager), this.Li.initialize(this.localDocuments, this.indexManager);\n }\n collectGarbage(t) {\n return this.persistence.runTransaction(\"Collect garbage\", \"readwrite-primary\", (e => t.collect(e, this.qi)));\n }\n}\n\nfunction qo(\n/** Manages our in-memory or durable persistence. */\nt, e, n, s) {\n return new Lo(t, e, n, s);\n}\n\n/**\n * Tells the LocalStore that the currently authenticated user has changed.\n *\n * In response the local store switches the mutation queue to the new user and\n * returns any resulting document changes.\n */\n// PORTING NOTE: Android and iOS only return the documents affected by the\n// change.\nasync function Uo(t, e) {\n const n = $(t);\n return await n.persistence.runTransaction(\"Handle user change\", \"readonly\", (t => {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n let s;\n return n.mutationQueue.getAllMutationBatches(t).next((i => (s = i, n.Qi(e), n.mutationQueue.getAllMutationBatches(t)))).next((e => {\n const i = [], r = [];\n // Union the old/new changed keys.\n let o = Es();\n for (const t of s) {\n i.push(t.batchId);\n for (const e of t.mutations) o = o.add(e.key);\n }\n for (const t of e) {\n r.push(t.batchId);\n for (const e of t.mutations) o = o.add(e.key);\n }\n // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n return n.localDocuments.getDocuments(t, o).next((t => ({\n ji: t,\n removedBatchIds: i,\n addedBatchIds: r\n })));\n }));\n }));\n}\n\n/* Accepts locally generated Mutations and commit them to storage. */\n/**\n * Acknowledges the given batch.\n *\n * On the happy path when a batch is acknowledged, the local store will\n *\n * + remove the batch from the mutation queue;\n * + apply the changes to the remote document cache;\n * + recalculate the latency compensated view implied by those changes (there\n * may be mutations in the queue that affect the documents but haven't been\n * acknowledged yet); and\n * + give the changed documents back the sync engine\n *\n * @returns The resulting (modified) documents.\n */\nfunction Ko(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Acknowledge batch\", \"readwrite-primary\", (t => {\n const s = e.batch.keys(), i = n.Gi.newChangeBuffer({\n trackRemovals: !0\n });\n return function(t, e, n, s) {\n const i = n.batch, r = i.keys();\n let o = At.resolve();\n return r.forEach((t => {\n o = o.next((() => s.getEntry(e, t))).next((e => {\n const r = n.docVersions.get(t);\n M(null !== r), e.version.compareTo(r) < 0 && (i.applyToRemoteDocument(e, n), e.isValidDocument() && (\n // We use the commitVersion as the readTime rather than the\n // document's updateTime since the updateTime is not advanced\n // for updates that do not modify the underlying document.\n e.setReadTime(n.commitVersion), s.addEntry(e)));\n }));\n })), o.next((() => t.mutationQueue.removeMutationBatch(e, i)));\n }\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-Tab only.\n (n, t, e, i).next((() => i.apply(t))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, function(t) {\n let e = Es();\n for (let n = 0; n < t.mutationResults.length; ++n) {\n t.mutationResults[n].transformResults.length > 0 && (e = e.add(t.batch.mutations[n].key));\n }\n return e;\n }\n /**\n * Removes mutations from the MutationQueue for the specified batch;\n * LocalDocuments will be recalculated.\n *\n * @returns The resulting modified documents.\n */ (e)))).next((() => n.localDocuments.getDocuments(t, s)));\n }));\n}\n\n/**\n * Returns the last consistent snapshot processed (used by the RemoteStore to\n * determine whether to buffer incoming snapshots from the backend).\n */\nfunction Go(t) {\n const e = $(t);\n return e.persistence.runTransaction(\"Get last remote snapshot version\", \"readonly\", (t => e.Cs.getLastRemoteSnapshotVersion(t)));\n}\n\n/**\n * Updates the \"ground-state\" (remote) documents. We assume that the remote\n * event reflects any write batches that have been acknowledged or rejected\n * (i.e. we do not re-apply local mutations to updates from this event).\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */ function Qo(t, e) {\n const n = $(t), s = e.snapshotVersion;\n let i = n.qi;\n return n.persistence.runTransaction(\"Apply remote event\", \"readwrite-primary\", (t => {\n const r = n.Gi.newChangeBuffer({\n trackRemovals: !0\n });\n // Reset newTargetDataByTargetMap in case this transaction gets re-run.\n i = n.qi;\n const o = [];\n e.targetChanges.forEach(((r, u) => {\n const c = i.get(u);\n if (!c) return;\n // Only update the remote keys if the target is still active. This\n // ensures that we can persist the updated target data along with\n // the updated assignment.\n o.push(n.Cs.removeMatchingKeys(t, r.removedDocuments, u).next((() => n.Cs.addMatchingKeys(t, r.addedDocuments, u))));\n let a = c.withSequenceNumber(t.currentSequenceNumber);\n e.targetMismatches.has(u) ? a = a.withResumeToken(Qt.EMPTY_BYTE_STRING, st.min()).withLastLimboFreeSnapshotVersion(st.min()) : r.resumeToken.approximateByteSize() > 0 && (a = a.withResumeToken(r.resumeToken, s)), \n i = i.insert(u, a), \n // Update the target data if there are target changes (or if\n // sufficient time has passed since the last update).\n /**\n * Returns true if the newTargetData should be persisted during an update of\n * an active target. TargetData should always be persisted when a target is\n * being released and should not call this function.\n *\n * While the target is active, TargetData updates can be omitted when nothing\n * about the target has changed except metadata like the resume token or\n * snapshot version. Occasionally it's worth the extra write to prevent these\n * values from getting too stale after a crash, but this doesn't have to be\n * too frequent.\n */\n function(t, e, n) {\n // Always persist target data if we don't already have a resume token.\n if (0 === t.resumeToken.approximateByteSize()) return !0;\n // Don't allow resume token changes to be buffered indefinitely. This\n // allows us to be reasonably up-to-date after a crash and avoids needing\n // to loop over all active queries on shutdown. Especially in the browser\n // we may not get time to do anything interesting while the current tab is\n // closing.\n if (e.snapshotVersion.toMicroseconds() - t.snapshotVersion.toMicroseconds() >= 3e8) return !0;\n // Otherwise if the only thing that has changed about a target is its resume\n // token it's not worth persisting. Note that the RemoteStore keeps an\n // in-memory view of the currently active targets which includes the current\n // resume token, so stream failure or user changes will still use an\n // up-to-date resume token regardless of what we do here.\n return n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size > 0;\n }\n /**\n * Notifies local store of the changed views to locally pin documents.\n */ (c, a, r) && o.push(n.Cs.updateTargetData(t, a));\n }));\n let u = ds(), c = Es();\n // HACK: The only reason we allow a null snapshot version is so that we\n // can synthesize remote events when we get permission denied errors while\n // trying to resolve the state of a locally cached document that is in\n // limbo.\n if (e.documentUpdates.forEach((s => {\n e.resolvedLimboDocuments.has(s) && o.push(n.persistence.referenceDelegate.updateLimboDocument(t, s));\n })), \n // Each loop iteration only affects its \"own\" doc, so it's safe to get all\n // the remote documents in advance in a single call.\n o.push(jo(t, r, e.documentUpdates).next((t => {\n u = t.Wi, c = t.zi;\n }))), !s.isEqual(st.min())) {\n const e = n.Cs.getLastRemoteSnapshotVersion(t).next((e => n.Cs.setTargetsMetadata(t, t.currentSequenceNumber, s)));\n o.push(e);\n }\n return At.waitFor(o).next((() => r.apply(t))).next((() => n.localDocuments.getLocalViewOfDocuments(t, u, c))).next((() => u));\n })).then((t => (n.qi = i, t)));\n}\n\n/**\n * Populates document change buffer with documents from backend or a bundle.\n * Returns the document changes resulting from applying those documents, and\n * also a set of documents whose existence state are changed as a result.\n *\n * @param txn - Transaction to use to read existing documents from storage.\n * @param documentBuffer - Document buffer to collect the resulted changes to be\n * applied to storage.\n * @param documents - Documents to be applied.\n */ function jo(t, e, n) {\n let s = Es(), i = Es();\n return n.forEach((t => s = s.add(t))), e.getEntries(t, s).next((t => {\n let s = ds();\n return n.forEach(((n, r) => {\n const o = t.get(n);\n // Check if see if there is a existence state change for this document.\n r.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), \n // Note: The order of the steps below is important, since we want\n // to ensure that rejected limbo resolutions (which fabricate\n // NoDocuments with SnapshotVersion.min()) never add documents to\n // cache.\n r.isNoDocument() && r.version.isEqual(st.min()) ? (\n // NoDocuments with SnapshotVersion.min() are used in manufactured\n // events. We remove these documents from cache since we lost\n // access.\n e.removeEntry(n, r.readTime), s = s.insert(n, r)) : !o.isValidDocument() || r.version.compareTo(o.version) > 0 || 0 === r.version.compareTo(o.version) && o.hasPendingWrites ? (e.addEntry(r), \n s = s.insert(n, r)) : C(\"LocalStore\", \"Ignoring outdated watch update for \", n, \". Current version:\", o.version, \" Watch version:\", r.version);\n })), {\n Wi: s,\n zi: i\n };\n }));\n}\n\n/**\n * Gets the mutation batch after the passed in batchId in the mutation queue\n * or null if empty.\n * @param afterBatchId - If provided, the batch to search after.\n * @returns The next mutation or null if there wasn't one.\n */\nfunction Wo(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Get next mutation batch\", \"readonly\", (t => (void 0 === e && (e = -1), \n n.mutationQueue.getNextMutationBatchAfterBatchId(t, e))));\n}\n\n/**\n * Reads the current value of a Document with a given key or null if not\n * found - used for testing.\n */\n/**\n * Assigns the given target an internal ID so that its results can be pinned so\n * they don't get GC'd. A target must be allocated in the local store before\n * the store can be used to manage its view.\n *\n * Allocating an already allocated `Target` will return the existing `TargetData`\n * for that `Target`.\n */\nfunction zo(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Allocate target\", \"readwrite\", (t => {\n let s;\n return n.Cs.getTargetData(t, e).next((i => i ? (\n // This target has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n s = i, At.resolve(s)) : n.Cs.allocateTargetId(t).next((i => (s = new zi(e, i, 0 /* TargetPurpose.Listen */ , t.currentSequenceNumber), \n n.Cs.addTargetData(t, s).next((() => s)))))));\n })).then((t => {\n // If Multi-Tab is enabled, the existing target data may be newer than\n // the in-memory data\n const s = n.qi.get(t.targetId);\n return (null === s || t.snapshotVersion.compareTo(s.snapshotVersion) > 0) && (n.qi = n.qi.insert(t.targetId, t), \n n.Ui.set(e, t.targetId)), t;\n }));\n}\n\n/**\n * Returns the TargetData as seen by the LocalStore, including updates that may\n * have not yet been persisted to the TargetCache.\n */\n// Visible for testing.\n/**\n * Unpins all the documents associated with the given target. If\n * `keepPersistedTargetData` is set to false and Eager GC enabled, the method\n * directly removes the associated target data from the target cache.\n *\n * Releasing a non-existing `Target` is a no-op.\n */\n// PORTING NOTE: `keepPersistedTargetData` is multi-tab only.\nasync function Ho(t, e, n) {\n const s = $(t), i = s.qi.get(e), r = n ? \"readwrite\" : \"readwrite-primary\";\n try {\n n || await s.persistence.runTransaction(\"Release target\", r, (t => s.persistence.referenceDelegate.removeTarget(t, i)));\n } catch (t) {\n if (!Vt(t)) throw t;\n // All `releaseTarget` does is record the final metadata state for the\n // target, but we've been recording this periodically during target\n // activity. If we lose this write this could cause a very slight\n // difference in the order of target deletion during GC, but we\n // don't define exact LRU semantics so this is acceptable.\n C(\"LocalStore\", `Failed to update sequence numbers for target ${e}: ${t}`);\n }\n s.qi = s.qi.remove(e), s.Ui.delete(i.target);\n}\n\n/**\n * Runs the specified query against the local store and returns the results,\n * potentially taking advantage of query data from previous executions (such\n * as the set of remote keys).\n *\n * @param usePreviousResults - Whether results from previous executions can\n * be used to optimize this query execution.\n */ function Jo(t, e, n) {\n const s = $(t);\n let i = st.min(), r = Es();\n return s.persistence.runTransaction(\"Execute query\", \"readonly\", (t => function(t, e, n) {\n const s = $(t), i = s.Ui.get(n);\n return void 0 !== i ? At.resolve(s.qi.get(i)) : s.Cs.getTargetData(e, n);\n }(s, t, gn(e)).next((e => {\n if (e) return i = e.lastLimboFreeSnapshotVersion, s.Cs.getMatchingKeysForTargetId(t, e.targetId).next((t => {\n r = t;\n }));\n })).next((() => s.Li.getDocumentsMatchingQuery(t, e, n ? i : st.min(), n ? r : Es()))).next((t => (Zo(s, Rn(e), t), \n {\n documents: t,\n Hi: r\n })))));\n}\n\n// PORTING NOTE: Multi-Tab only.\nfunction Yo(t, e) {\n const n = $(t), s = $(n.Cs), i = n.qi.get(e);\n return i ? Promise.resolve(i.target) : n.persistence.runTransaction(\"Get target data\", \"readonly\", (t => s.ne(t, e).next((t => t ? t.target : null))));\n}\n\n/**\n * Returns the set of documents that have been updated since the last call.\n * If this is the first call, returns the set of changes since client\n * initialization. Further invocations will return document that have changed\n * since the prior call.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction Xo(t, e) {\n const n = $(t), s = n.Ki.get(e) || st.min();\n // Get the current maximum read time for the collection. This should always\n // exist, but to reduce the chance for regressions we default to\n // SnapshotVersion.Min()\n // TODO(indexing): Consider removing the default value.\n return n.persistence.runTransaction(\"Get new document changes\", \"readonly\", (t => n.Gi.getAllFromCollectionGroup(t, e, mt(s, -1), \n /* limit= */ Number.MAX_SAFE_INTEGER))).then((t => (Zo(n, e, t), t)));\n}\n\n/** Sets the collection group's maximum read time from the given documents. */\n// PORTING NOTE: Multi-Tab only.\nfunction Zo(t, e, n) {\n let s = t.Ki.get(e) || st.min();\n n.forEach(((t, e) => {\n e.readTime.compareTo(s) > 0 && (s = e.readTime);\n })), t.Ki.set(e, s);\n}\n\n/**\n * Creates a new target using the given bundle name, which will be used to\n * hold the keys of all documents from the bundle in query-document mappings.\n * This ensures that the loaded documents do not get garbage collected\n * right away.\n */\n/**\n * Applies the documents from a bundle to the \"ground-state\" (remote)\n * documents.\n *\n * LocalDocuments are re-calculated if there are remaining mutations in the\n * queue.\n */\nasync function tu(t, e, n, s) {\n const i = $(t);\n let r = Es(), o = ds();\n for (const t of n) {\n const n = e.Ji(t.metadata.name);\n t.document && (r = r.add(n));\n const s = e.Yi(t);\n s.setReadTime(e.Xi(t.metadata.readTime)), o = o.insert(n, s);\n }\n const u = i.Gi.newChangeBuffer({\n trackRemovals: !0\n }), c = await zo(i, function(t) {\n // It is OK that the path used for the query is not valid, because this will\n // not be read and queried.\n return gn(ln(rt.fromString(`__bundle__/docs/${t}`)));\n }(s));\n // Allocates a target to hold all document keys from the bundle, such that\n // they will not get garbage collected right away.\n return i.persistence.runTransaction(\"Apply bundle documents\", \"readwrite\", (t => jo(t, u, o).next((e => (u.apply(t), \n e))).next((e => i.Cs.removeMatchingKeysForTargetId(t, c.targetId).next((() => i.Cs.addMatchingKeys(t, r, c.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(t, e.Wi, e.zi))).next((() => e.Wi))))));\n}\n\n/**\n * Returns a promise of a boolean to indicate if the given bundle has already\n * been loaded and the create time is newer than the current loading bundle.\n */\n/**\n * Saves the given `NamedQuery` to local persistence.\n */\nasync function eu(t, e, n = Es()) {\n // Allocate a target for the named query such that it can be resumed\n // from associated read time if users use it to listen.\n // NOTE: this also means if no corresponding target exists, the new target\n // will remain active and will not get collected, unless users happen to\n // unlisten the query somehow.\n const s = await zo(t, gn(ir(e.bundledQuery))), i = $(t);\n return i.persistence.runTransaction(\"Save named query\", \"readwrite\", (t => {\n const r = qs(e.readTime);\n // Simply save the query itself if it is older than what the SDK already\n // has.\n if (s.snapshotVersion.compareTo(r) >= 0) return i.Ns.saveNamedQuery(t, e);\n // Update existing target data because the query from the bundle is newer.\n const o = s.withResumeToken(Qt.EMPTY_BYTE_STRING, r);\n return i.qi = i.qi.insert(o.targetId, o), i.Cs.updateTargetData(t, o).next((() => i.Cs.removeMatchingKeysForTargetId(t, s.targetId))).next((() => i.Cs.addMatchingKeys(t, n, s.targetId))).next((() => i.Ns.saveNamedQuery(t, e)));\n }));\n}\n\n/** Assembles the key for a client state in WebStorage */\nfunction nu(t, e) {\n return `firestore_clients_${t}_${e}`;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations_<persistence_prefix>_<batch_id>\n// (for unauthenticated users)\n// or: firestore_mutations_<persistence_prefix>_<batch_id>_<user_uid>\n\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n/** Assembles the key for a mutation batch in WebStorage */\nfunction su(t, e, n) {\n let s = `firestore_mutations_${t}_${n}`;\n return e.isAuthenticated() && (s += `_${e.uid}`), s;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets_<persistence_prefix>_<target_id>\n/** Assembles the key for a query state in WebStorage */\nfunction iu(t, e) {\n return `firestore_targets_${t}_${e}`;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_<persistence_prefix>\n/**\n * Holds the state of a mutation batch, including its user ID, batch ID and\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\n */\n// Visible for testing\nclass ru {\n constructor(t, e, n, s) {\n this.user = t, this.batchId = e, this.state = n, this.error = s;\n }\n /**\n * Parses a MutationMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Zi(t, e, n) {\n const s = JSON.parse(n);\n let i, r = \"object\" == typeof s && -1 !== [ \"pending\", \"acknowledged\", \"rejected\" ].indexOf(s.state) && (void 0 === s.error || \"object\" == typeof s.error);\n return r && s.error && (r = \"string\" == typeof s.error.message && \"string\" == typeof s.error.code, \n r && (i = new L(s.error.code, s.error.message))), r ? new ru(t, e, s.state, i) : (x(\"SharedClientState\", `Failed to parse mutation state for ID '${e}': ${n}`), \n null);\n }\n tr() {\n const t = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (t.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(t);\n }\n}\n\n/**\n * Holds the state of a query target, including its target ID and whether the\n * target is 'not-current', 'current' or 'rejected'.\n */\n// Visible for testing\nclass ou {\n constructor(t, e, n) {\n this.targetId = t, this.state = e, this.error = n;\n }\n /**\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Zi(t, e) {\n const n = JSON.parse(e);\n let s, i = \"object\" == typeof n && -1 !== [ \"not-current\", \"current\", \"rejected\" ].indexOf(n.state) && (void 0 === n.error || \"object\" == typeof n.error);\n return i && n.error && (i = \"string\" == typeof n.error.message && \"string\" == typeof n.error.code, \n i && (s = new L(n.error.code, n.error.message))), i ? new ou(t, n.state, s) : (x(\"SharedClientState\", `Failed to parse target state for ID '${t}': ${e}`), \n null);\n }\n tr() {\n const t = {\n state: this.state,\n updateTimeMs: Date.now()\n };\n return this.error && (t.error = {\n code: this.error.code,\n message: this.error.message\n }), JSON.stringify(t);\n }\n}\n\n/**\n * This class represents the immutable ClientState for a client read from\n * WebStorage, containing the list of active query targets.\n */ class uu {\n constructor(t, e) {\n this.clientId = t, this.activeTargetIds = e;\n }\n /**\n * Parses a RemoteClientState from the JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Zi(t, e) {\n const n = JSON.parse(e);\n let s = \"object\" == typeof n && n.activeTargetIds instanceof Array, i = Rs();\n for (let t = 0; s && t < n.activeTargetIds.length; ++t) s = Kt(n.activeTargetIds[t]), \n i = i.add(n.activeTargetIds[t]);\n return s ? new uu(t, i) : (x(\"SharedClientState\", `Failed to parse client data for instance '${t}': ${e}`), \n null);\n }\n}\n\n/**\n * This class represents the online state for all clients participating in\n * multi-tab. The online state is only written to by the primary client, and\n * used in secondary clients to update their query views.\n */ class cu {\n constructor(t, e) {\n this.clientId = t, this.onlineState = e;\n }\n /**\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\n * Logs a warning and returns null if the format of the data is not valid.\n */ static Zi(t) {\n const e = JSON.parse(t);\n return \"object\" == typeof e && -1 !== [ \"Unknown\", \"Online\", \"Offline\" ].indexOf(e.onlineState) && \"string\" == typeof e.clientId ? new cu(e.clientId, e.onlineState) : (x(\"SharedClientState\", `Failed to parse online state: ${t}`), \n null);\n }\n}\n\n/**\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\n * mutable and keeps track of all pending mutations, which allows us to\n * update the range of pending mutation batch IDs as new mutations are added or\n * removed.\n *\n * The data in `LocalClientState` is not read from WebStorage and instead\n * updated via its instance methods. The updated state can be serialized via\n * `toWebStorageJSON()`.\n */\n// Visible for testing.\nclass au {\n constructor() {\n this.activeTargetIds = Rs();\n }\n er(t) {\n this.activeTargetIds = this.activeTargetIds.add(t);\n }\n nr(t) {\n this.activeTargetIds = this.activeTargetIds.delete(t);\n }\n /**\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\n * Does not encode `clientId` as it is part of the key in WebStorage.\n */ tr() {\n const t = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now()\n };\n return JSON.stringify(t);\n }\n}\n\n/**\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\n * backing store for the SharedClientState. It keeps track of all active\n * clients and supports modifications of the local client's data.\n */ class hu {\n constructor(t, e, n, s, i) {\n this.window = t, this.Hs = e, this.persistenceKey = n, this.sr = s, this.syncEngine = null, \n this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.ir = this.rr.bind(this), \n this.ur = new Ge(Z), this.started = !1, \n /**\n * Captures WebStorage events that occur before `start()` is called. These\n * events are replayed once `WebStorageSharedClientState` is started.\n */\n this.cr = [];\n // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n const r = n.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n this.storage = this.window.localStorage, this.currentUser = i, this.ar = nu(this.persistenceKey, this.sr), \n this.hr = \n /** Assembles the key for the current sequence number. */\n function(t) {\n return `firestore_sequence_number_${t}`;\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (this.persistenceKey), this.ur = this.ur.insert(this.sr, new au), this.lr = new RegExp(`^firestore_clients_${r}_([^_]*)$`), \n this.dr = new RegExp(`^firestore_mutations_${r}_(\\\\d+)(?:_(.*))?$`), this._r = new RegExp(`^firestore_targets_${r}_(\\\\d+)$`), \n this.wr = \n /** Assembles the key for the online state of the primary tab. */\n function(t) {\n return `firestore_online_state_${t}`;\n }\n // The WebStorage prefix that plays as a event to indicate the remote documents\n // might have changed due to some secondary tabs loading a bundle.\n // format of the key is:\n // firestore_bundle_loaded_v2_<persistenceKey>\n // The version ending with \"v2\" stores the list of modified collection groups.\n (this.persistenceKey), this.mr = function(t) {\n return `firestore_bundle_loaded_v2_${t}`;\n }\n // The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n // looks like 'firestore_sequence_number_<persistence_prefix>'.\n (this.persistenceKey), \n // Rather than adding the storage observer during start(), we add the\n // storage observer during initialization. This ensures that we collect\n // events before other components populate their initial state (during their\n // respective start() calls). Otherwise, we might for example miss a\n // mutation that is added after LocalStore's start() processed the existing\n // mutations but before we observe WebStorage events.\n this.window.addEventListener(\"storage\", this.ir);\n }\n /** Returns 'true' if WebStorage is available in the current environment. */ static C(t) {\n return !(!t || !t.localStorage);\n }\n async start() {\n // Retrieve the list of existing clients to backfill the data in\n // SharedClientState.\n const t = await this.syncEngine.vi();\n for (const e of t) {\n if (e === this.sr) continue;\n const t = this.getItem(nu(this.persistenceKey, e));\n if (t) {\n const n = uu.Zi(e, t);\n n && (this.ur = this.ur.insert(n.clientId, n));\n }\n }\n this.gr();\n // Check if there is an existing online state and call the callback handler\n // if applicable.\n const e = this.storage.getItem(this.wr);\n if (e) {\n const t = this.yr(e);\n t && this.pr(t);\n }\n for (const t of this.cr) this.rr(t);\n this.cr = [], \n // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n this.window.addEventListener(\"pagehide\", (() => this.shutdown())), this.started = !0;\n }\n writeSequenceNumber(t) {\n this.setItem(this.hr, JSON.stringify(t));\n }\n getAllActiveQueryTargets() {\n return this.Ir(this.ur);\n }\n isActiveQueryTarget(t) {\n let e = !1;\n return this.ur.forEach(((n, s) => {\n s.activeTargetIds.has(t) && (e = !0);\n })), e;\n }\n addPendingMutation(t) {\n this.Tr(t, \"pending\");\n }\n updateMutationState(t, e, n) {\n this.Tr(t, e, n), \n // Once a final mutation result is observed by other clients, they no longer\n // access the mutation's metadata entry. Since WebStorage replays events\n // in order, it is safe to delete the entry right after updating it.\n this.Er(t);\n }\n addLocalQueryTarget(t) {\n let e = \"not-current\";\n // Lookup an existing query state if the target ID was already registered\n // by another tab\n if (this.isActiveQueryTarget(t)) {\n const n = this.storage.getItem(iu(this.persistenceKey, t));\n if (n) {\n const s = ou.Zi(t, n);\n s && (e = s.state);\n }\n }\n return this.Ar.er(t), this.gr(), e;\n }\n removeLocalQueryTarget(t) {\n this.Ar.nr(t), this.gr();\n }\n isLocalQueryTarget(t) {\n return this.Ar.activeTargetIds.has(t);\n }\n clearQueryState(t) {\n this.removeItem(iu(this.persistenceKey, t));\n }\n updateQueryState(t, e, n) {\n this.Rr(t, e, n);\n }\n handleUserChange(t, e, n) {\n e.forEach((t => {\n this.Er(t);\n })), this.currentUser = t, n.forEach((t => {\n this.addPendingMutation(t);\n }));\n }\n setOnlineState(t) {\n this.br(t);\n }\n notifyBundleLoaded(t) {\n this.Pr(t);\n }\n shutdown() {\n this.started && (this.window.removeEventListener(\"storage\", this.ir), this.removeItem(this.ar), \n this.started = !1);\n }\n getItem(t) {\n const e = this.storage.getItem(t);\n return C(\"SharedClientState\", \"READ\", t, e), e;\n }\n setItem(t, e) {\n C(\"SharedClientState\", \"SET\", t, e), this.storage.setItem(t, e);\n }\n removeItem(t) {\n C(\"SharedClientState\", \"REMOVE\", t), this.storage.removeItem(t);\n }\n rr(t) {\n // Note: The function is typed to take Event to be interface-compatible with\n // `Window.addEventListener`.\n const e = t;\n if (e.storageArea === this.storage) {\n if (C(\"SharedClientState\", \"EVENT\", e.key, e.newValue), e.key === this.ar) return void x(\"Received WebStorage notification for local change. Another client might have garbage-collected our state\");\n this.Hs.enqueueRetryable((async () => {\n if (this.started) {\n if (null !== e.key) if (this.lr.test(e.key)) {\n if (null == e.newValue) {\n const t = this.vr(e.key);\n return this.Vr(t, null);\n }\n {\n const t = this.Sr(e.key, e.newValue);\n if (t) return this.Vr(t.clientId, t);\n }\n } else if (this.dr.test(e.key)) {\n if (null !== e.newValue) {\n const t = this.Dr(e.key, e.newValue);\n if (t) return this.Cr(t);\n }\n } else if (this._r.test(e.key)) {\n if (null !== e.newValue) {\n const t = this.Nr(e.key, e.newValue);\n if (t) return this.kr(t);\n }\n } else if (e.key === this.wr) {\n if (null !== e.newValue) {\n const t = this.yr(e.newValue);\n if (t) return this.pr(t);\n }\n } else if (e.key === this.hr) {\n const t = function(t) {\n let e = Ot.at;\n if (null != t) try {\n const n = JSON.parse(t);\n M(\"number\" == typeof n), e = n;\n } catch (t) {\n x(\"SharedClientState\", \"Failed to read sequence number from WebStorage\", t);\n }\n return e;\n }\n /**\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\n * clients using memory persistence. The state in this class remains fully\n * isolated and no synchronization is performed.\n */ (e.newValue);\n t !== Ot.at && this.sequenceNumberHandler(t);\n } else if (e.key === this.mr) {\n const t = this.Or(e.newValue);\n await Promise.all(t.map((t => this.syncEngine.Mr(t))));\n }\n } else this.cr.push(e);\n }));\n }\n }\n get Ar() {\n return this.ur.get(this.sr);\n }\n gr() {\n this.setItem(this.ar, this.Ar.tr());\n }\n Tr(t, e, n) {\n const s = new ru(this.currentUser, t, e, n), i = su(this.persistenceKey, this.currentUser, t);\n this.setItem(i, s.tr());\n }\n Er(t) {\n const e = su(this.persistenceKey, this.currentUser, t);\n this.removeItem(e);\n }\n br(t) {\n const e = {\n clientId: this.sr,\n onlineState: t\n };\n this.storage.setItem(this.wr, JSON.stringify(e));\n }\n Rr(t, e, n) {\n const s = iu(this.persistenceKey, t), i = new ou(t, e, n);\n this.setItem(s, i.tr());\n }\n Pr(t) {\n const e = JSON.stringify(Array.from(t));\n this.setItem(this.mr, e);\n }\n /**\n * Parses a client state key in WebStorage. Returns null if the key does not\n * match the expected key format.\n */ vr(t) {\n const e = this.lr.exec(t);\n return e ? e[1] : null;\n }\n /**\n * Parses a client state in WebStorage. Returns 'null' if the value could not\n * be parsed.\n */ Sr(t, e) {\n const n = this.vr(t);\n return uu.Zi(n, e);\n }\n /**\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Dr(t, e) {\n const n = this.dr.exec(t), s = Number(n[1]), i = void 0 !== n[2] ? n[2] : null;\n return ru.Zi(new P(i), s, e);\n }\n /**\n * Parses a query target state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ Nr(t, e) {\n const n = this._r.exec(t), s = Number(n[1]);\n return ou.Zi(s, e);\n }\n /**\n * Parses an online state from WebStorage. Returns 'null' if the value\n * could not be parsed.\n */ yr(t) {\n return cu.Zi(t);\n }\n Or(t) {\n return JSON.parse(t);\n }\n async Cr(t) {\n if (t.user.uid === this.currentUser.uid) return this.syncEngine.Fr(t.batchId, t.state, t.error);\n C(\"SharedClientState\", `Ignoring mutation for non-active user ${t.user.uid}`);\n }\n kr(t) {\n return this.syncEngine.$r(t.targetId, t.state, t.error);\n }\n Vr(t, e) {\n const n = e ? this.ur.insert(t, e) : this.ur.remove(t), s = this.Ir(this.ur), i = this.Ir(n), r = [], o = [];\n return i.forEach((t => {\n s.has(t) || r.push(t);\n })), s.forEach((t => {\n i.has(t) || o.push(t);\n })), this.syncEngine.Br(r, o).then((() => {\n this.ur = n;\n }));\n }\n pr(t) {\n // We check whether the client that wrote this online state is still active\n // by comparing its client ID to the list of clients kept active in\n // IndexedDb. If a client does not update their IndexedDb client state\n // within 5 seconds, it is considered inactive and we don't emit an online\n // state event.\n this.ur.get(t.clientId) && this.onlineStateHandler(t.onlineState);\n }\n Ir(t) {\n let e = Rs();\n return t.forEach(((t, n) => {\n e = e.unionWith(n.activeTargetIds);\n })), e;\n }\n}\n\nclass lu {\n constructor() {\n this.Lr = new au, this.qr = {}, this.onlineStateHandler = null, this.sequenceNumberHandler = null;\n }\n addPendingMutation(t) {\n // No op.\n }\n updateMutationState(t, e, n) {\n // No op.\n }\n addLocalQueryTarget(t) {\n return this.Lr.er(t), this.qr[t] || \"not-current\";\n }\n updateQueryState(t, e, n) {\n this.qr[t] = e;\n }\n removeLocalQueryTarget(t) {\n this.Lr.nr(t);\n }\n isLocalQueryTarget(t) {\n return this.Lr.activeTargetIds.has(t);\n }\n clearQueryState(t) {\n delete this.qr[t];\n }\n getAllActiveQueryTargets() {\n return this.Lr.activeTargetIds;\n }\n isActiveQueryTarget(t) {\n return this.Lr.activeTargetIds.has(t);\n }\n start() {\n return this.Lr = new au, Promise.resolve();\n }\n handleUserChange(t, e, n) {\n // No op.\n }\n setOnlineState(t) {\n // No op.\n }\n shutdown() {}\n writeSequenceNumber(t) {}\n notifyBundleLoaded(t) {\n // No op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class fu {\n Ur(t) {\n // No-op.\n }\n shutdown() {\n // No-op.\n }\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable()\n/* eslint-disable no-restricted-globals */\n/**\n * Browser implementation of ConnectivityMonitor.\n */\nclass du {\n constructor() {\n this.Kr = () => this.Gr(), this.Qr = () => this.jr(), this.Wr = [], this.zr();\n }\n Ur(t) {\n this.Wr.push(t);\n }\n shutdown() {\n window.removeEventListener(\"online\", this.Kr), window.removeEventListener(\"offline\", this.Qr);\n }\n zr() {\n window.addEventListener(\"online\", this.Kr), window.addEventListener(\"offline\", this.Qr);\n }\n Gr() {\n C(\"ConnectivityMonitor\", \"Network connectivity changed: AVAILABLE\");\n for (const t of this.Wr) t(0 /* NetworkStatus.AVAILABLE */);\n }\n jr() {\n C(\"ConnectivityMonitor\", \"Network connectivity changed: UNAVAILABLE\");\n for (const t of this.Wr) t(1 /* NetworkStatus.UNAVAILABLE */);\n }\n // TODO(chenbrian): Consider passing in window either into this component or\n // here for testing via FakeWindow.\n /** Checks that all used attributes of window are available. */\n static C() {\n return \"undefined\" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const _u = {\n BatchGetDocuments: \"batchGet\",\n Commit: \"commit\",\n RunQuery: \"runQuery\",\n RunAggregationQuery: \"runAggregationQuery\"\n};\n\n/**\n * Maps RPC names to the corresponding REST endpoint name.\n *\n * We use array notation to avoid mangling.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Provides a simple helper class that implements the Stream interface to\n * bridge to other implementations that are streams but do not implement the\n * interface. The stream callbacks are invoked with the callOn... methods.\n */\nclass wu {\n constructor(t) {\n this.Hr = t.Hr, this.Jr = t.Jr;\n }\n Yr(t) {\n this.Xr = t;\n }\n Zr(t) {\n this.eo = t;\n }\n onMessage(t) {\n this.no = t;\n }\n close() {\n this.Jr();\n }\n send(t) {\n this.Hr(t);\n }\n so() {\n this.Xr();\n }\n io(t) {\n this.eo(t);\n }\n ro(t) {\n this.no(t);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class mu extends \n/**\n * Base class for all Rest-based connections to the backend (WebChannel and\n * HTTP).\n */\nclass {\n constructor(t) {\n this.databaseInfo = t, this.databaseId = t.databaseId;\n const e = t.ssl ? \"https\" : \"http\";\n this.oo = e + \"://\" + t.host, this.uo = \"projects/\" + this.databaseId.projectId + \"/databases/\" + this.databaseId.database + \"/documents\";\n }\n get co() {\n // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine\n // where to run the query, and expect the `request` to NOT specify the \"path\".\n return !1;\n }\n ao(t, e, n, s, i) {\n const r = this.ho(t, e);\n C(\"RestConnection\", \"Sending: \", r, n);\n const o = {};\n return this.lo(o, s, i), this.fo(t, r, o, n).then((t => (C(\"RestConnection\", \"Received: \", t), \n t)), (e => {\n throw N(\"RestConnection\", `${t} failed with error: `, e, \"url: \", r, \"request:\", n), \n e;\n }));\n }\n _o(t, e, n, s, i, r) {\n // The REST API automatically aggregates all of the streamed results, so we\n // can just use the normal invoke() method.\n return this.ao(t, e, n, s, i);\n }\n /**\n * Modifies the headers for a request, adding any authorization token if\n * present and any additional headers for the request.\n */ lo(t, e, n) {\n t[\"X-Goog-Api-Client\"] = \"gl-js/ fire/\" + v, \n // Content-Type: text/plain will avoid preflight requests which might\n // mess with CORS and redirects by proxies. If we add custom headers\n // we will need to change this code to potentially use the $httpOverwrite\n // parameter supported by ESF to avoid triggering preflight requests.\n t[\"Content-Type\"] = \"text/plain\", this.databaseInfo.appId && (t[\"X-Firebase-GMPID\"] = this.databaseInfo.appId), \n e && e.headers.forEach(((e, n) => t[n] = e)), n && n.headers.forEach(((e, n) => t[n] = e));\n }\n ho(t, e) {\n const n = _u[t];\n return `${this.oo}/v1/${e}:${n}`;\n }\n} {\n constructor(t) {\n super(t), this.forceLongPolling = t.forceLongPolling, this.autoDetectLongPolling = t.autoDetectLongPolling, \n this.useFetchStreams = t.useFetchStreams;\n }\n fo(t, e, n, s) {\n return new Promise(((i, r) => {\n const o = new m;\n o.setWithCredentials(!0), o.listenOnce(g.COMPLETE, (() => {\n try {\n switch (o.getLastErrorCode()) {\n case y.NO_ERROR:\n const e = o.getResponseJson();\n C(\"Connection\", \"XHR received:\", JSON.stringify(e)), i(e);\n break;\n\n case y.TIMEOUT:\n C(\"Connection\", 'RPC \"' + t + '\" timed out'), r(new L(B.DEADLINE_EXCEEDED, \"Request time out\"));\n break;\n\n case y.HTTP_ERROR:\n const n = o.getStatus();\n if (C(\"Connection\", 'RPC \"' + t + '\" failed with status:', n, \"response text:\", o.getResponseText()), \n n > 0) {\n let t = o.getResponseJson();\n Array.isArray(t) && (t = t[0]);\n const e = null == t ? void 0 : t.error;\n if (e && e.status && e.message) {\n const t = function(t) {\n const e = t.toLowerCase().replace(/_/g, \"-\");\n return Object.values(B).indexOf(e) >= 0 ? e : B.UNKNOWN;\n }(e.status);\n r(new L(t, e.message));\n } else r(new L(B.UNKNOWN, \"Server responded with status \" + o.getStatus()));\n } else \n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n r(new L(B.UNAVAILABLE, \"Connection failed.\"));\n break;\n\n default:\n O();\n }\n } finally {\n C(\"Connection\", 'RPC \"' + t + '\" completed.');\n }\n }));\n const u = JSON.stringify(s);\n o.send(e, \"POST\", u, n, 15);\n }));\n }\n wo(t, e, n) {\n const s = [ this.oo, \"/\", \"google.firestore.v1.Firestore\", \"/\", t, \"/channel\" ], i = p(), r = I(), o = {\n // Required for backend stickiness, routing behavior is based on this\n // parameter.\n httpSessionIdParam: \"gsessionid\",\n initMessageHeaders: {},\n messageUrlParams: {\n // This param is used to improve routing and project isolation by the\n // backend and must be included in every request.\n database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}`\n },\n sendRawJson: !0,\n supportsCrossDomainXhr: !0,\n internalChannelParams: {\n // Override the default timeout (randomized between 10-20 seconds) since\n // a large write batch on a slow internet connection may take a long\n // time to send to the backend. Rather than have WebChannel impose a\n // tight timeout which could lead to infinite timeouts and retries, we\n // set it very large (5-10 minutes) and rely on the browser's builtin\n // timeouts to kick in if the request isn't working.\n forwardChannelRequestTimeoutMs: 6e5\n },\n forceLongPolling: this.forceLongPolling,\n detectBufferingProxy: this.autoDetectLongPolling\n };\n this.useFetchStreams && (o.xmlHttpFactory = new T({})), this.lo(o.initMessageHeaders, e, n), \n // Sending the custom headers we just added to request.initMessageHeaders\n // (Authorization, etc.) will trigger the browser to make a CORS preflight\n // request because the XHR will no longer meet the criteria for a \"simple\"\n // CORS request:\n // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests\n // Therefore to avoid the CORS preflight request (an extra network\n // roundtrip), we use the encodeInitMessageHeaders option to specify that\n // the headers should instead be encoded in the request's POST payload,\n // which is recognized by the webchannel backend.\n o.encodeInitMessageHeaders = !0;\n const u = s.join(\"\");\n C(\"Connection\", \"Creating WebChannel: \" + u, o);\n const c = i.createWebChannel(u, o);\n // WebChannel supports sending the first message with the handshake - saving\n // a network round trip. However, it will have to call send in the same\n // JS event loop as open. In order to enforce this, we delay actually\n // opening the WebChannel until send is called. Whether we have called\n // open is tracked with this variable.\n let a = !1, h = !1;\n // A flag to determine whether the stream was closed (by us or through an\n // error/close event) to avoid delivering multiple close events or sending\n // on a closed stream\n const l = new wu({\n Hr: t => {\n h ? C(\"Connection\", \"Not sending because WebChannel is closed:\", t) : (a || (C(\"Connection\", \"Opening WebChannel transport.\"), \n c.open(), a = !0), C(\"Connection\", \"WebChannel sending:\", t), c.send(t));\n },\n Jr: () => c.close()\n }), f = (t, e, n) => {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n t.listen(e, (t => {\n try {\n n(t);\n } catch (t) {\n setTimeout((() => {\n throw t;\n }), 0);\n }\n }));\n };\n // Closure events are guarded and exceptions are swallowed, so catch any\n // exception and rethrow using a setTimeout so they become visible again.\n // Note that eventually this function could go away if we are confident\n // enough the code is exception free.\n return f(c, E.EventType.OPEN, (() => {\n h || C(\"Connection\", \"WebChannel transport opened.\");\n })), f(c, E.EventType.CLOSE, (() => {\n h || (h = !0, C(\"Connection\", \"WebChannel transport closed\"), l.io());\n })), f(c, E.EventType.ERROR, (t => {\n h || (h = !0, N(\"Connection\", \"WebChannel transport errored:\", t), l.io(new L(B.UNAVAILABLE, \"The operation could not be completed\")));\n })), f(c, E.EventType.MESSAGE, (t => {\n var e;\n if (!h) {\n const n = t.data[0];\n M(!!n);\n // TODO(b/35143891): There is a bug in One Platform that caused errors\n // (and only errors) to be wrapped in an extra array. To be forward\n // compatible with the bug we need to check either condition. The latter\n // can be removed once the fix has been rolled out.\n // Use any because msgData.error is not typed.\n const s = n, i = s.error || (null === (e = s[0]) || void 0 === e ? void 0 : e.error);\n if (i) {\n C(\"Connection\", \"WebChannel received error:\", i);\n // error.status will be a string like 'OK' or 'NOT_FOUND'.\n const t = i.status;\n let e = \n /**\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\n *\n * @returns The Code equivalent to the given status string or undefined if\n * there is no match.\n */\n function(t) {\n // lookup by string\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const e = us[t];\n if (void 0 !== e) return hs(e);\n }(t), n = i.message;\n void 0 === e && (e = B.INTERNAL, n = \"Unknown error status: \" + t + \" with message \" + i.message), \n // Mark closed so no further events are propagated\n h = !0, l.io(new L(e, n)), c.close();\n } else C(\"Connection\", \"WebChannel received:\", n), l.ro(n);\n }\n })), f(r, A.STAT_EVENT, (t => {\n t.stat === R.PROXY ? C(\"Connection\", \"Detected buffering proxy\") : t.stat === R.NOPROXY && C(\"Connection\", \"Detected no buffering proxy\");\n })), setTimeout((() => {\n // Technically we could/should wait for the WebChannel opened event,\n // but because we want to send the first message with the WebChannel\n // handshake we pretend the channel opened here (asynchronously), and\n // then delay the actual open until the first message is sent.\n l.so();\n }), 0), l;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** Initializes the WebChannelConnection for the browser. */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** The Platform's 'window' implementation or null if not available. */\nfunction gu() {\n // `window` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof window ? window : null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */ function yu() {\n // `document` is not always available, e.g. in ReactNative and WebWorkers.\n // eslint-disable-next-line no-restricted-globals\n return \"undefined\" != typeof document ? document : null;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function pu(t) {\n return new Fs(t, /* useProto3Json= */ !0);\n}\n\n/**\n * An instance of the Platform's 'TextEncoder' implementation.\n */\n/**\n * A helper for running delayed tasks following an exponential backoff curve\n * between attempts.\n *\n * Each delay is made up of a \"base\" delay which follows the exponential\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\n * base delay. This prevents clients from accidentally synchronizing their\n * delays causing spikes of load to the backend.\n */\nclass Iu {\n constructor(\n /**\n * The AsyncQueue to run backoff operations on.\n */\n t, \n /**\n * The ID to use when scheduling backoff operations on the AsyncQueue.\n */\n e, \n /**\n * The initial delay (used as the base delay on the first retry attempt).\n * Note that jitter will still be applied, so the actual delay could be as\n * little as 0.5*initialDelayMs.\n */\n n = 1e3\n /**\n * The multiplier to use to determine the extended base delay after each\n * attempt.\n */ , s = 1.5\n /**\n * The maximum base delay after which no further backoff is performed.\n * Note that jitter will still be applied, so the actual delay could be as\n * much as 1.5*maxDelayMs.\n */ , i = 6e4) {\n this.Hs = t, this.timerId = e, this.mo = n, this.yo = s, this.po = i, this.Io = 0, \n this.To = null, \n /** The last backoff attempt, as epoch milliseconds. */\n this.Eo = Date.now(), this.reset();\n }\n /**\n * Resets the backoff delay.\n *\n * The very next backoffAndWait() will have no delay. If it is called again\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\n * subsequent ones will increase according to the backoffFactor.\n */ reset() {\n this.Io = 0;\n }\n /**\n * Resets the backoff delay to the maximum delay (e.g. for use after a\n * RESOURCE_EXHAUSTED error).\n */ Ao() {\n this.Io = this.po;\n }\n /**\n * Returns a promise that resolves after currentDelayMs, and increases the\n * delay for any subsequent attempts. If there was a pending backoff operation\n * already, it will be canceled.\n */ Ro(t) {\n // Cancel any pending backoff operation.\n this.cancel();\n // First schedule using the current base (which may be 0 and should be\n // honored as such).\n const e = Math.floor(this.Io + this.bo()), n = Math.max(0, Date.now() - this.Eo), s = Math.max(0, e - n);\n // Guard against lastAttemptTime being in the future due to a clock change.\n s > 0 && C(\"ExponentialBackoff\", `Backing off for ${s} ms (base delay: ${this.Io} ms, delay with jitter: ${e} ms, last attempt: ${n} ms ago)`), \n this.To = this.Hs.enqueueAfterDelay(this.timerId, s, (() => (this.Eo = Date.now(), \n t()))), \n // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n this.Io *= this.yo, this.Io < this.mo && (this.Io = this.mo), this.Io > this.po && (this.Io = this.po);\n }\n Po() {\n null !== this.To && (this.To.skipDelay(), this.To = null);\n }\n cancel() {\n null !== this.To && (this.To.cancel(), this.To = null);\n }\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ bo() {\n return (Math.random() - .5) * this.Io;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A PersistentStream is an abstract base class that represents a streaming RPC\n * to the Firestore backend. It's built on top of the connections own support\n * for streaming RPCs, and adds several critical features for our clients:\n *\n * - Exponential backoff on failure\n * - Authentication via CredentialsProvider\n * - Dispatching all callbacks into the shared worker queue\n * - Closing idle streams after 60 seconds of inactivity\n *\n * Subclasses of PersistentStream implement serialization of models to and\n * from the JSON representation of the protocol buffers for a specific\n * streaming RPC.\n *\n * ## Starting and Stopping\n *\n * Streaming RPCs are stateful and need to be start()ed before messages can\n * be sent and received. The PersistentStream will call the onOpen() function\n * of the listener once the stream is ready to accept requests.\n *\n * Should a start() fail, PersistentStream will call the registered onClose()\n * listener with a FirestoreError indicating what went wrong.\n *\n * A PersistentStream can be started and stopped repeatedly.\n *\n * Generic types:\n * SendType: The type of the outgoing message of the underlying\n * connection stream\n * ReceiveType: The type of the incoming message of the underlying\n * connection stream\n * ListenerType: The type of the listener that will be used for callbacks\n */\nclass Tu {\n constructor(t, e, n, s, i, r, o, u) {\n this.Hs = t, this.vo = n, this.Vo = s, this.connection = i, this.authCredentialsProvider = r, \n this.appCheckCredentialsProvider = o, this.listener = u, this.state = 0 /* PersistentStreamState.Initial */ , \n /**\n * A close count that's incremented every time the stream is closed; used by\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\n * close.\n */\n this.So = 0, this.Do = null, this.Co = null, this.stream = null, this.xo = new Iu(t, e);\n }\n /**\n * Returns true if start() has been called and no error has occurred. True\n * indicates the stream is open or in the process of opening (which\n * encompasses respecting backoff, getting auth tokens, and starting the\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\n * outbound requests.\n */ No() {\n return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.ko();\n }\n /**\n * Returns true if the underlying RPC is open (the onOpen() listener has been\n * called) and the stream is ready for outbound requests.\n */ ko() {\n return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state;\n }\n /**\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\n * not immediately ready for use: onOpen() will be invoked when the RPC is\n * ready for outbound requests, at which point isOpen() will return true.\n *\n * When start returns, isStarted() will return true.\n */ start() {\n 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.Oo();\n }\n /**\n * Stops the RPC. This call is idempotent and allowed regardless of the\n * current isStarted() state.\n *\n * When stop returns, isStarted() and isOpen() will both return false.\n */ async stop() {\n this.No() && await this.close(0 /* PersistentStreamState.Initial */);\n }\n /**\n * After an error the stream will usually back off on the next attempt to\n * start it. If the error warrants an immediate restart of the stream, the\n * sender can use this to indicate that the receiver should not back off.\n *\n * Each error will call the onClose() listener. That function can decide to\n * inhibit backoff if required.\n */ Mo() {\n this.state = 0 /* PersistentStreamState.Initial */ , this.xo.reset();\n }\n /**\n * Marks this stream as idle. If no further actions are performed on the\n * stream for one minute, the stream will automatically close itself and\n * notify the stream's onClose() handler with Status.OK. The stream will then\n * be in a !isStarted() state, requiring the caller to start the stream again\n * before further use.\n *\n * Only streams that are in state 'Open' can be marked idle, as all other\n * states imply pending network operations.\n */ Fo() {\n // Starts the idle time if we are in state 'Open' and are not yet already\n // running a timer (in which case the previous idle timeout still applies).\n this.ko() && null === this.Do && (this.Do = this.Hs.enqueueAfterDelay(this.vo, 6e4, (() => this.$o())));\n }\n /** Sends a message to the underlying stream. */ Bo(t) {\n this.Lo(), this.stream.send(t);\n }\n /** Called by the idle timer when the stream should close due to inactivity. */ async $o() {\n if (this.ko()) \n // When timing out an idle stream there's no reason to force the stream into backoff when\n // it restarts so set the stream state to Initial instead of Error.\n return this.close(0 /* PersistentStreamState.Initial */);\n }\n /** Marks the stream as active again. */ Lo() {\n this.Do && (this.Do.cancel(), this.Do = null);\n }\n /** Cancels the health check delayed operation. */ qo() {\n this.Co && (this.Co.cancel(), this.Co = null);\n }\n /**\n * Closes the stream and cleans up as necessary:\n *\n * * closes the underlying GRPC stream;\n * * calls the onClose handler with the given 'error';\n * * sets internal stream state to 'finalState';\n * * adjusts the backoff timer based on the error\n *\n * A new stream can be opened by calling start().\n *\n * @param finalState - the intended state of the stream after closing.\n * @param error - the error the connection was closed with.\n */ async close(t, e) {\n // Cancel any outstanding timers (they're guaranteed not to execute).\n this.Lo(), this.qo(), this.xo.cancel(), \n // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n this.So++, 4 /* PersistentStreamState.Error */ !== t ? \n // If this is an intentional close ensure we don't delay our next connection attempt.\n this.xo.reset() : e && e.code === B.RESOURCE_EXHAUSTED ? (\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n x(e.toString()), x(\"Using maximum backoff delay to prevent overloading the backend.\"), \n this.xo.Ao()) : e && e.code === B.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && (\n // \"unauthenticated\" error means the token was rejected. This should rarely\n // happen since both Auth and AppCheck ensure a sufficient TTL when we\n // request a token. If a user manually resets their system clock this can\n // fail, however. In this case, we should get a Code.UNAUTHENTICATED error\n // before we received the first message and we need to invalidate the token\n // to ensure that we fetch a new token.\n this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), \n // Clean up the underlying stream because we are no longer interested in events.\n null !== this.stream && (this.Uo(), this.stream.close(), this.stream = null), \n // This state must be assigned before calling onClose() to allow the callback to\n // inhibit backoff or otherwise manipulate the state in its non-started state.\n this.state = t, \n // Notify the listener that the stream closed.\n await this.listener.Zr(e);\n }\n /**\n * Can be overridden to perform additional cleanup before the stream is closed.\n * Calling super.tearDown() is not required.\n */ Uo() {}\n auth() {\n this.state = 1 /* PersistentStreamState.Starting */;\n const t = this.Ko(this.So), e = this.So;\n // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([t, n]) => {\n // Stream can be stopped while waiting for authentication.\n // TODO(mikelehen): We really should just use dispatchIfNotClosed\n // and let this dispatch onto the queue, but that opened a spec test can\n // of worms that I don't want to deal with in this PR.\n this.So === e && \n // Normally we'd have to schedule the callback on the AsyncQueue.\n // However, the following calls are safe to be called outside the\n // AsyncQueue since they don't chain asynchronous calls\n this.Go(t, n);\n }), (e => {\n t((() => {\n const t = new L(B.UNKNOWN, \"Fetching auth token failed: \" + e.message);\n return this.Qo(t);\n }));\n }));\n }\n Go(t, e) {\n const n = this.Ko(this.So);\n this.stream = this.jo(t, e), this.stream.Yr((() => {\n n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.Co = this.Hs.enqueueAfterDelay(this.Vo, 1e4, (() => (this.ko() && (this.state = 3 /* PersistentStreamState.Healthy */), \n Promise.resolve()))), this.listener.Yr())));\n })), this.stream.Zr((t => {\n n((() => this.Qo(t)));\n })), this.stream.onMessage((t => {\n n((() => this.onMessage(t)));\n }));\n }\n Oo() {\n this.state = 5 /* PersistentStreamState.Backoff */ , this.xo.Ro((async () => {\n this.state = 0 /* PersistentStreamState.Initial */ , this.start();\n }));\n }\n // Visible for tests\n Qo(t) {\n // In theory the stream could close cleanly, however, in our current model\n // we never expect this to happen because if we stop a stream ourselves,\n // this callback will never be called. To prevent cases where we retry\n // without a backoff accidentally, we set the stream to error in all cases.\n return C(\"PersistentStream\", `close with error: ${t}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , t);\n }\n /**\n * Returns a \"dispatcher\" function that dispatches operations onto the\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\n * re-opened, etc.\n */ Ko(t) {\n return e => {\n this.Hs.enqueueAndForget((() => this.So === t ? e() : (C(\"PersistentStream\", \"stream callback skipped by getCloseGuardedDispatcher.\"), \n Promise.resolve())));\n };\n }\n}\n\n/**\n * A PersistentStream that implements the Listen RPC.\n *\n * Once the Listen stream has called the onOpen() listener, any number of\n * listen() and unlisten() calls can be made to control what changes will be\n * sent from the server for ListenResponses.\n */ class Eu extends Tu {\n constructor(t, e, n, s, i, r) {\n super(t, \"listen_stream_connection_backoff\" /* TimerId.ListenStreamConnectionBackoff */ , \"listen_stream_idle\" /* TimerId.ListenStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , e, n, s, r), \n this.yt = i;\n }\n jo(t, e) {\n return this.connection.wo(\"Listen\", t, e);\n }\n onMessage(t) {\n // A successful response means the stream is healthy\n this.xo.reset();\n const e = Zs(this.yt, t), n = function(t) {\n // We have only reached a consistent snapshot for the entire stream if there\n // is a read_time set and it applies to all targets (i.e. the list of\n // targets is empty). The backend is guaranteed to send such responses.\n if (!(\"targetChange\" in t)) return st.min();\n const e = t.targetChange;\n return e.targetIds && e.targetIds.length ? st.min() : e.readTime ? qs(e.readTime) : st.min();\n }(t);\n return this.listener.Wo(e, n);\n }\n /**\n * Registers interest in the results of the given target. If the target\n * includes a resumeToken it will be included in the request. Results that\n * affect the target will be streamed back as WatchChange messages that\n * reference the targetId.\n */ zo(t) {\n const e = {};\n e.database = zs(this.yt), e.addTarget = function(t, e) {\n let n;\n const s = e.target;\n return n = rn(s) ? {\n documents: si(t, s)\n } : {\n query: ii(t, s)\n }, n.targetId = e.targetId, e.resumeToken.approximateByteSize() > 0 ? n.resumeToken = Bs(t, e.resumeToken) : e.snapshotVersion.compareTo(st.min()) > 0 && (\n // TODO(wuandy): Consider removing above check because it is most likely true.\n // Right now, many tests depend on this behaviour though (leaving min() out\n // of serialization).\n n.readTime = $s(t, e.snapshotVersion.toTimestamp())), n;\n }(this.yt, t);\n const n = oi(this.yt, t);\n n && (e.labels = n), this.Bo(e);\n }\n /**\n * Unregisters interest in the results of the target associated with the\n * given targetId.\n */ Ho(t) {\n const e = {};\n e.database = zs(this.yt), e.removeTarget = t, this.Bo(e);\n }\n}\n\n/**\n * A Stream that implements the Write RPC.\n *\n * The Write RPC requires the caller to maintain special streamToken\n * state in between calls, to help the server understand which responses the\n * client has processed by the time the next request is made. Every response\n * will contain a streamToken; this value must be passed to the next\n * request.\n *\n * After calling start() on this stream, the next request must be a handshake,\n * containing whatever streamToken is on hand. Once a response to this\n * request is received, all pending mutations may be submitted. When\n * submitting multiple batches of mutations at the same time, it's\n * okay to use the same streamToken for the calls to writeMutations.\n *\n * TODO(b/33271235): Use proto types\n */ class Au extends Tu {\n constructor(t, e, n, s, i, r) {\n super(t, \"write_stream_connection_backoff\" /* TimerId.WriteStreamConnectionBackoff */ , \"write_stream_idle\" /* TimerId.WriteStreamIdle */ , \"health_check_timeout\" /* TimerId.HealthCheckTimeout */ , e, n, s, r), \n this.yt = i, this.Jo = !1;\n }\n /**\n * Tracks whether or not a handshake has been successfully exchanged and\n * the stream is ready to accept mutations.\n */ get Yo() {\n return this.Jo;\n }\n // Override of PersistentStream.start\n start() {\n this.Jo = !1, this.lastStreamToken = void 0, super.start();\n }\n Uo() {\n this.Jo && this.Xo([]);\n }\n jo(t, e) {\n return this.connection.wo(\"Write\", t, e);\n }\n onMessage(t) {\n if (\n // Always capture the last stream token.\n M(!!t.streamToken), this.lastStreamToken = t.streamToken, this.Jo) {\n // A successful first write response means the stream is healthy,\n // Note, that we could consider a successful handshake healthy, however,\n // the write itself might be causing an error we want to back off from.\n this.xo.reset();\n const e = ni(t.writeResults, t.commitTime), n = qs(t.commitTime);\n return this.listener.Zo(n, e);\n }\n // The first response is always the handshake response\n return M(!t.writeResults || 0 === t.writeResults.length), this.Jo = !0, this.listener.tu();\n }\n /**\n * Sends an initial streamToken to the server, performing the handshake\n * required to make the StreamingWrite RPC work. Subsequent\n * calls should wait until onHandshakeComplete was called.\n */ eu() {\n // TODO(dimond): Support stream resumption. We intentionally do not set the\n // stream token on the handshake, ignoring any stream token we might have.\n const t = {};\n t.database = zs(this.yt), this.Bo(t);\n }\n /** Sends a group of mutations to the Firestore backend to apply. */ Xo(t) {\n const e = {\n streamToken: this.lastStreamToken,\n writes: t.map((t => ti(this.yt, t)))\n };\n this.Bo(e);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Datastore and its related methods are a wrapper around the external Google\n * Cloud Datastore grpc API, which provides an interface that is more convenient\n * for the rest of the client SDK architecture to consume.\n */\n/**\n * An implementation of Datastore that exposes additional state for internal\n * consumption.\n */\nclass Ru extends class {} {\n constructor(t, e, n, s) {\n super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = n, \n this.yt = s, this.nu = !1;\n }\n su() {\n if (this.nu) throw new L(B.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n /** Invokes the provided RPC with auth and AppCheck tokens. */ ao(t, e, n) {\n return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, i]) => this.connection.ao(t, e, n, s, i))).catch((t => {\n throw \"FirebaseError\" === t.name ? (t.code === B.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), t) : new L(B.UNKNOWN, t.toString());\n }));\n }\n /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ _o(t, e, n, s) {\n return this.su(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, r]) => this.connection._o(t, e, n, i, r, s))).catch((t => {\n throw \"FirebaseError\" === t.name ? (t.code === B.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), \n this.appCheckCredentials.invalidateToken()), t) : new L(B.UNKNOWN, t.toString());\n }));\n }\n terminate() {\n this.nu = !0;\n }\n}\n\n// TODO(firestorexp): Make sure there is only one Datastore instance per\n// firestore-exp client.\nasync function bu(t, e) {\n const n = $(t), s = function(t, e) {\n const n = ii(t, e);\n return {\n structuredAggregationQuery: {\n aggregations: [ {\n count: {},\n alias: \"count_alias\"\n } ],\n structuredQuery: n.structuredQuery\n },\n parent: n.parent\n };\n }(n.yt, gn(e)), i = s.parent;\n n.connection.co || delete s.parent;\n return (await n._o(\"RunAggregationQuery\", i, s, /*expectedResponseCount=*/ 1)).filter((t => !!t.result)).map((t => t.result.aggregateFields));\n}\n\n/**\n * A component used by the RemoteStore to track the OnlineState (that is,\n * whether or not the client as a whole should be considered to be online or\n * offline), implementing the appropriate heuristics.\n *\n * In particular, when the client is trying to connect to the backend, we\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\n * a connection to succeed. If we have too many failures or the timeout elapses,\n * then we set the OnlineState to Offline, and the client will behave as if\n * it is offline (get()s will return cached data, etc.).\n */\nclass Pu {\n constructor(t, e) {\n this.asyncQueue = t, this.onlineStateHandler = e, \n /** The current OnlineState. */\n this.state = \"Unknown\" /* OnlineState.Unknown */ , \n /**\n * A count of consecutive failures to open the stream. If it reaches the\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\n * Offline.\n */\n this.iu = 0, \n /**\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\n */\n this.ru = null, \n /**\n * Whether the client should log a warning message if it fails to connect to\n * the backend (initially true, cleared after a successful stream, or if we've\n * logged the message already).\n */\n this.ou = !0;\n }\n /**\n * Called by RemoteStore when a watch stream is started (including on each\n * backoff attempt).\n *\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\n * the onlineStateTimer.\n */ uu() {\n 0 === this.iu && (this.cu(\"Unknown\" /* OnlineState.Unknown */), this.ru = this.asyncQueue.enqueueAfterDelay(\"online_state_timeout\" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this.ru = null, \n this.au(\"Backend didn't respond within 10 seconds.\"), this.cu(\"Offline\" /* OnlineState.Offline */), \n Promise.resolve()))));\n }\n /**\n * Updates our OnlineState as appropriate after the watch stream reports a\n * failure. The first failure moves us to the 'Unknown' state. We then may\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\n * actually transition to the 'Offline' state.\n */ hu(t) {\n \"Online\" /* OnlineState.Online */ === this.state ? this.cu(\"Unknown\" /* OnlineState.Unknown */) : (this.iu++, \n this.iu >= 1 && (this.lu(), this.au(`Connection failed 1 times. Most recent error: ${t.toString()}`), \n this.cu(\"Offline\" /* OnlineState.Offline */)));\n }\n /**\n * Explicitly sets the OnlineState to the specified state.\n *\n * Note that this resets our timers / failure counters, etc. used by our\n * Offline heuristics, so must not be used in place of\n * handleWatchStreamStart() and handleWatchStreamFailure().\n */ set(t) {\n this.lu(), this.iu = 0, \"Online\" /* OnlineState.Online */ === t && (\n // We've connected to watch at least once. Don't warn the developer\n // about being offline going forward.\n this.ou = !1), this.cu(t);\n }\n cu(t) {\n t !== this.state && (this.state = t, this.onlineStateHandler(t));\n }\n au(t) {\n const e = `Could not reach Cloud Firestore backend. ${t}\\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`;\n this.ou ? (x(e), this.ou = !1) : C(\"OnlineStateTracker\", e);\n }\n lu() {\n null !== this.ru && (this.ru.cancel(), this.ru = null);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ class vu {\n constructor(\n /**\n * The local store, used to fill the write pipeline with outbound mutations.\n */\n t, \n /** The client-side proxy for interacting with the backend. */\n e, n, s, i) {\n this.localStore = t, this.datastore = e, this.asyncQueue = n, this.remoteSyncer = {}, \n /**\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\n * LocalStore via fillWritePipeline() and have or will send to the write\n * stream.\n *\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\n * restart the write stream. When the stream is established the writes in the\n * pipeline will be sent in order.\n *\n * Writes remain in writePipeline until they are acknowledged by the backend\n * and thus will automatically be re-sent if the stream is interrupted /\n * restarted before they're acknowledged.\n *\n * Write responses from the backend are linked to their originating request\n * purely based on order, and so we can just shift() writes from the front of\n * the writePipeline as we receive responses.\n */\n this.fu = [], \n /**\n * A mapping of watched targets that the client cares about tracking and the\n * user has explicitly called a 'listen' for this target.\n *\n * These targets may or may not have been sent to or acknowledged by the\n * server. On re-establishing the listen stream, these targets should be sent\n * to the server. The targets removed with unlistens are removed eagerly\n * without waiting for confirmation from the listen stream.\n */\n this.du = new Map, \n /**\n * A set of reasons for why the RemoteStore may be offline. If empty, the\n * RemoteStore may start its network connections.\n */\n this._u = new Set, \n /**\n * Event handlers that get called when the network is disabled or enabled.\n *\n * PORTING NOTE: These functions are used on the Web client to create the\n * underlying streams (to support tree-shakeable streams). On Android and iOS,\n * the streams are created during construction of RemoteStore.\n */\n this.wu = [], this.mu = i, this.mu.Ur((t => {\n n.enqueueAndForget((async () => {\n // Porting Note: Unlike iOS, `restartNetwork()` is called even when the\n // network becomes unreachable as we don't have any other way to tear\n // down our streams.\n Mu(this) && (C(\"RemoteStore\", \"Restarting streams for network reachability change.\"), \n await async function(t) {\n const e = $(t);\n e._u.add(4 /* OfflineCause.ConnectivityChange */), await Su(e), e.gu.set(\"Unknown\" /* OnlineState.Unknown */), \n e._u.delete(4 /* OfflineCause.ConnectivityChange */), await Vu(e);\n }(this));\n }));\n })), this.gu = new Pu(n, s);\n }\n}\n\nasync function Vu(t) {\n if (Mu(t)) for (const e of t.wu) await e(/* enabled= */ !0);\n}\n\n/**\n * Temporarily disables the network. The network can be re-enabled using\n * enableNetwork().\n */ async function Su(t) {\n for (const e of t.wu) await e(/* enabled= */ !1);\n}\n\n/**\n * Starts new listen for the given target. Uses resume token if provided. It\n * is a no-op if the target of given `TargetData` is already being listened to.\n */\nfunction Du(t, e) {\n const n = $(t);\n n.du.has(e.targetId) || (\n // Mark this as something the client is currently listening for.\n n.du.set(e.targetId, e), Ou(n) ? \n // The listen will be sent in onWatchStreamOpen\n ku(n) : tc(n).ko() && xu(n, e));\n}\n\n/**\n * Removes the listen from server. It is a no-op if the given target id is\n * not being listened to.\n */ function Cu(t, e) {\n const n = $(t), s = tc(n);\n n.du.delete(e), s.ko() && Nu(n, e), 0 === n.du.size && (s.ko() ? s.Fo() : Mu(n) && \n // Revert to OnlineState.Unknown if the watch stream is not open and we\n // have no listeners, since without any listens to send we cannot\n // confirm if the stream is healthy and upgrade to OnlineState.Online.\n n.gu.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * We need to increment the the expected number of pending responses we're due\n * from watch so we wait for the ack to process any messages from this target.\n */ function xu(t, e) {\n t.yu.Ot(e.targetId), tc(t).zo(e);\n}\n\n/**\n * We need to increment the expected number of pending responses we're due\n * from watch so we wait for the removal on the server before we process any\n * messages from this target.\n */ function Nu(t, e) {\n t.yu.Ot(e), tc(t).Ho(e);\n}\n\nfunction ku(t) {\n t.yu = new Cs({\n getRemoteKeysForTarget: e => t.remoteSyncer.getRemoteKeysForTarget(e),\n ne: e => t.du.get(e) || null\n }), tc(t).start(), t.gu.uu();\n}\n\n/**\n * Returns whether the watch stream should be started because it's necessary\n * and has not yet been started.\n */ function Ou(t) {\n return Mu(t) && !tc(t).No() && t.du.size > 0;\n}\n\nfunction Mu(t) {\n return 0 === $(t)._u.size;\n}\n\nfunction Fu(t) {\n t.yu = void 0;\n}\n\nasync function $u(t) {\n t.du.forEach(((e, n) => {\n xu(t, e);\n }));\n}\n\nasync function Bu(t, e) {\n Fu(t), \n // If we still need the watch stream, retry the connection.\n Ou(t) ? (t.gu.hu(e), ku(t)) : \n // No need to restart watch stream because there are no active targets.\n // The online state is set to unknown because there is no active attempt\n // at establishing a connection\n t.gu.set(\"Unknown\" /* OnlineState.Unknown */);\n}\n\nasync function Lu(t, e, n) {\n if (\n // Mark the client as online since we got a message from the server\n t.gu.set(\"Online\" /* OnlineState.Online */), e instanceof Ss && 2 /* WatchTargetChangeState.Removed */ === e.state && e.cause) \n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n try {\n await \n /** Handles an error on a target */\n async function(t, e) {\n const n = e.cause;\n for (const s of e.targetIds) \n // A watched target might have been removed already.\n t.du.has(s) && (await t.remoteSyncer.rejectListen(s, n), t.du.delete(s), t.yu.removeTarget(s));\n }\n /**\n * Attempts to fill our write pipeline with writes from the LocalStore.\n *\n * Called internally to bootstrap or refill the write pipeline and by\n * SyncEngine whenever there are new mutations to process.\n *\n * Starts the write stream if necessary.\n */ (t, e);\n } catch (n) {\n C(\"RemoteStore\", \"Failed to remove targets %s: %s \", e.targetIds.join(\",\"), n), \n await qu(t, n);\n } else if (e instanceof vs ? t.yu.Kt(e) : e instanceof Vs ? t.yu.Jt(e) : t.yu.jt(e), \n !n.isEqual(st.min())) try {\n const e = await Go(t.localStore);\n n.compareTo(e) >= 0 && \n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.min().\n await \n /**\n * Takes a batch of changes from the Datastore, repackages them as a\n * RemoteEvent, and passes that on to the listener, which is typically the\n * SyncEngine.\n */\n function(t, e) {\n const n = t.yu.Zt(e);\n // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n return n.targetChanges.forEach(((n, s) => {\n if (n.resumeToken.approximateByteSize() > 0) {\n const i = t.du.get(s);\n // A watched target might have been removed already.\n i && t.du.set(s, i.withResumeToken(n.resumeToken, e));\n }\n })), \n // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n n.targetMismatches.forEach((e => {\n const n = t.du.get(e);\n if (!n) \n // A watched target might have been removed already.\n return;\n // Clear the resume token for the target, since we're in a known mismatch\n // state.\n t.du.set(e, n.withResumeToken(Qt.EMPTY_BYTE_STRING, n.snapshotVersion)), \n // Cause a hard reset by unwatching and rewatching immediately, but\n // deliberately don't send a resume token so that we get a full update.\n Nu(t, e);\n // Mark the target we send as being on behalf of an existence filter\n // mismatch, but don't actually retain that in listenTargets. This ensures\n // that we flag the first re-listen this way without impacting future\n // listens of this target (that might happen e.g. on reconnect).\n const s = new zi(n.target, e, 1 /* TargetPurpose.ExistenceFilterMismatch */ , n.sequenceNumber);\n xu(t, s);\n })), t.remoteSyncer.applyRemoteEvent(n);\n }(t, n);\n } catch (e) {\n C(\"RemoteStore\", \"Failed to raise snapshot:\", e), await qu(t, e);\n }\n}\n\n/**\n * Recovery logic for IndexedDB errors that takes the network offline until\n * `op` succeeds. Retries are scheduled with backoff using\n * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is\n * validated via a generic operation.\n *\n * The returned Promise is resolved once the network is disabled and before\n * any retry attempt.\n */ async function qu(t, e, n) {\n if (!Vt(e)) throw e;\n t._u.add(1 /* OfflineCause.IndexedDbFailed */), \n // Disable network and raise offline snapshots\n await Su(t), t.gu.set(\"Offline\" /* OnlineState.Offline */), n || (\n // Use a simple read operation to determine if IndexedDB recovered.\n // Ideally, we would expose a health check directly on SimpleDb, but\n // RemoteStore only has access to persistence through LocalStore.\n n = () => Go(t.localStore)), \n // Probe IndexedDB periodically and re-enable network\n t.asyncQueue.enqueueRetryable((async () => {\n C(\"RemoteStore\", \"Retrying IndexedDB access\"), await n(), t._u.delete(1 /* OfflineCause.IndexedDbFailed */), \n await Vu(t);\n }));\n}\n\n/**\n * Executes `op`. If `op` fails, takes the network offline until `op`\n * succeeds. Returns after the first attempt.\n */ function Uu(t, e) {\n return e().catch((n => qu(t, n, e)));\n}\n\nasync function Ku(t) {\n const e = $(t), n = ec(e);\n let s = e.fu.length > 0 ? e.fu[e.fu.length - 1].batchId : -1;\n for (;Gu(e); ) try {\n const t = await Wo(e.localStore, s);\n if (null === t) {\n 0 === e.fu.length && n.Fo();\n break;\n }\n s = t.batchId, Qu(e, t);\n } catch (t) {\n await qu(e, t);\n }\n ju(e) && Wu(e);\n}\n\n/**\n * Returns true if we can add to the write pipeline (i.e. the network is\n * enabled and the write pipeline is not full).\n */ function Gu(t) {\n return Mu(t) && t.fu.length < 10;\n}\n\n/**\n * Queues additional writes to be sent to the write stream, sending them\n * immediately if the write stream is established.\n */ function Qu(t, e) {\n t.fu.push(e);\n const n = ec(t);\n n.ko() && n.Yo && n.Xo(e.mutations);\n}\n\nfunction ju(t) {\n return Mu(t) && !ec(t).No() && t.fu.length > 0;\n}\n\nfunction Wu(t) {\n ec(t).start();\n}\n\nasync function zu(t) {\n ec(t).eu();\n}\n\nasync function Hu(t) {\n const e = ec(t);\n // Send the write pipeline now that the stream is established.\n for (const n of t.fu) e.Xo(n.mutations);\n}\n\nasync function Ju(t, e, n) {\n const s = t.fu.shift(), i = ji.from(s, e, n);\n await Uu(t, (() => t.remoteSyncer.applySuccessfulWrite(i))), \n // It's possible that with the completion of this mutation another\n // slot has freed up.\n await Ku(t);\n}\n\nasync function Yu(t, e) {\n // If the write stream closed after the write handshake completes, a write\n // operation failed and we fail the pending operation.\n e && ec(t).Yo && \n // This error affects the actual write.\n await async function(t, e) {\n // Only handle permanent errors here. If it's transient, just let the retry\n // logic kick in.\n if (n = e.code, as(n) && n !== B.ABORTED) {\n // This was a permanent error, the request itself was the problem\n // so it's not going to succeed if we resend it.\n const n = t.fu.shift();\n // In this case it's also unlikely that the server itself is melting\n // down -- this was just a bad request so inhibit backoff on the next\n // restart.\n ec(t).Mo(), await Uu(t, (() => t.remoteSyncer.rejectFailedWrite(n.batchId, e))), \n // It's possible that with the completion of this mutation\n // another slot has freed up.\n await Ku(t);\n }\n var n;\n }(t, e), \n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n ju(t) && Wu(t);\n}\n\nasync function Xu(t, e) {\n const n = $(t);\n n.asyncQueue.verifyOperationInProgress(), C(\"RemoteStore\", \"RemoteStore received new credentials\");\n const s = Mu(n);\n // Tear down and re-create our network streams. This will ensure we get a\n // fresh auth token for the new user and re-fill the write pipeline with\n // new mutations from the LocalStore (since mutations are per-user).\n n._u.add(3 /* OfflineCause.CredentialChange */), await Su(n), s && \n // Don't set the network status to Unknown if we are offline.\n n.gu.set(\"Unknown\" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(e), \n n._u.delete(3 /* OfflineCause.CredentialChange */), await Vu(n);\n}\n\n/**\n * Toggles the network state when the client gains or loses its primary lease.\n */ async function Zu(t, e) {\n const n = $(t);\n e ? (n._u.delete(2 /* OfflineCause.IsSecondary */), await Vu(n)) : e || (n._u.add(2 /* OfflineCause.IsSecondary */), \n await Su(n), n.gu.set(\"Unknown\" /* OnlineState.Unknown */));\n}\n\n/**\n * If not yet initialized, registers the WatchStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function tc(t) {\n return t.pu || (\n // Create stream (but note that it is not started yet).\n t.pu = function(t, e, n) {\n const s = $(t);\n return s.su(), new Eu(e, s.connection, s.authCredentials, s.appCheckCredentials, s.yt, n);\n }\n /**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t.datastore, t.asyncQueue, {\n Yr: $u.bind(null, t),\n Zr: Bu.bind(null, t),\n Wo: Lu.bind(null, t)\n }), t.wu.push((async e => {\n e ? (t.pu.Mo(), Ou(t) ? ku(t) : t.gu.set(\"Unknown\" /* OnlineState.Unknown */)) : (await t.pu.stop(), \n Fu(t));\n }))), t.pu;\n}\n\n/**\n * If not yet initialized, registers the WriteStream and its network state\n * callback with `remoteStoreImpl`. Returns the existing stream if one is\n * already available.\n *\n * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup.\n * This is not done on Web to allow it to be tree-shaken.\n */ function ec(t) {\n return t.Iu || (\n // Create stream (but note that it is not started yet).\n t.Iu = function(t, e, n) {\n const s = $(t);\n return s.su(), new Au(e, s.connection, s.authCredentials, s.appCheckCredentials, s.yt, n);\n }(t.datastore, t.asyncQueue, {\n Yr: zu.bind(null, t),\n Zr: Yu.bind(null, t),\n tu: Hu.bind(null, t),\n Zo: Ju.bind(null, t)\n }), t.wu.push((async e => {\n e ? (t.Iu.Mo(), \n // This will start the write stream if necessary.\n await Ku(t)) : (await t.Iu.stop(), t.fu.length > 0 && (C(\"RemoteStore\", `Stopping write stream with ${t.fu.length} pending writes`), \n t.fu = []));\n }))), t.Iu;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\n *\n * It is created via DelayedOperation.createAndSchedule().\n *\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\n *\n * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type\n * in newer versions of TypeScript defines `finally`, which is not available in\n * IE.\n */\nclass nc {\n constructor(t, e, n, s, i) {\n this.asyncQueue = t, this.timerId = e, this.targetTimeMs = n, this.op = s, this.removalCallback = i, \n this.deferred = new q, this.then = this.deferred.promise.then.bind(this.deferred.promise), \n // It's normal for the deferred promise to be canceled (due to cancellation)\n // and so we attach a dummy catch callback to avoid\n // 'UnhandledPromiseRejectionWarning' log spam.\n this.deferred.promise.catch((t => {}));\n }\n /**\n * Creates and returns a DelayedOperation that has been scheduled to be\n * executed on the provided asyncQueue after the provided delayMs.\n *\n * @param asyncQueue - The queue to schedule the operation on.\n * @param id - A Timer ID identifying the type of operation this is.\n * @param delayMs - The delay (ms) before the operation should be scheduled.\n * @param op - The operation to run.\n * @param removalCallback - A callback to be called synchronously once the\n * operation is executed or canceled, notifying the AsyncQueue to remove it\n * from its delayedOperations list.\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\n * the DelayedOperation class public.\n */ static createAndSchedule(t, e, n, s, i) {\n const r = Date.now() + n, o = new nc(t, e, r, s, i);\n return o.start(n), o;\n }\n /**\n * Starts the timer. This is called immediately after construction by\n * createAndSchedule().\n */ start(t) {\n this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t);\n }\n /**\n * Queues the operation to run immediately (if it hasn't already been run or\n * canceled).\n */ skipDelay() {\n return this.handleDelayElapsed();\n }\n /**\n * Cancels the operation if it hasn't already been executed or canceled. The\n * promise will be rejected.\n *\n * As long as the operation has not yet been run, calling cancel() provides a\n * guarantee that the operation will not be run.\n */ cancel(t) {\n null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new L(B.CANCELLED, \"Operation cancelled\" + (t ? \": \" + t : \"\"))));\n }\n handleDelayElapsed() {\n this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), \n this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve()));\n }\n clearTimeout() {\n null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), \n this.timerHandle = null);\n }\n}\n\n/**\n * Returns a FirestoreError that can be surfaced to the user if the provided\n * error is an IndexedDbTransactionError. Re-throws the error otherwise.\n */ function sc(t, e) {\n if (x(\"AsyncQueue\", `${e}: ${t}`), Vt(t)) return new L(B.UNAVAILABLE, `${e}: ${t}`);\n throw t;\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\n * in order specified by the provided comparator. We always add a document key\n * comparator on top of what is provided to guarantee document equality based on\n * the key.\n */ class ic {\n /** The default ordering is by key if the comparator is omitted */\n constructor(t) {\n // We are adding document key comparator to the end as it's the only\n // guaranteed unique property of a document.\n this.comparator = t ? (e, n) => t(e, n) || ct.comparator(e.key, n.key) : (t, e) => ct.comparator(t.key, e.key), \n this.keyedMap = ws(), this.sortedSet = new Ge(this.comparator);\n }\n /**\n * Returns an empty copy of the existing DocumentSet, using the same\n * comparator.\n */ static emptySet(t) {\n return new ic(t.comparator);\n }\n has(t) {\n return null != this.keyedMap.get(t);\n }\n get(t) {\n return this.keyedMap.get(t);\n }\n first() {\n return this.sortedSet.minKey();\n }\n last() {\n return this.sortedSet.maxKey();\n }\n isEmpty() {\n return this.sortedSet.isEmpty();\n }\n /**\n * Returns the index of the provided key in the document set, or -1 if the\n * document key is not present in the set;\n */ indexOf(t) {\n const e = this.keyedMap.get(t);\n return e ? this.sortedSet.indexOf(e) : -1;\n }\n get size() {\n return this.sortedSet.size;\n }\n /** Iterates documents in order defined by \"comparator\" */ forEach(t) {\n this.sortedSet.inorderTraversal(((e, n) => (t(e), !1)));\n }\n /** Inserts or updates a document with the same key */ add(t) {\n // First remove the element if we have it.\n const e = this.delete(t.key);\n return e.copy(e.keyedMap.insert(t.key, t), e.sortedSet.insert(t, null));\n }\n /** Deletes a document with a given key */ delete(t) {\n const e = this.get(t);\n return e ? this.copy(this.keyedMap.remove(t), this.sortedSet.remove(e)) : this;\n }\n isEqual(t) {\n if (!(t instanceof ic)) return !1;\n if (this.size !== t.size) return !1;\n const e = this.sortedSet.getIterator(), n = t.sortedSet.getIterator();\n for (;e.hasNext(); ) {\n const t = e.getNext().key, s = n.getNext().key;\n if (!t.isEqual(s)) return !1;\n }\n return !0;\n }\n toString() {\n const t = [];\n return this.forEach((e => {\n t.push(e.toString());\n })), 0 === t.length ? \"DocumentSet ()\" : \"DocumentSet (\\n \" + t.join(\" \\n\") + \"\\n)\";\n }\n copy(t, e) {\n const n = new ic;\n return n.comparator = this.comparator, n.keyedMap = t, n.sortedSet = e, n;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\n * duplicate events for the same doc.\n */ class rc {\n constructor() {\n this.Tu = new Ge(ct.comparator);\n }\n track(t) {\n const e = t.doc.key, n = this.Tu.get(e);\n n ? \n // Merge the new change with the existing change.\n 0 /* ChangeType.Added */ !== t.type && 3 /* ChangeType.Metadata */ === n.type ? this.Tu = this.Tu.insert(e, t) : 3 /* ChangeType.Metadata */ === t.type && 1 /* ChangeType.Removed */ !== n.type ? this.Tu = this.Tu.insert(e, {\n type: n.type,\n doc: t.doc\n }) : 2 /* ChangeType.Modified */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {\n type: 2 /* ChangeType.Modified */ ,\n doc: t.doc\n }) : 2 /* ChangeType.Modified */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.insert(e, {\n type: 0 /* ChangeType.Added */ ,\n doc: t.doc\n }) : 1 /* ChangeType.Removed */ === t.type && 0 /* ChangeType.Added */ === n.type ? this.Tu = this.Tu.remove(e) : 1 /* ChangeType.Removed */ === t.type && 2 /* ChangeType.Modified */ === n.type ? this.Tu = this.Tu.insert(e, {\n type: 1 /* ChangeType.Removed */ ,\n doc: n.doc\n }) : 0 /* ChangeType.Added */ === t.type && 1 /* ChangeType.Removed */ === n.type ? this.Tu = this.Tu.insert(e, {\n type: 2 /* ChangeType.Modified */ ,\n doc: t.doc\n }) : \n // This includes these cases, which don't make sense:\n // Added->Added\n // Removed->Removed\n // Modified->Added\n // Removed->Modified\n // Metadata->Added\n // Removed->Metadata\n O() : this.Tu = this.Tu.insert(e, t);\n }\n Eu() {\n const t = [];\n return this.Tu.inorderTraversal(((e, n) => {\n t.push(n);\n })), t;\n }\n}\n\nclass oc {\n constructor(t, e, n, s, i, r, o, u, c) {\n this.query = t, this.docs = e, this.oldDocs = n, this.docChanges = s, this.mutatedKeys = i, \n this.fromCache = r, this.syncStateChanged = o, this.excludesMetadataChanges = u, \n this.hasCachedResults = c;\n }\n /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(t, e, n, s, i) {\n const r = [];\n return e.forEach((t => {\n r.push({\n type: 0 /* ChangeType.Added */ ,\n doc: t\n });\n })), new oc(t, e, ic.emptySet(e), r, n, s, \n /* syncStateChanged= */ !0, \n /* excludesMetadataChanges= */ !1, i);\n }\n get hasPendingWrites() {\n return !this.mutatedKeys.isEmpty();\n }\n isEqual(t) {\n if (!(this.fromCache === t.fromCache && this.hasCachedResults === t.hasCachedResults && this.syncStateChanged === t.syncStateChanged && this.mutatedKeys.isEqual(t.mutatedKeys) && In(this.query, t.query) && this.docs.isEqual(t.docs) && this.oldDocs.isEqual(t.oldDocs))) return !1;\n const e = this.docChanges, n = t.docChanges;\n if (e.length !== n.length) return !1;\n for (let t = 0; t < e.length; t++) if (e[t].type !== n[t].type || !e[t].doc.isEqual(n[t].doc)) return !1;\n return !0;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Holds the listeners and the last received ViewSnapshot for a query being\n * tracked by EventManager.\n */ class uc {\n constructor() {\n this.Au = void 0, this.listeners = [];\n }\n}\n\nclass cc {\n constructor() {\n this.queries = new ls((t => Tn(t)), In), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.Ru = new Set;\n }\n}\n\nasync function ac(t, e) {\n const n = $(t), s = e.query;\n let i = !1, r = n.queries.get(s);\n if (r || (i = !0, r = new uc), i) try {\n r.Au = await n.onListen(s);\n } catch (t) {\n const n = sc(t, `Initialization of query '${En(e.query)}' failed`);\n return void e.onError(n);\n }\n if (n.queries.set(s, r), r.listeners.push(e), \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n e.bu(n.onlineState), r.Au) {\n e.Pu(r.Au) && dc(n);\n }\n}\n\nasync function hc(t, e) {\n const n = $(t), s = e.query;\n let i = !1;\n const r = n.queries.get(s);\n if (r) {\n const t = r.listeners.indexOf(e);\n t >= 0 && (r.listeners.splice(t, 1), i = 0 === r.listeners.length);\n }\n if (i) return n.queries.delete(s), n.onUnlisten(s);\n}\n\nfunction lc(t, e) {\n const n = $(t);\n let s = !1;\n for (const t of e) {\n const e = t.query, i = n.queries.get(e);\n if (i) {\n for (const e of i.listeners) e.Pu(t) && (s = !0);\n i.Au = t;\n }\n }\n s && dc(n);\n}\n\nfunction fc(t, e, n) {\n const s = $(t), i = s.queries.get(e);\n if (i) for (const t of i.listeners) t.onError(n);\n // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n s.queries.delete(e);\n}\n\n// Call all global snapshot listeners that have been set.\nfunction dc(t) {\n t.Ru.forEach((t => {\n t.next();\n }));\n}\n\n/**\n * QueryListener takes a series of internal view snapshots and determines\n * when to raise the event.\n *\n * It uses an Observer to dispatch events.\n */ class _c {\n constructor(t, e, n) {\n this.query = t, this.vu = e, \n /**\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\n * observer. This flag is set to true once we've actually raised an event.\n */\n this.Vu = !1, this.Su = null, this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n this.options = n || {};\n }\n /**\n * Applies the new ViewSnapshot to this listener, raising a user-facing event\n * if applicable (depending on what changed, whether the user has opted into\n * metadata-only changes, etc.). Returns true if a user-facing event was\n * indeed raised.\n */ Pu(t) {\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n const e = [];\n for (const n of t.docChanges) 3 /* ChangeType.Metadata */ !== n.type && e.push(n);\n t = new oc(t.query, t.docs, t.oldDocs, e, t.mutatedKeys, t.fromCache, t.syncStateChanged, \n /* excludesMetadataChanges= */ !0, t.hasCachedResults);\n }\n let e = !1;\n return this.Vu ? this.Du(t) && (this.vu.next(t), e = !0) : this.Cu(t, this.onlineState) && (this.xu(t), \n e = !0), this.Su = t, e;\n }\n onError(t) {\n this.vu.error(t);\n }\n /** Returns whether a snapshot was raised. */ bu(t) {\n this.onlineState = t;\n let e = !1;\n return this.Su && !this.Vu && this.Cu(this.Su, t) && (this.xu(this.Su), e = !0), \n e;\n }\n Cu(t, e) {\n // Always raise the first event when we're synced\n if (!t.fromCache) return !0;\n // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n const n = \"Offline\" /* OnlineState.Offline */ !== e;\n // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n return (!this.options.Nu || !n) && (!t.docs.isEmpty() || t.hasCachedResults || \"Offline\" /* OnlineState.Offline */ === e);\n // Raise data from cache if we have any documents, have cached results before,\n // or we are offline.\n }\n Du(t) {\n // We don't need to handle includeDocumentMetadataChanges here because\n // the Metadata only changes have already been stripped out if needed.\n // At this point the only changes we will see are the ones we should\n // propagate.\n if (t.docChanges.length > 0) return !0;\n const e = this.Su && this.Su.hasPendingWrites !== t.hasPendingWrites;\n return !(!t.syncStateChanged && !e) && !0 === this.options.includeMetadataChanges;\n // Generally we should have hit one of the cases above, but it's possible\n // to get here if there were only metadata docChanges and they got\n // stripped out.\n }\n xu(t) {\n t = oc.fromInitialDocuments(t.query, t.docs, t.mutatedKeys, t.fromCache, t.hasCachedResults), \n this.Vu = !0, this.vu.next(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */ class wc {\n constructor(t, \n // How many bytes this element takes to store in the bundle.\n e) {\n this.ku = t, this.byteLength = e;\n }\n Ou() {\n return \"metadata\" in this.ku;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */ class mc {\n constructor(t) {\n this.yt = t;\n }\n Ji(t) {\n return Qs(this.yt, t);\n }\n /**\n * Converts a BundleDocument to a MutableDocument.\n */ Yi(t) {\n return t.metadata.exists ? Ys(this.yt, t.document, !1) : Ze.newNoDocument(this.Ji(t.metadata.name), this.Xi(t.metadata.readTime));\n }\n Xi(t) {\n return qs(t);\n }\n}\n\n/**\n * A class to process the elements from a bundle, load them into local\n * storage and provide progress update while loading.\n */ class gc {\n constructor(t, e, n) {\n this.Mu = t, this.localStore = e, this.yt = n, \n /** Batched queries to be saved into storage */\n this.queries = [], \n /** Batched documents to be saved into storage */\n this.documents = [], \n /** The collection groups affected by this bundle. */\n this.collectionGroups = new Set, this.progress = yc(t);\n }\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */ Fu(t) {\n this.progress.bytesLoaded += t.byteLength;\n let e = this.progress.documentsLoaded;\n if (t.ku.namedQuery) this.queries.push(t.ku.namedQuery); else if (t.ku.documentMetadata) {\n this.documents.push({\n metadata: t.ku.documentMetadata\n }), t.ku.documentMetadata.exists || ++e;\n const n = rt.fromString(t.ku.documentMetadata.name);\n this.collectionGroups.add(n.get(n.length - 2));\n } else t.ku.document && (this.documents[this.documents.length - 1].document = t.ku.document, \n ++e);\n return e !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = e, \n Object.assign({}, this.progress)) : null;\n }\n $u(t) {\n const e = new Map, n = new mc(this.yt);\n for (const s of t) if (s.metadata.queries) {\n const t = n.Ji(s.metadata.name);\n for (const n of s.metadata.queries) {\n const s = (e.get(n) || Es()).add(t);\n e.set(n, s);\n }\n }\n return e;\n }\n /**\n * Update the progress to 'Success' and return the updated progress.\n */ async complete() {\n const t = await tu(this.localStore, new mc(this.yt), this.documents, this.Mu.id), e = this.$u(this.documents);\n for (const t of this.queries) await eu(this.localStore, t, e.get(t.name));\n return this.progress.taskState = \"Success\", {\n progress: this.progress,\n Bu: this.collectionGroups,\n Lu: t\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */ function yc(t) {\n return {\n taskState: \"Running\",\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: t.totalDocuments,\n totalBytes: t.totalBytes\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nclass pc {\n constructor(t) {\n this.key = t;\n }\n}\n\nclass Ic {\n constructor(t) {\n this.key = t;\n }\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */ class Tc {\n constructor(t, \n /** Documents included in the remote target */\n e) {\n this.query = t, this.qu = e, this.Uu = null, this.hasCachedResults = !1, \n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n this.current = !1, \n /** Documents in the view but not in the remote target */\n this.Ku = Es(), \n /** Document Keys that have local changes */\n this.mutatedKeys = Es(), this.Gu = bn(t), this.Qu = new ic(this.Gu);\n }\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */ get ju() {\n return this.qu;\n }\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */ Wu(t, e) {\n const n = e ? e.zu : new rc, s = e ? e.Qu : this.Qu;\n let i = e ? e.mutatedKeys : this.mutatedKeys, r = s, o = !1;\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const u = \"F\" /* LimitType.First */ === this.query.limitType && s.size === this.query.limit ? s.last() : null, c = \"L\" /* LimitType.Last */ === this.query.limitType && s.size === this.query.limit ? s.first() : null;\n // Drop documents out to meet limit/limitToLast requirement.\n if (t.inorderTraversal(((t, e) => {\n const a = s.get(t), h = An(this.query, e) ? e : null, l = !!a && this.mutatedKeys.has(a.key), f = !!h && (h.hasLocalMutations || \n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n this.mutatedKeys.has(h.key) && h.hasCommittedMutations);\n let d = !1;\n // Calculate change\n if (a && h) {\n a.data.isEqual(h.data) ? l !== f && (n.track({\n type: 3 /* ChangeType.Metadata */ ,\n doc: h\n }), d = !0) : this.Hu(a, h) || (n.track({\n type: 2 /* ChangeType.Modified */ ,\n doc: h\n }), d = !0, (u && this.Gu(h, u) > 0 || c && this.Gu(h, c) < 0) && (\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n o = !0));\n } else !a && h ? (n.track({\n type: 0 /* ChangeType.Added */ ,\n doc: h\n }), d = !0) : a && !h && (n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: a\n }), d = !0, (u || c) && (\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n o = !0));\n d && (h ? (r = r.add(h), i = f ? i.add(t) : i.delete(t)) : (r = r.delete(t), i = i.delete(t)));\n })), null !== this.query.limit) for (;r.size > this.query.limit; ) {\n const t = \"F\" /* LimitType.First */ === this.query.limitType ? r.last() : r.first();\n r = r.delete(t.key), i = i.delete(t.key), n.track({\n type: 1 /* ChangeType.Removed */ ,\n doc: t\n });\n }\n return {\n Qu: r,\n zu: n,\n $i: o,\n mutatedKeys: i\n };\n }\n Hu(t, e) {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return t.hasLocalMutations && e.hasCommittedMutations && !e.hasLocalMutations;\n }\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param updateLimboDocuments - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(t, e, n) {\n const s = this.Qu;\n this.Qu = t.Qu, this.mutatedKeys = t.mutatedKeys;\n // Sort changes based on type and query comparator\n const i = t.zu.Eu();\n i.sort(((t, e) => function(t, e) {\n const n = t => {\n switch (t) {\n case 0 /* ChangeType.Added */ :\n return 1;\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n\n case 1 /* ChangeType.Removed */ :\n return 0;\n\n default:\n return O();\n }\n };\n return n(t) - n(e);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t.type, e.type) || this.Gu(t.doc, e.doc))), this.Ju(n);\n const r = e ? this.Yu() : [], o = 0 === this.Ku.size && this.current ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , u = o !== this.Uu;\n if (this.Uu = o, 0 !== i.length || u) {\n return {\n snapshot: new oc(this.query, t.Qu, s, i, t.mutatedKeys, 0 /* SyncState.Local */ === o, u, \n /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0),\n Xu: r\n };\n }\n // no changes\n return {\n Xu: r\n };\n }\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */ bu(t) {\n return this.current && \"Offline\" /* OnlineState.Offline */ === t ? (\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = !1, this.applyChanges({\n Qu: this.Qu,\n zu: new rc,\n mutatedKeys: this.mutatedKeys,\n $i: !1\n }, \n /* updateLimboDocuments= */ !1)) : {\n Xu: []\n };\n }\n /**\n * Returns whether the doc for the given key should be in limbo.\n */ Zu(t) {\n // If the remote end says it's part of this query, it's not in limbo.\n return !this.qu.has(t) && (\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n !!this.Qu.has(t) && !this.Qu.get(t).hasLocalMutations);\n }\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */ Ju(t) {\n t && (t.addedDocuments.forEach((t => this.qu = this.qu.add(t))), t.modifiedDocuments.forEach((t => {})), \n t.removedDocuments.forEach((t => this.qu = this.qu.delete(t))), this.current = t.current);\n }\n Yu() {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) return [];\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const t = this.Ku;\n this.Ku = Es(), this.Qu.forEach((t => {\n this.Zu(t.key) && (this.Ku = this.Ku.add(t.key));\n }));\n // Diff the new limbo docs with the old limbo docs.\n const e = [];\n return t.forEach((t => {\n this.Ku.has(t) || e.push(new Ic(t));\n })), this.Ku.forEach((n => {\n t.has(n) || e.push(new pc(n));\n })), e;\n }\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n tc(t) {\n this.qu = t.Hi, this.Ku = Es();\n const e = this.Wu(t.documents);\n return this.applyChanges(e, /*updateLimboDocuments=*/ !0);\n }\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n ec() {\n return oc.fromInitialDocuments(this.query, this.Qu, this.mutatedKeys, 0 /* SyncState.Local */ === this.Uu, this.hasCachedResults);\n }\n}\n\n/**\n * QueryView contains all of the data that SyncEngine needs to keep track of for\n * a particular query.\n */\nclass Ec {\n constructor(\n /**\n * The query itself.\n */\n t, \n /**\n * The target number created by the client that is used in the watch\n * stream to identify this query.\n */\n e, \n /**\n * The view is responsible for computing the final merged truth of what\n * docs are in the query. It gets notified of local and remote changes,\n * and applies the query filters and limits to determine the most correct\n * possible results.\n */\n n) {\n this.query = t, this.targetId = e, this.view = n;\n }\n}\n\n/** Tracks a limbo resolution. */ class Ac {\n constructor(t) {\n this.key = t, \n /**\n * Set to true once we've received a document. This is used in\n * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to\n * decide whether it needs to manufacture a delete event for the target once\n * the target is CURRENT.\n */\n this.nc = !1;\n }\n}\n\n/**\n * An implementation of `SyncEngine` coordinating with other parts of SDK.\n *\n * The parts of SyncEngine that act as a callback to RemoteStore need to be\n * registered individually. This is done in `syncEngineWrite()` and\n * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods\n * serve as entry points to RemoteStore's functionality.\n *\n * Note: some field defined in this class might have public access level, but\n * the class is not exported so they are only accessible from this module.\n * This is useful to implement optional features (like bundles) in free\n * functions, such that they are tree-shakeable.\n */ class Rc {\n constructor(t, e, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n s, i, r) {\n this.localStore = t, this.remoteStore = e, this.eventManager = n, this.sharedClientState = s, \n this.currentUser = i, this.maxConcurrentLimboResolutions = r, this.sc = {}, this.ic = new ls((t => Tn(t)), In), \n this.rc = new Map, \n /**\n * The keys of documents that are in limbo for which we haven't yet started a\n * limbo resolution query. The strings in this set are the result of calling\n * `key.path.canonicalString()` where `key` is a `DocumentKey` object.\n *\n * The `Set` type was chosen because it provides efficient lookup and removal\n * of arbitrary elements and it also maintains insertion order, providing the\n * desired queue-like FIFO semantics.\n */\n this.oc = new Set, \n /**\n * Keeps track of the target ID for each document that is in limbo with an\n * active target.\n */\n this.uc = new Ge(ct.comparator), \n /**\n * Keeps track of the information about an active limbo resolution for each\n * active target ID that was started for the purpose of limbo resolution.\n */\n this.cc = new Map, this.ac = new Eo, \n /** Stores user completion handlers, indexed by User and BatchId. */\n this.hc = {}, \n /** Stores user callbacks waiting for all pending writes to be acknowledged. */\n this.lc = new Map, this.fc = Yr.vn(), this.onlineState = \"Unknown\" /* OnlineState.Unknown */ , \n // The primary state is set to `true` or `false` immediately after Firestore\n // startup. In the interim, a client should only be considered primary if\n // `isPrimary` is true.\n this.dc = void 0;\n }\n get isPrimaryClient() {\n return !0 === this.dc;\n }\n}\n\n/**\n * Initiates the new listen, resolves promise when listen enqueued to the\n * server. All the subsequent view snapshots or errors are sent to the\n * subscribed handlers. Returns the initial snapshot.\n */\nasync function bc(t, e) {\n const n = ta(t);\n let s, i;\n const r = n.ic.get(e);\n if (r) \n // PORTING NOTE: With Multi-Tab Web, it is possible that a query view\n // already exists when EventManager calls us for the first time. This\n // happens when the primary tab is already listening to this query on\n // behalf of another tab and the user of the primary also starts listening\n // to the query. EventManager will not have an assigned target ID in this\n // case and calls `listen` to obtain this ID.\n s = r.targetId, n.sharedClientState.addLocalQueryTarget(s), i = r.view.ec(); else {\n const t = await zo(n.localStore, gn(e));\n n.isPrimaryClient && Du(n.remoteStore, t);\n const r = n.sharedClientState.addLocalQueryTarget(t.targetId);\n s = t.targetId, i = await Pc(n, e, s, \"current\" === r, t.resumeToken);\n }\n return i;\n}\n\n/**\n * Registers a view for a previously unknown query and computes its initial\n * snapshot.\n */ async function Pc(t, e, n, s, i) {\n // PORTING NOTE: On Web only, we inject the code that registers new Limbo\n // targets based on view changes. This allows us to only depend on Limbo\n // changes when user code includes queries.\n t._c = (e, n, s) => async function(t, e, n, s) {\n let i = e.view.Wu(n);\n i.$i && (\n // The query has a limit and some docs were removed, so we need\n // to re-run the query against the local store to make sure we\n // didn't lose any good docs that had been past the limit.\n i = await Jo(t.localStore, e.query, \n /* usePreviousResults= */ !1).then((({documents: t}) => e.view.Wu(t, i))));\n const r = s && s.targetChanges.get(e.targetId), o = e.view.applyChanges(i, \n /* updateLimboDocuments= */ t.isPrimaryClient, r);\n return Bc(t, e.targetId, o.Xu), o.snapshot;\n }(t, e, n, s);\n const r = await Jo(t.localStore, e, \n /* usePreviousResults= */ !0), o = new Tc(e, r.Hi), u = o.Wu(r.documents), c = Ps.createSynthesizedTargetChangeForCurrentChange(n, s && \"Offline\" /* OnlineState.Offline */ !== t.onlineState, i), a = o.applyChanges(u, \n /* updateLimboDocuments= */ t.isPrimaryClient, c);\n Bc(t, n, a.Xu);\n const h = new Ec(e, n, o);\n return t.ic.set(e, h), t.rc.has(n) ? t.rc.get(n).push(e) : t.rc.set(n, [ e ]), a.snapshot;\n}\n\n/** Stops listening to the query. */ async function vc(t, e) {\n const n = $(t), s = n.ic.get(e), i = n.rc.get(s.targetId);\n if (i.length > 1) return n.rc.set(s.targetId, i.filter((t => !In(t, e)))), void n.ic.delete(e);\n // No other queries are mapped to the target, clean up the query and the target.\n if (n.isPrimaryClient) {\n // We need to remove the local query target first to allow us to verify\n // whether any other client is still interested in this target.\n n.sharedClientState.removeLocalQueryTarget(s.targetId);\n n.sharedClientState.isActiveQueryTarget(s.targetId) || await Ho(n.localStore, s.targetId, \n /*keepPersistedTargetData=*/ !1).then((() => {\n n.sharedClientState.clearQueryState(s.targetId), Cu(n.remoteStore, s.targetId), \n Fc(n, s.targetId);\n })).catch(Et);\n } else Fc(n, s.targetId), await Ho(n.localStore, s.targetId, \n /*keepPersistedTargetData=*/ !0);\n}\n\n/**\n * Initiates the write of local mutation batch which involves adding the\n * writes to the mutation queue, notifying the remote store about new\n * mutations and raising events for any changes this write caused.\n *\n * The promise returned by this call is resolved when the above steps\n * have completed, *not* when the write was acked by the backend. The\n * userCallback is resolved once the write was acked/rejected by the\n * backend (or failed locally for any other reason).\n */ async function Vc(t, e, n) {\n const s = ea(t);\n try {\n const t = await function(t, e) {\n const n = $(t), s = nt.now(), i = e.reduce(((t, e) => t.add(e.key)), Es());\n let r, o;\n return n.persistence.runTransaction(\"Locally write mutations\", \"readwrite\", (t => {\n // Figure out which keys do not have a remote version in the cache, this\n // is needed to create the right overlay mutation: if no remote version\n // presents, we do not need to create overlays as patch mutations.\n // TODO(Overlay): Is there a better way to determine this? Using the\n // document version does not work because local mutations set them back\n // to 0.\n let u = ds(), c = Es();\n return n.Gi.getEntries(t, i).next((t => {\n u = t, u.forEach(((t, e) => {\n e.isValidDocument() || (c = c.add(t));\n }));\n })).next((() => n.localDocuments.getOverlayedDocuments(t, u))).next((i => {\n r = i;\n // For non-idempotent mutations (such as `FieldValue.increment()`),\n // we record the base state in a separate patch mutation. This is\n // later used to guarantee consistent values and prevents flicker\n // even if the backend sends us an update that already includes our\n // transform.\n const o = [];\n for (const t of e) {\n const e = Yn(t, r.get(t.key).overlayedDocument);\n null != e && \n // NOTE: The base state should only be applied if there's some\n // existing document to override, so use a Precondition of\n // exists=true\n o.push(new ts(t.key, e, Xe(e.value.mapValue), Qn.exists(!0)));\n }\n return n.mutationQueue.addMutationBatch(t, s, o, e);\n })).next((e => {\n o = e;\n const s = e.applyToLocalDocumentSet(r, c);\n return n.documentOverlayCache.saveOverlays(t, e.batchId, s);\n }));\n })).then((() => ({\n batchId: o.batchId,\n changes: ms(r)\n })));\n }(s.localStore, e);\n s.sharedClientState.addPendingMutation(t.batchId), function(t, e, n) {\n let s = t.hc[t.currentUser.toKey()];\n s || (s = new Ge(Z));\n s = s.insert(e, n), t.hc[t.currentUser.toKey()] = s;\n }\n /**\n * Resolves or rejects the user callback for the given batch and then discards\n * it.\n */ (s, t.batchId, n), await Uc(s, t.changes), await Ku(s.remoteStore);\n } catch (t) {\n // If we can't persist the mutation, we reject the user callback and\n // don't send the mutation. The user can then retry the write.\n const e = sc(t, \"Failed to persist write\");\n n.reject(e);\n }\n}\n\n/**\n * Applies one remote event to the sync engine, notifying any views of the\n * changes, and releasing any pending mutation batches that would become\n * visible because of the snapshot version the remote event contains.\n */ async function Sc(t, e) {\n const n = $(t);\n try {\n const t = await Qo(n.localStore, e);\n // Update `receivedDocument` as appropriate for any limbo targets.\n e.targetChanges.forEach(((t, e) => {\n const s = n.cc.get(e);\n s && (\n // Since this is a limbo resolution lookup, it's for a single document\n // and it could be added, modified, or removed, but not a combination.\n M(t.addedDocuments.size + t.modifiedDocuments.size + t.removedDocuments.size <= 1), \n t.addedDocuments.size > 0 ? s.nc = !0 : t.modifiedDocuments.size > 0 ? M(s.nc) : t.removedDocuments.size > 0 && (M(s.nc), \n s.nc = !1));\n })), await Uc(n, t, e);\n } catch (t) {\n await Et(t);\n }\n}\n\n/**\n * Applies an OnlineState change to the sync engine and notifies any views of\n * the change.\n */ function Dc(t, e, n) {\n const s = $(t);\n // If we are the secondary client, we explicitly ignore the remote store's\n // online state (the local client may go offline, even though the primary\n // tab remains online) and only apply the primary tab's online state from\n // SharedClientState.\n if (s.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !s.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) {\n const t = [];\n s.ic.forEach(((n, s) => {\n const i = s.view.bu(e);\n i.snapshot && t.push(i.snapshot);\n })), function(t, e) {\n const n = $(t);\n n.onlineState = e;\n let s = !1;\n n.queries.forEach(((t, n) => {\n for (const t of n.listeners) \n // Run global snapshot listeners if a consistent snapshot has been emitted.\n t.bu(e) && (s = !0);\n })), s && dc(n);\n }(s.eventManager, e), t.length && s.sc.Wo(t), s.onlineState = e, s.isPrimaryClient && s.sharedClientState.setOnlineState(e);\n }\n}\n\n/**\n * Rejects the listen for the given targetID. This can be triggered by the\n * backend for any active target.\n *\n * @param syncEngine - The sync engine implementation.\n * @param targetId - The targetID corresponds to one previously initiated by the\n * user as part of TargetData passed to listen() on RemoteStore.\n * @param err - A description of the condition that has forced the rejection.\n * Nearly always this will be an indication that the user is no longer\n * authorized to see the data matching the target.\n */ async function Cc(t, e, n) {\n const s = $(t);\n // PORTING NOTE: Multi-tab only.\n s.sharedClientState.updateQueryState(e, \"rejected\", n);\n const i = s.cc.get(e), r = i && i.key;\n if (r) {\n // TODO(klimt): We really only should do the following on permission\n // denied errors, but we don't have the cause code here.\n // It's a limbo doc. Create a synthetic event saying it was deleted.\n // This is kind of a hack. Ideally, we would have a method in the local\n // store to purge a document. However, it would be tricky to keep all of\n // the local store's invariants with another method.\n let t = new Ge(ct.comparator);\n // TODO(b/217189216): This limbo document should ideally have a read time,\n // so that it is picked up by any read-time based scans. The backend,\n // however, does not send a read time for target removals.\n t = t.insert(r, Ze.newNoDocument(r, st.min()));\n const n = Es().add(r), i = new bs(st.min(), \n /* targetChanges= */ new Map, \n /* targetMismatches= */ new We(Z), t, n);\n await Sc(s, i), \n // Since this query failed, we won't want to manually unlisten to it.\n // We only remove it from bookkeeping after we successfully applied the\n // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to\n // this query when the RemoteStore restarts the Watch stream, which should\n // re-trigger the target failure.\n s.uc = s.uc.remove(r), s.cc.delete(e), qc(s);\n } else await Ho(s.localStore, e, \n /* keepPersistedTargetData */ !1).then((() => Fc(s, e, n))).catch(Et);\n}\n\nasync function xc(t, e) {\n const n = $(t), s = e.batch.batchId;\n try {\n const t = await Ko(n.localStore, e);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught\n // up), so we raise user callbacks first so that they consistently happen\n // before listen events.\n Mc(n, s, /*error=*/ null), Oc(n, s), n.sharedClientState.updateMutationState(s, \"acknowledged\"), \n await Uc(n, t);\n } catch (t) {\n await Et(t);\n }\n}\n\nasync function Nc(t, e, n) {\n const s = $(t);\n try {\n const t = await function(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Reject batch\", \"readwrite-primary\", (t => {\n let s;\n return n.mutationQueue.lookupMutationBatch(t, e).next((e => (M(null !== e), s = e.keys(), \n n.mutationQueue.removeMutationBatch(t, e)))).next((() => n.mutationQueue.performConsistencyCheck(t))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(t, s, e))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(t, s))).next((() => n.localDocuments.getDocuments(t, s)));\n }));\n }\n /**\n * Returns the largest (latest) batch id in mutation queue that is pending\n * server response.\n *\n * Returns `BATCHID_UNKNOWN` if the queue is empty.\n */ (s.localStore, e);\n // The local store may or may not be able to apply the write result and\n // raise events immediately (depending on whether the watcher is caught up),\n // so we raise user callbacks first so that they consistently happen before\n // listen events.\n Mc(s, e, n), Oc(s, e), s.sharedClientState.updateMutationState(e, \"rejected\", n), \n await Uc(s, t);\n } catch (n) {\n await Et(n);\n }\n}\n\n/**\n * Registers a user callback that resolves when all pending mutations at the moment of calling\n * are acknowledged .\n */ async function kc(t, e) {\n const n = $(t);\n Mu(n.remoteStore) || C(\"SyncEngine\", \"The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled.\");\n try {\n const t = await function(t) {\n const e = $(t);\n return e.persistence.runTransaction(\"Get highest unacknowledged batch id\", \"readonly\", (t => e.mutationQueue.getHighestUnacknowledgedBatchId(t)));\n }(n.localStore);\n if (-1 === t) \n // Trigger the callback right away if there is no pending writes at the moment.\n return void e.resolve();\n const s = n.lc.get(t) || [];\n s.push(e), n.lc.set(t, s);\n } catch (t) {\n const n = sc(t, \"Initialization of waitForPendingWrites() operation failed\");\n e.reject(n);\n }\n}\n\n/**\n * Triggers the callbacks that are waiting for this batch id to get acknowledged by server,\n * if there are any.\n */ function Oc(t, e) {\n (t.lc.get(e) || []).forEach((t => {\n t.resolve();\n })), t.lc.delete(e);\n}\n\n/** Reject all outstanding callbacks waiting for pending writes to complete. */ function Mc(t, e, n) {\n const s = $(t);\n let i = s.hc[s.currentUser.toKey()];\n // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n if (i) {\n const t = i.get(e);\n t && (n ? t.reject(n) : t.resolve(), i = i.remove(e)), s.hc[s.currentUser.toKey()] = i;\n }\n}\n\nfunction Fc(t, e, n = null) {\n t.sharedClientState.removeLocalQueryTarget(e);\n for (const s of t.rc.get(e)) t.ic.delete(s), n && t.sc.wc(s, n);\n if (t.rc.delete(e), t.isPrimaryClient) {\n t.ac.ls(e).forEach((e => {\n t.ac.containsKey(e) || \n // We removed the last reference for this key\n $c(t, e);\n }));\n }\n}\n\nfunction $c(t, e) {\n t.oc.delete(e.path.canonicalString());\n // It's possible that the target already got removed because the query failed. In that case,\n // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target.\n const n = t.uc.get(e);\n null !== n && (Cu(t.remoteStore, n), t.uc = t.uc.remove(e), t.cc.delete(n), qc(t));\n}\n\nfunction Bc(t, e, n) {\n for (const s of n) if (s instanceof pc) t.ac.addReference(s.key, e), Lc(t, s); else if (s instanceof Ic) {\n C(\"SyncEngine\", \"Document no longer in limbo: \" + s.key), t.ac.removeReference(s.key, e);\n t.ac.containsKey(s.key) || \n // We removed the last reference for this key\n $c(t, s.key);\n } else O();\n}\n\nfunction Lc(t, e) {\n const n = e.key, s = n.path.canonicalString();\n t.uc.get(n) || t.oc.has(s) || (C(\"SyncEngine\", \"New document in limbo: \" + n), t.oc.add(s), \n qc(t));\n}\n\n/**\n * Starts listens for documents in limbo that are enqueued for resolution,\n * subject to a maximum number of concurrent resolutions.\n *\n * Without bounding the number of concurrent resolutions, the server can fail\n * with \"resource exhausted\" errors which can lead to pathological client\n * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683.\n */ function qc(t) {\n for (;t.oc.size > 0 && t.uc.size < t.maxConcurrentLimboResolutions; ) {\n const e = t.oc.values().next().value;\n t.oc.delete(e);\n const n = new ct(rt.fromString(e)), s = t.fc.next();\n t.cc.set(s, new Ac(n)), t.uc = t.uc.insert(n, s), Du(t.remoteStore, new zi(gn(ln(n.path)), s, 2 /* TargetPurpose.LimboResolution */ , Ot.at));\n }\n}\n\nasync function Uc(t, e, n) {\n const s = $(t), i = [], r = [], o = [];\n s.ic.isEmpty() || (s.ic.forEach(((t, u) => {\n o.push(s._c(u, e, n).then((t => {\n // Update views if there are actual changes.\n if (\n // If there are changes, or we are handling a global snapshot, notify\n // secondary clients to update query state.\n (t || n) && s.isPrimaryClient && s.sharedClientState.updateQueryState(u.targetId, (null == t ? void 0 : t.fromCache) ? \"not-current\" : \"current\"), \n t) {\n i.push(t);\n const e = $o.Ci(u.targetId, t);\n r.push(e);\n }\n })));\n })), await Promise.all(o), s.sc.Wo(i), await async function(t, e) {\n const n = $(t);\n try {\n await n.persistence.runTransaction(\"notifyLocalViewChanges\", \"readwrite\", (t => At.forEach(e, (e => At.forEach(e.Si, (s => n.persistence.referenceDelegate.addReference(t, e.targetId, s))).next((() => At.forEach(e.Di, (s => n.persistence.referenceDelegate.removeReference(t, e.targetId, s)))))))));\n } catch (t) {\n if (!Vt(t)) throw t;\n // If `notifyLocalViewChanges` fails, we did not advance the sequence\n // number for the documents that were included in this transaction.\n // This might trigger them to be deleted earlier than they otherwise\n // would have, but it should not invalidate the integrity of the data.\n C(\"LocalStore\", \"Failed to update sequence numbers: \" + t);\n }\n for (const t of e) {\n const e = t.targetId;\n if (!t.fromCache) {\n const t = n.qi.get(e), s = t.snapshotVersion, i = t.withLastLimboFreeSnapshotVersion(s);\n // Advance the last limbo free snapshot version\n n.qi = n.qi.insert(e, i);\n }\n }\n }(s.localStore, r));\n}\n\nasync function Kc(t, e) {\n const n = $(t);\n if (!n.currentUser.isEqual(e)) {\n C(\"SyncEngine\", \"User change. New user:\", e.toKey());\n const t = await Uo(n.localStore, e);\n n.currentUser = e, \n // Fails tasks waiting for pending writes requested by previous user.\n function(t, e) {\n t.lc.forEach((t => {\n t.forEach((t => {\n t.reject(new L(B.CANCELLED, e));\n }));\n })), t.lc.clear();\n }(n, \"'waitForPendingWrites' promise is rejected due to a user change.\"), \n // TODO(b/114226417): Consider calling this only in the primary tab.\n n.sharedClientState.handleUserChange(e, t.removedBatchIds, t.addedBatchIds), await Uc(n, t.ji);\n }\n}\n\nfunction Gc(t, e) {\n const n = $(t), s = n.cc.get(e);\n if (s && s.nc) return Es().add(s.key);\n {\n let t = Es();\n const s = n.rc.get(e);\n if (!s) return t;\n for (const e of s) {\n const s = n.ic.get(e);\n t = t.unionWith(s.view.ju);\n }\n return t;\n }\n}\n\n/**\n * Reconcile the list of synced documents in an existing view with those\n * from persistence.\n */ async function Qc(t, e) {\n const n = $(t), s = await Jo(n.localStore, e.query, \n /* usePreviousResults= */ !0), i = e.view.tc(s);\n return n.isPrimaryClient && Bc(n, e.targetId, i.Xu), i;\n}\n\n/**\n * Retrieves newly changed documents from remote document cache and raises\n * snapshots if needed.\n */\n// PORTING NOTE: Multi-Tab only.\nasync function jc(t, e) {\n const n = $(t);\n return Xo(n.localStore, e).then((t => Uc(n, t)));\n}\n\n/** Applies a mutation state to an existing batch. */\n// PORTING NOTE: Multi-Tab only.\nasync function Wc(t, e, n, s) {\n const i = $(t), r = await function(t, e) {\n const n = $(t), s = $(n.mutationQueue);\n return n.persistence.runTransaction(\"Lookup mutation documents\", \"readonly\", (t => s.Tn(t, e).next((e => e ? n.localDocuments.getDocuments(t, e) : At.resolve(null)))));\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, e);\n null !== r ? (\"pending\" === n ? \n // If we are the primary client, we need to send this write to the\n // backend. Secondary clients will ignore these writes since their remote\n // connection is disabled.\n await Ku(i.remoteStore) : \"acknowledged\" === n || \"rejected\" === n ? (\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n Mc(i, e, s || null), Oc(i, e), function(t, e) {\n $($(t).mutationQueue).An(e);\n }\n // PORTING NOTE: Multi-Tab only.\n (i.localStore, e)) : O(), await Uc(i, r)) : \n // A throttled tab may not have seen the mutation before it was completed\n // and removed from the mutation queue, in which case we won't have cached\n // the affected documents. In this case we can safely ignore the update\n // since that means we didn't apply the mutation locally at all (if we\n // had, we would have cached the affected documents), and so we will just\n // see any resulting document changes via normal remote document updates\n // as applicable.\n C(\"SyncEngine\", \"Cannot apply mutation batch with id: \" + e);\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function zc(t, e) {\n const n = $(t);\n if (ta(n), ea(n), !0 === e && !0 !== n.dc) {\n // Secondary tabs only maintain Views for their local listeners and the\n // Views internal state may not be 100% populated (in particular\n // secondary tabs don't track syncedDocuments, the set of documents the\n // server considers to be in the target). So when a secondary becomes\n // primary, we need to need to make sure that all views for all targets\n // match the state on disk.\n const t = n.sharedClientState.getAllActiveQueryTargets(), e = await Hc(n, t.toArray());\n n.dc = !0, await Zu(n.remoteStore, !0);\n for (const t of e) Du(n.remoteStore, t);\n } else if (!1 === e && !1 !== n.dc) {\n const t = [];\n let e = Promise.resolve();\n n.rc.forEach(((s, i) => {\n n.sharedClientState.isLocalQueryTarget(i) ? t.push(i) : e = e.then((() => (Fc(n, i), \n Ho(n.localStore, i, \n /*keepPersistedTargetData=*/ !0)))), Cu(n.remoteStore, i);\n })), await e, await Hc(n, t), \n // PORTING NOTE: Multi-Tab only.\n function(t) {\n const e = $(t);\n e.cc.forEach(((t, n) => {\n Cu(e.remoteStore, n);\n })), e.ac.fs(), e.cc = new Map, e.uc = new Ge(ct.comparator);\n }\n /**\n * Reconcile the query views of the provided query targets with the state from\n * persistence. Raises snapshots for any changes that affect the local\n * client and returns the updated state of all target's query data.\n *\n * @param syncEngine - The sync engine implementation\n * @param targets - the list of targets with views that need to be recomputed\n * @param transitionToPrimary - `true` iff the tab transitions from a secondary\n * tab to a primary tab\n */\n // PORTING NOTE: Multi-Tab only.\n (n), n.dc = !1, await Zu(n.remoteStore, !1);\n }\n}\n\nasync function Hc(t, e, n) {\n const s = $(t), i = [], r = [];\n for (const t of e) {\n let e;\n const n = s.rc.get(t);\n if (n && 0 !== n.length) {\n // For queries that have a local View, we fetch their current state\n // from LocalStore (as the resume token and the snapshot version\n // might have changed) and reconcile their views with the persisted\n // state (the list of syncedDocuments may have gotten out of sync).\n e = await zo(s.localStore, gn(n[0]));\n for (const t of n) {\n const e = s.ic.get(t), n = await Qc(s, e);\n n.snapshot && r.push(n.snapshot);\n }\n } else {\n // For queries that never executed on this client, we need to\n // allocate the target in LocalStore and initialize a new View.\n const n = await Yo(s.localStore, t);\n e = await zo(s.localStore, n), await Pc(s, Jc(n), t, \n /*current=*/ !1, e.resumeToken);\n }\n i.push(e);\n }\n return s.sc.Wo(r), i;\n}\n\n/**\n * Creates a `Query` object from the specified `Target`. There is no way to\n * obtain the original `Query`, so we synthesize a `Query` from the `Target`\n * object.\n *\n * The synthesized result might be different from the original `Query`, but\n * since the synthesized `Query` should return the same results as the\n * original one (only the presentation of results might differ), the potential\n * difference will not cause issues.\n */\n// PORTING NOTE: Multi-Tab only.\nfunction Jc(t) {\n return hn(t.path, t.collectionGroup, t.orderBy, t.filters, t.limit, \"F\" /* LimitType.First */ , t.startAt, t.endAt);\n}\n\n/** Returns the IDs of the clients that are currently active. */\n// PORTING NOTE: Multi-Tab only.\nfunction Yc(t) {\n const e = $(t);\n return $($(e.localStore).persistence).vi();\n}\n\n/** Applies a query target change from a different tab. */\n// PORTING NOTE: Multi-Tab only.\nasync function Xc(t, e, n, s) {\n const i = $(t);\n if (i.dc) \n // If we receive a target state notification via WebStorage, we are\n // either already secondary or another tab has taken the primary lease.\n return void C(\"SyncEngine\", \"Ignoring unexpected query state notification.\");\n const r = i.rc.get(e);\n if (r && r.length > 0) switch (n) {\n case \"current\":\n case \"not-current\":\n {\n const t = await Xo(i.localStore, Rn(r[0])), s = bs.createSynthesizedRemoteEventForCurrentChange(e, \"current\" === n, Qt.EMPTY_BYTE_STRING);\n await Uc(i, t, s);\n break;\n }\n\n case \"rejected\":\n await Ho(i.localStore, e, \n /* keepPersistedTargetData */ !0), Fc(i, e, s);\n break;\n\n default:\n O();\n }\n}\n\n/** Adds or removes Watch targets for queries from different tabs. */ async function Zc(t, e, n) {\n const s = ta(t);\n if (s.dc) {\n for (const t of e) {\n if (s.rc.has(t)) {\n // A target might have been added in a previous attempt\n C(\"SyncEngine\", \"Adding an already active target \" + t);\n continue;\n }\n const e = await Yo(s.localStore, t), n = await zo(s.localStore, e);\n await Pc(s, Jc(e), n.targetId, \n /*current=*/ !1, n.resumeToken), Du(s.remoteStore, n);\n }\n for (const t of n) \n // Check that the target is still active since the target might have been\n // removed if it has been rejected by the backend.\n s.rc.has(t) && \n // Release queries that are still active.\n await Ho(s.localStore, t, \n /* keepPersistedTargetData */ !1).then((() => {\n Cu(s.remoteStore, t), Fc(s, t);\n })).catch(Et);\n }\n}\n\nfunction ta(t) {\n const e = $(t);\n return e.remoteStore.remoteSyncer.applyRemoteEvent = Sc.bind(null, e), e.remoteStore.remoteSyncer.getRemoteKeysForTarget = Gc.bind(null, e), \n e.remoteStore.remoteSyncer.rejectListen = Cc.bind(null, e), e.sc.Wo = lc.bind(null, e.eventManager), \n e.sc.wc = fc.bind(null, e.eventManager), e;\n}\n\nfunction ea(t) {\n const e = $(t);\n return e.remoteStore.remoteSyncer.applySuccessfulWrite = xc.bind(null, e), e.remoteStore.remoteSyncer.rejectFailedWrite = Nc.bind(null, e), \n e;\n}\n\n/**\n * Loads a Firestore bundle into the SDK. The returned promise resolves when\n * the bundle finished loading.\n *\n * @param syncEngine - SyncEngine to use.\n * @param bundleReader - Bundle to load into the SDK.\n * @param task - LoadBundleTask used to update the loading progress to public API.\n */ function na(t, e, n) {\n const s = $(t);\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n (\n /** Loads a bundle and returns the list of affected collection groups. */\n async function(t, e, n) {\n try {\n const s = await e.getMetadata();\n if (await function(t, e) {\n const n = $(t), s = qs(e.createTime);\n return n.persistence.runTransaction(\"hasNewerBundle\", \"readonly\", (t => n.Ns.getBundleMetadata(t, e.id))).then((t => !!t && t.createTime.compareTo(s) >= 0));\n }\n /**\n * Saves the given `BundleMetadata` to local persistence.\n */ (t.localStore, s)) return await e.close(), n._completeWith(function(t) {\n return {\n taskState: \"Success\",\n documentsLoaded: t.totalDocuments,\n bytesLoaded: t.totalBytes,\n totalDocuments: t.totalDocuments,\n totalBytes: t.totalBytes\n };\n }(s)), Promise.resolve(new Set);\n n._updateProgress(yc(s));\n const i = new gc(s, t.localStore, e.yt);\n let r = await e.mc();\n for (;r; ) {\n const t = await i.Fu(r);\n t && n._updateProgress(t), r = await e.mc();\n }\n const o = await i.complete();\n return await Uc(t, o.Lu, \n /* remoteEvent */ void 0), \n // Save metadata, so loading the same bundle will skip.\n await function(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Save bundle\", \"readwrite\", (t => n.Ns.saveBundleMetadata(t, e)));\n }\n /**\n * Returns a promise of a `NamedQuery` associated with given query name. Promise\n * resolves to undefined if no persisted data can be found.\n */ (t.localStore, s), n._completeWith(o.progress), Promise.resolve(o.Bu);\n } catch (t) {\n return N(\"SyncEngine\", `Loading bundle failed with ${t}`), n._failWith(t), Promise.resolve(new Set);\n }\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Provides all components needed for Firestore with in-memory persistence.\n * Uses EagerGC garbage collection.\n */)(s, e, n).then((t => {\n s.sharedClientState.notifyBundleLoaded(t);\n }));\n}\n\nclass sa {\n constructor() {\n this.synchronizeTabs = !1;\n }\n async initialize(t) {\n this.yt = pu(t.databaseInfo.databaseId), this.sharedClientState = this.gc(t), this.persistence = this.yc(t), \n await this.persistence.start(), this.localStore = this.Ic(t), this.gcScheduler = this.Tc(t, this.localStore), \n this.indexBackfillerScheduler = this.Ec(t, this.localStore);\n }\n Tc(t, e) {\n return null;\n }\n Ec(t, e) {\n return null;\n }\n Ic(t) {\n return qo(this.persistence, new Bo, t.initialUser, this.yt);\n }\n yc(t) {\n return new Vo(Do.Bs, this.yt);\n }\n gc(t) {\n return new lu;\n }\n async terminate() {\n this.gcScheduler && this.gcScheduler.stop(), await this.sharedClientState.shutdown(), \n await this.persistence.shutdown();\n }\n}\n\n/**\n * Provides all components needed for Firestore with IndexedDB persistence.\n */ class ia extends sa {\n constructor(t, e, n) {\n super(), this.Ac = t, this.cacheSizeBytes = e, this.forceOwnership = n, this.synchronizeTabs = !1;\n }\n async initialize(t) {\n await super.initialize(t), await this.Ac.initialize(this, t), \n // Enqueue writes from a previous session\n await ea(this.Ac.syncEngine), await Ku(this.Ac.remoteStore), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.li((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), \n this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), \n Promise.resolve())));\n }\n Ic(t) {\n return qo(this.persistence, new Bo, t.initialUser, this.yt);\n }\n Tc(t, e) {\n const n = this.persistence.referenceDelegate.garbageCollector;\n return new io(n, t.asyncQueue, e);\n }\n Ec(t, e) {\n const n = new kt(e, this.persistence);\n return new Nt(t.asyncQueue, n);\n }\n yc(t) {\n const e = Fo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? Kr.withCacheSize(this.cacheSizeBytes) : Kr.DEFAULT;\n return new ko(this.synchronizeTabs, e, t.clientId, n, t.asyncQueue, gu(), yu(), this.yt, this.sharedClientState, !!this.forceOwnership);\n }\n gc(t) {\n return new lu;\n }\n}\n\n/**\n * Provides all components needed for Firestore with multi-tab IndexedDB\n * persistence.\n *\n * In the legacy client, this provider is used to provide both multi-tab and\n * non-multi-tab persistence since we cannot tell at build time whether\n * `synchronizeTabs` will be enabled.\n */ class ra extends ia {\n constructor(t, e) {\n super(t, e, /* forceOwnership= */ !1), this.Ac = t, this.cacheSizeBytes = e, this.synchronizeTabs = !0;\n }\n async initialize(t) {\n await super.initialize(t);\n const e = this.Ac.syncEngine;\n this.sharedClientState instanceof hu && (this.sharedClientState.syncEngine = {\n Fr: Wc.bind(null, e),\n $r: Xc.bind(null, e),\n Br: Zc.bind(null, e),\n vi: Yc.bind(null, e),\n Mr: jc.bind(null, e)\n }, await this.sharedClientState.start()), \n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n await this.persistence.li((async t => {\n await zc(this.Ac.syncEngine, t), this.gcScheduler && (t && !this.gcScheduler.started ? this.gcScheduler.start() : t || this.gcScheduler.stop()), \n this.indexBackfillerScheduler && (t && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : t || this.indexBackfillerScheduler.stop());\n }));\n }\n gc(t) {\n const e = gu();\n if (!hu.C(e)) throw new L(B.UNIMPLEMENTED, \"IndexedDB persistence is only available on platforms that support LocalStorage.\");\n const n = Fo(t.databaseInfo.databaseId, t.databaseInfo.persistenceKey);\n return new hu(e, t.asyncQueue, n, t.clientId, t.initialUser);\n }\n}\n\n/**\n * Initializes and wires the components that are needed to interface with the\n * network.\n */ class oa {\n async initialize(t, e) {\n this.localStore || (this.localStore = t.localStore, this.sharedClientState = t.sharedClientState, \n this.datastore = this.createDatastore(e), this.remoteStore = this.createRemoteStore(e), \n this.eventManager = this.createEventManager(e), this.syncEngine = this.createSyncEngine(e, \n /* startAsPrimary=*/ !t.synchronizeTabs), this.sharedClientState.onlineStateHandler = t => Dc(this.syncEngine, t, 1 /* OnlineStateSource.SharedClientState */), \n this.remoteStore.remoteSyncer.handleCredentialChange = Kc.bind(null, this.syncEngine), \n await Zu(this.remoteStore, this.syncEngine.isPrimaryClient));\n }\n createEventManager(t) {\n return new cc;\n }\n createDatastore(t) {\n const e = pu(t.databaseInfo.databaseId), n = (s = t.databaseInfo, new mu(s));\n var s;\n /** Return the Platform-specific connectivity monitor. */ return function(t, e, n, s) {\n return new Ru(t, e, n, s);\n }(t.authCredentials, t.appCheckCredentials, n, e);\n }\n createRemoteStore(t) {\n return e = this.localStore, n = this.datastore, s = t.asyncQueue, i = t => Dc(this.syncEngine, t, 0 /* OnlineStateSource.RemoteStore */), \n r = du.C() ? new du : new fu, new vu(e, n, s, i, r);\n var e, n, s, i, r;\n /** Re-enables the network. Idempotent. */ }\n createSyncEngine(t, e) {\n return function(t, e, n, \n // PORTING NOTE: Manages state synchronization in multi-tab environments.\n s, i, r, o) {\n const u = new Rc(t, e, n, s, i, r);\n return o && (u.dc = !0), u;\n }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, t.initialUser, t.maxConcurrentLimboResolutions, e);\n }\n terminate() {\n return async function(t) {\n const e = $(t);\n C(\"RemoteStore\", \"RemoteStore shutting down.\"), e._u.add(5 /* OfflineCause.Shutdown */), \n await Su(e), e.mu.shutdown(), \n // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n e.gu.set(\"Unknown\" /* OnlineState.Unknown */);\n }(this.remoteStore);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function ua(t, e, n) {\n if (!n) throw new L(B.INVALID_ARGUMENT, `Function ${t}() cannot be called with an empty ${e}.`);\n}\n\n/**\n * Validates that two boolean options are not set at the same time.\n * @internal\n */ function ca(t, e, n, s) {\n if (!0 === e && !0 === s) throw new L(B.INVALID_ARGUMENT, `${t} and ${n} cannot be used together.`);\n}\n\n/**\n * Validates that `path` refers to a document (indicated by the fact it contains\n * an even numbers of segments).\n */ function aa(t) {\n if (!ct.isDocumentKey(t)) throw new L(B.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`);\n}\n\n/**\n * Validates that `path` refers to a collection (indicated by the fact it\n * contains an odd numbers of segments).\n */ function ha(t) {\n if (ct.isDocumentKey(t)) throw new L(B.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`);\n}\n\n/**\n * Returns true if it's a non-null object without a custom prototype\n * (i.e. excludes Array, Date, etc.).\n */\n/** Returns a string describing the type / value of the provided input. */\nfunction la(t) {\n if (void 0 === t) return \"undefined\";\n if (null === t) return \"null\";\n if (\"string\" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), \n JSON.stringify(t);\n if (\"number\" == typeof t || \"boolean\" == typeof t) return \"\" + t;\n if (\"object\" == typeof t) {\n if (t instanceof Array) return \"an array\";\n {\n const e = \n /** try to get the constructor name for an object. */\n function(t) {\n if (t.constructor) return t.constructor.name;\n return null;\n }\n /**\n * Casts `obj` to `T`, optionally unwrapping Compat types to expose the\n * underlying instance. Throws if `obj` is not an instance of `T`.\n *\n * This cast is used in the Lite and Full SDK to verify instance types for\n * arguments passed to the public API.\n * @internal\n */ (t);\n return e ? `a custom ${e} object` : \"an object\";\n }\n }\n return \"function\" == typeof t ? \"a function\" : O();\n}\n\nfunction fa(t, \n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ne) {\n if (\"_delegate\" in t && (\n // Unwrap Compat types\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n t = t._delegate), !(t instanceof e)) {\n if (e.name === t.constructor.name) throw new L(B.INVALID_ARGUMENT, \"Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?\");\n {\n const n = la(t);\n throw new L(B.INVALID_ARGUMENT, `Expected type '${e.name}', but it was: ${n}`);\n }\n }\n return t;\n}\n\nfunction da(t, e) {\n if (e <= 0) throw new L(B.INVALID_ARGUMENT, `Function ${t}() requires a positive number, but it was: ${e}.`);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const _a = new Map;\n\n/**\n * An instance map that ensures only one Datastore exists per Firestore\n * instance.\n */\n/**\n * A concrete type describing all the values that can be applied via a\n * user-supplied `FirestoreSettings` object. This is a separate type so that\n * defaults can be supplied and the value can be checked for equality.\n */\nclass wa {\n constructor(t) {\n var e;\n if (void 0 === t.host) {\n if (void 0 !== t.ssl) throw new L(B.INVALID_ARGUMENT, \"Can't provide ssl option if host option is not set\");\n this.host = \"firestore.googleapis.com\", this.ssl = true;\n } else this.host = t.host, this.ssl = null === (e = t.ssl) || void 0 === e || e;\n if (this.credentials = t.credentials, this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, \n void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else {\n if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < 1048576) throw new L(B.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n this.cacheSizeBytes = t.cacheSizeBytes;\n }\n this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, \n this.useFetchStreams = !!t.useFetchStreams, ca(\"experimentalForceLongPolling\", t.experimentalForceLongPolling, \"experimentalAutoDetectLongPolling\", t.experimentalAutoDetectLongPolling);\n }\n isEqual(t) {\n return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */ class ma {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = n, \n this._app = s, \n /**\n * Whether it's a Firestore or Firestore Lite instance.\n */\n this.type = \"firestore-lite\", this._persistenceKey = \"(lite)\", this._settings = new wa({}), \n this._settingsFrozen = !1;\n }\n /**\n * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service\n * instance.\n */ get app() {\n if (!this._app) throw new L(B.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is not available\");\n return this._app;\n }\n get _initialized() {\n return this._settingsFrozen;\n }\n get _terminated() {\n return void 0 !== this._terminateTask;\n }\n _setSettings(t) {\n if (this._settingsFrozen) throw new L(B.FAILED_PRECONDITION, \"Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object.\");\n this._settings = new wa(t), void 0 !== t.credentials && (this._authCredentials = function(t) {\n if (!t) return new K;\n switch (t.type) {\n case \"gapi\":\n const e = t.client;\n return new W(e, t.sessionIndex || \"0\", t.iamToken || null, t.authTokenFactory || null);\n\n case \"provider\":\n return t.client;\n\n default:\n throw new L(B.INVALID_ARGUMENT, \"makeAuthCredentialsProvider failed due to invalid credential type\");\n }\n }(t.credentials));\n }\n _getSettings() {\n return this._settings;\n }\n _freezeSettings() {\n return this._settingsFrozen = !0, this._settings;\n }\n _delete() {\n return this._terminateTask || (this._terminateTask = this._terminate()), this._terminateTask;\n }\n /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() {\n return {\n app: this._app,\n databaseId: this._databaseId,\n settings: this._settings\n };\n }\n /**\n * Terminates all components used by this client. Subclasses can override\n * this method to clean up their own dependencies, but must also call this\n * method.\n *\n * Only ever called once.\n */ _terminate() {\n /**\n * Removes all components associated with the provided instance. Must be called\n * when the `Firestore` instance is terminated.\n */\n return function(t) {\n const e = _a.get(t);\n e && (C(\"ComponentProvider\", \"Removing Datastore\"), _a.delete(t), e.terminate());\n }(this), Promise.resolve();\n }\n}\n\n/**\n * Modify this instance to communicate with the Cloud Firestore emulator.\n *\n * Note: This must be called before this instance has been used to do any\n * operations.\n *\n * @param firestore - The `Firestore` instance to configure to connect to the\n * emulator.\n * @param host - the emulator host (ex: localhost).\n * @param port - the emulator port (ex: 9000).\n * @param options.mockUserToken - the mock auth token to use for unit testing\n * Security Rules.\n */ function ga(t, e, n, s = {}) {\n var i;\n const r = (t = fa(t, ma))._getSettings();\n if (\"firestore.googleapis.com\" !== r.host && r.host !== e && N(\"Host has been set in both settings() and useEmulator(), emulator host will be used\"), \n t._setSettings(Object.assign(Object.assign({}, r), {\n host: `${e}:${n}`,\n ssl: !1\n })), s.mockUserToken) {\n let e, n;\n if (\"string\" == typeof s.mockUserToken) e = s.mockUserToken, n = P.MOCK_USER; else {\n // Let createMockUserToken validate first (catches common mistakes like\n // invalid field \"uid\" and missing field \"sub\" / \"user_id\".)\n e = f(s.mockUserToken, null === (i = t._app) || void 0 === i ? void 0 : i.options.projectId);\n const r = s.mockUserToken.sub || s.mockUserToken.user_id;\n if (!r) throw new L(B.INVALID_ARGUMENT, \"mockUserToken must contain 'sub' or 'user_id' field!\");\n n = new P(r);\n }\n t._authCredentials = new G(new U(e, n));\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentReference` refers to a document location in a Firestore database\n * and can be used to write, read, or listen to the location. The document at\n * the referenced location may or may not exist.\n */ class ya {\n /** @hideconstructor */\n constructor(t, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n e, n) {\n this.converter = e, this._key = n, \n /** The type of this Firestore reference. */\n this.type = \"document\", this.firestore = t;\n }\n get _path() {\n return this._key.path;\n }\n /**\n * The document's identifier within its collection.\n */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced document (relative\n * to the root of the database).\n */ get path() {\n return this._key.path.canonicalString();\n }\n /**\n * The collection this `DocumentReference` belongs to.\n */ get parent() {\n return new Ia(this.firestore, this.converter, this._key.path.popLast());\n }\n withConverter(t) {\n return new ya(this.firestore, t, this._key);\n }\n}\n\n/**\n * A `Query` refers to a query which you can read or listen to. You can also\n * construct refined `Query` objects by adding filters and ordering.\n */ class pa {\n // This is the lite version of the Query class in the main SDK.\n /** @hideconstructor protected */\n constructor(t, \n /**\n * If provided, the `FirestoreDataConverter` associated with this instance.\n */\n e, n) {\n this.converter = e, this._query = n, \n /** The type of this Firestore reference. */\n this.type = \"query\", this.firestore = t;\n }\n withConverter(t) {\n return new pa(this.firestore, t, this._query);\n }\n}\n\n/**\n * A `CollectionReference` object can be used for adding documents, getting\n * document references, and querying for documents (using {@link query}).\n */ class Ia extends pa {\n /** @hideconstructor */\n constructor(t, e, n) {\n super(t, e, ln(n)), this._path = n, \n /** The type of this Firestore reference. */\n this.type = \"collection\";\n }\n /** The collection's identifier. */ get id() {\n return this._query.path.lastSegment();\n }\n /**\n * A string representing the path of the referenced collection (relative\n * to the root of the database).\n */ get path() {\n return this._query.path.canonicalString();\n }\n /**\n * A reference to the containing `DocumentReference` if this is a\n * subcollection. If this isn't a subcollection, the reference is null.\n */ get parent() {\n const t = this._path.popLast();\n return t.isEmpty() ? null : new ya(this.firestore, \n /* converter= */ null, new ct(t));\n }\n withConverter(t) {\n return new Ia(this.firestore, t, this._path);\n }\n}\n\nfunction Ta(t, e, ...n) {\n if (t = d(t), ua(\"collection\", \"path\", e), t instanceof ma) {\n const s = rt.fromString(e, ...n);\n return ha(s), new Ia(t, /* converter= */ null, s);\n }\n {\n if (!(t instanceof ya || t instanceof Ia)) throw new L(B.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const s = t._path.child(rt.fromString(e, ...n));\n return ha(s), new Ia(t.firestore, \n /* converter= */ null, s);\n }\n}\n\n// TODO(firestorelite): Consider using ErrorFactory -\n// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106\n/**\n * Creates and returns a new `Query` instance that includes all documents in the\n * database that are contained in a collection or subcollection with the\n * given `collectionId`.\n *\n * @param firestore - A reference to the root `Firestore` instance.\n * @param collectionId - Identifies the collections to query over. Every\n * collection or subcollection with this ID as the last segment of its path\n * will be included. Cannot contain a slash.\n * @returns The created `Query`.\n */ function Ea(t, e) {\n if (t = fa(t, ma), ua(\"collectionGroup\", \"collection id\", e), e.indexOf(\"/\") >= 0) throw new L(B.INVALID_ARGUMENT, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`);\n return new pa(t, \n /* converter= */ null, function(t) {\n return new an(rt.emptyPath(), t);\n }(e));\n}\n\nfunction Aa(t, e, ...n) {\n if (t = d(t), \n // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n 1 === arguments.length && (e = X.R()), ua(\"doc\", \"path\", e), t instanceof ma) {\n const s = rt.fromString(e, ...n);\n return aa(s), new ya(t, \n /* converter= */ null, new ct(s));\n }\n {\n if (!(t instanceof ya || t instanceof Ia)) throw new L(B.INVALID_ARGUMENT, \"Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore\");\n const s = t._path.child(rt.fromString(e, ...n));\n return aa(s), new ya(t.firestore, t instanceof Ia ? t.converter : null, new ct(s));\n }\n}\n\n/**\n * Returns true if the provided references are equal.\n *\n * @param left - A reference to compare.\n * @param right - A reference to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function Ra(t, e) {\n return t = d(t), e = d(e), (t instanceof ya || t instanceof Ia) && (e instanceof ya || e instanceof Ia) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter);\n}\n\n/**\n * Returns true if the provided queries point to the same collection and apply\n * the same constraints.\n *\n * @param left - A `Query` to compare.\n * @param right - A `Query` to compare.\n * @returns true if the references point to the same location in the same\n * Firestore database.\n */ function ba(t, e) {\n return t = d(t), e = d(e), t instanceof pa && e instanceof pa && (t.firestore === e.firestore && In(t._query, e._query) && t.converter === e.converter);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nfunction Pa(t, e = 10240) {\n let n = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read() {\n if (n < t.byteLength) {\n const s = {\n value: t.slice(n, n + e),\n done: !1\n };\n return n += e, s;\n }\n return {\n done: !0\n };\n },\n async cancel() {},\n releaseLock() {},\n closed: Promise.reject(\"unimplemented\")\n };\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/*\n * A wrapper implementation of Observer<T> that will dispatch events\n * asynchronously. To allow immediate silencing, a mute call is added which\n * causes events scheduled to no longer be raised.\n */\nclass va {\n constructor(t) {\n this.observer = t, \n /**\n * When set to true, will not raise future events. Necessary to deal with\n * async detachment of listener.\n */\n this.muted = !1;\n }\n next(t) {\n this.observer.next && this.Rc(this.observer.next, t);\n }\n error(t) {\n this.observer.error ? this.Rc(this.observer.error, t) : x(\"Uncaught Error in snapshot listener:\", t.toString());\n }\n bc() {\n this.muted = !0;\n }\n Rc(t, e) {\n this.muted || setTimeout((() => {\n this.muted || t(e);\n }), 0);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */ class Va {\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n t, e) {\n this.Pc = t, this.yt = e, \n /** Cached bundle metadata. */\n this.metadata = new q, \n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n this.buffer = new Uint8Array, this.vc = new TextDecoder(\"utf-8\"), \n // Read the metadata (which is the first element).\n this.Vc().then((t => {\n t && t.Ou() ? this.metadata.resolve(t.ku.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\\n ${JSON.stringify(null == t ? void 0 : t.ku)}`));\n }), (t => this.metadata.reject(t)));\n }\n close() {\n return this.Pc.cancel();\n }\n async getMetadata() {\n return this.metadata.promise;\n }\n async mc() {\n // Makes sure metadata is read before proceeding.\n return await this.getMetadata(), this.Vc();\n }\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */ async Vc() {\n const t = await this.Sc();\n if (null === t) return null;\n const e = this.vc.decode(t), n = Number(e);\n isNaN(n) && this.Dc(`length string (${e}) is not valid number`);\n const s = await this.Cc(n);\n return new wc(JSON.parse(s), t.length + n);\n }\n /** First index of '{' from the underlying buffer. */ xc() {\n return this.buffer.findIndex((t => t === \"{\".charCodeAt(0)));\n }\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */ async Sc() {\n for (;this.xc() < 0; ) {\n if (await this.Nc()) break;\n }\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (0 === this.buffer.length) return null;\n const t = this.xc();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n t < 0 && this.Dc(\"Reached the end of bundle when a length string is expected.\");\n const e = this.buffer.slice(0, t);\n // Update the internal buffer to drop the read length.\n return this.buffer = this.buffer.slice(t), e;\n }\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */ async Cc(t) {\n for (;this.buffer.length < t; ) {\n await this.Nc() && this.Dc(\"Reached the end of bundle when more is expected.\");\n }\n const e = this.vc.decode(this.buffer.slice(0, t));\n // Update the internal buffer to drop the read json string.\n return this.buffer = this.buffer.slice(t), e;\n }\n Dc(t) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n throw this.Pc.cancel(), new Error(`Invalid bundle format: ${t}`);\n }\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */ async Nc() {\n const t = await this.Pc.read();\n if (!t.done) {\n const e = new Uint8Array(this.buffer.length + t.value.length);\n e.set(this.buffer), e.set(t.value, this.buffer.length), this.buffer = e;\n }\n return t.done;\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nclass Sa {\n constructor() {\n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateField\";\n }\n}\n\n/**\n * The results of executing an aggregation query.\n */ class Da {\n /** @hideconstructor */\n constructor(t, e) {\n this._data = e, \n /** A type string to uniquely identify instances of this class. */\n this.type = \"AggregateQuerySnapshot\", this.query = t;\n }\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */ data() {\n return this._data;\n }\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * CountQueryRunner encapsulates the logic needed to run the count aggregation\n * queries.\n */ class Ca {\n constructor(t, e, n) {\n this.query = t, this.datastore = e, this.userDataWriter = n;\n }\n run() {\n return bu(this.datastore, this.query._query).then((t => {\n M(void 0 !== t[0]);\n const e = Object.entries(t[0]).filter((([t, e]) => \"count_alias\" === t)).map((([t, e]) => this.userDataWriter.convertValue(e)))[0];\n return M(\"number\" == typeof e), Promise.resolve(new Da(this.query, {\n count: e\n }));\n }));\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */ class xa {\n constructor(t) {\n this.datastore = t, \n // The version of each document that was read during this transaction.\n this.readVersions = new Map, this.mutations = [], this.committed = !1, \n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n this.lastWriteError = null, \n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n this.writtenDocs = new Set;\n }\n async lookup(t) {\n if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw new L(B.INVALID_ARGUMENT, \"Firestore transactions require all reads to be executed before all writes.\");\n const e = await async function(t, e) {\n const n = $(t), s = zs(n.yt) + \"/documents\", i = {\n documents: e.map((t => Gs(n.yt, t)))\n }, r = await n._o(\"BatchGetDocuments\", s, i, e.length), o = new Map;\n r.forEach((t => {\n const e = Xs(n.yt, t);\n o.set(e.key.toString(), e);\n }));\n const u = [];\n return e.forEach((t => {\n const e = o.get(t.toString());\n M(!!e), u.push(e);\n })), u;\n }(this.datastore, t);\n return e.forEach((t => this.recordVersion(t))), e;\n }\n set(t, e) {\n this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString());\n }\n update(t, e) {\n try {\n this.write(e.toMutation(t, this.preconditionForUpdate(t)));\n } catch (t) {\n this.lastWriteError = t;\n }\n this.writtenDocs.add(t.toString());\n }\n delete(t) {\n this.write(new is(t, this.precondition(t))), this.writtenDocs.add(t.toString());\n }\n async commit() {\n if (this.ensureCommitNotCalled(), this.lastWriteError) throw this.lastWriteError;\n const t = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach((e => {\n t.delete(e.key.toString());\n })), \n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n t.forEach(((t, e) => {\n const n = ct.fromPath(e);\n this.mutations.push(new rs(n, this.precondition(n)));\n })), await async function(t, e) {\n const n = $(t), s = zs(n.yt) + \"/documents\", i = {\n writes: e.map((t => ti(n.yt, t)))\n };\n await n.ao(\"Commit\", s, i);\n }(this.datastore, this.mutations), this.committed = !0;\n }\n recordVersion(t) {\n let e;\n if (t.isFoundDocument()) e = t.version; else {\n if (!t.isNoDocument()) throw O();\n // Represent a deleted doc using SnapshotVersion.min().\n e = st.min();\n }\n const n = this.readVersions.get(t.key.toString());\n if (n) {\n if (!e.isEqual(n)) \n // This transaction will fail no matter what.\n throw new L(B.ABORTED, \"Document version changed between two reads.\");\n } else this.readVersions.set(t.key.toString(), e);\n }\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */ precondition(t) {\n const e = this.readVersions.get(t.toString());\n return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(st.min()) ? Qn.exists(!1) : Qn.updateTime(e) : Qn.none();\n }\n /**\n * Returns the precondition for a document if the operation is an update.\n */ preconditionForUpdate(t) {\n const e = this.readVersions.get(t.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(t.toString()) && e) {\n if (e.isEqual(st.min())) \n // The document doesn't exist, so fail the transaction.\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new L(B.INVALID_ARGUMENT, \"Can't update a document that doesn't exist.\");\n // Document exists, base precondition on document update time.\n return Qn.updateTime(e);\n }\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Qn.exists(!0);\n }\n write(t) {\n this.ensureCommitNotCalled(), this.mutations.push(t);\n }\n ensureCommitNotCalled() {}\n}\n\n/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */ class Na {\n constructor(t, e, n, s, i) {\n this.asyncQueue = t, this.datastore = e, this.options = n, this.updateFunction = s, \n this.deferred = i, this.kc = n.maxAttempts, this.xo = new Iu(this.asyncQueue, \"transaction_retry\" /* TimerId.TransactionRetry */);\n }\n /** Runs the transaction and sets the result on deferred. */ run() {\n this.kc -= 1, this.Oc();\n }\n Oc() {\n this.xo.Ro((async () => {\n const t = new xa(this.datastore), e = this.Mc(t);\n e && e.then((e => {\n this.asyncQueue.enqueueAndForget((() => t.commit().then((() => {\n this.deferred.resolve(e);\n })).catch((t => {\n this.Fc(t);\n }))));\n })).catch((t => {\n this.Fc(t);\n }));\n }));\n }\n Mc(t) {\n try {\n const e = this.updateFunction(t);\n return !qt(e) && e.catch && e.then ? e : (this.deferred.reject(Error(\"Transaction callback must return a Promise\")), \n null);\n } catch (t) {\n // Do not retry errors thrown by user provided updateFunction.\n return this.deferred.reject(t), null;\n }\n }\n Fc(t) {\n this.kc > 0 && this.$c(t) ? (this.kc -= 1, this.asyncQueue.enqueueAndForget((() => (this.Oc(), \n Promise.resolve())))) : this.deferred.reject(t);\n }\n $c(t) {\n if (\"FirebaseError\" === t.name) {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const e = t.code;\n return \"aborted\" === e || \"failed-precondition\" === e || \"already-exists\" === e || !as(e);\n }\n return !1;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * FirestoreClient is a top-level class that constructs and owns all of the\n * pieces of the client SDK architecture. It is responsible for creating the\n * async queue that is shared by all of the other components in the system.\n */\nclass ka {\n constructor(t, e, \n /**\n * Asynchronous queue responsible for all of our internal processing. When\n * we get incoming work from the user (via public API) or the network\n * (incoming GRPC messages), we should always schedule onto this queue.\n * This ensures all of our work is properly serialized (e.g. we don't\n * start processing a new operation while the previous one is waiting for\n * an async I/O to complete).\n */\n n, s) {\n this.authCredentials = t, this.appCheckCredentials = e, this.asyncQueue = n, this.databaseInfo = s, \n this.user = P.UNAUTHENTICATED, this.clientId = X.R(), this.authCredentialListener = () => Promise.resolve(), \n this.appCheckCredentialListener = () => Promise.resolve(), this.authCredentials.start(n, (async t => {\n C(\"FirestoreClient\", \"Received user=\", t.uid), await this.authCredentialListener(t), \n this.user = t;\n })), this.appCheckCredentials.start(n, (t => (C(\"FirestoreClient\", \"Received new app check token=\", t), \n this.appCheckCredentialListener(t, this.user))));\n }\n async getConfiguration() {\n return {\n asyncQueue: this.asyncQueue,\n databaseInfo: this.databaseInfo,\n clientId: this.clientId,\n authCredentials: this.authCredentials,\n appCheckCredentials: this.appCheckCredentials,\n initialUser: this.user,\n maxConcurrentLimboResolutions: 100\n };\n }\n setCredentialChangeListener(t) {\n this.authCredentialListener = t;\n }\n setAppCheckTokenChangeListener(t) {\n this.appCheckCredentialListener = t;\n }\n /**\n * Checks that the client has not been terminated. Ensures that other methods on\n * this class cannot be called after the client is terminated.\n */ verifyNotTerminated() {\n if (this.asyncQueue.isShuttingDown) throw new L(B.FAILED_PRECONDITION, \"The client has already been terminated.\");\n }\n terminate() {\n this.asyncQueue.enterRestrictedMode();\n const t = new q;\n return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n this.onlineComponents && await this.onlineComponents.terminate(), this.offlineComponents && await this.offlineComponents.terminate(), \n // The credentials provider must be terminated after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving auth\n // tokens.\n this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), t.resolve();\n } catch (e) {\n const n = sc(e, \"Failed to shutdown persistence\");\n t.reject(n);\n }\n })), t.promise;\n }\n}\n\nasync function Oa(t, e) {\n t.asyncQueue.verifyOperationInProgress(), C(\"FirestoreClient\", \"Initializing OfflineComponentProvider\");\n const n = await t.getConfiguration();\n await e.initialize(n);\n let s = n.initialUser;\n t.setCredentialChangeListener((async t => {\n s.isEqual(t) || (await Uo(e.localStore, t), s = t);\n })), \n // When a user calls clearPersistence() in one client, all other clients\n // need to be terminated to allow the delete to succeed.\n e.persistence.setDatabaseDeletedListener((() => t.terminate())), t.offlineComponents = e;\n}\n\nasync function Ma(t, e) {\n t.asyncQueue.verifyOperationInProgress();\n const n = await Fa(t);\n C(\"FirestoreClient\", \"Initializing OnlineComponentProvider\");\n const s = await t.getConfiguration();\n await e.initialize(n, s), \n // The CredentialChangeListener of the online component provider takes\n // precedence over the offline component provider.\n t.setCredentialChangeListener((t => Xu(e.remoteStore, t))), t.setAppCheckTokenChangeListener(((t, n) => Xu(e.remoteStore, n))), \n t.onlineComponents = e;\n}\n\nasync function Fa(t) {\n return t.offlineComponents || (C(\"FirestoreClient\", \"Using default OfflineComponentProvider\"), \n await Oa(t, new sa)), t.offlineComponents;\n}\n\nasync function $a(t) {\n return t.onlineComponents || (C(\"FirestoreClient\", \"Using default OnlineComponentProvider\"), \n await Ma(t, new oa)), t.onlineComponents;\n}\n\nfunction Ba(t) {\n return Fa(t).then((t => t.persistence));\n}\n\nfunction La(t) {\n return Fa(t).then((t => t.localStore));\n}\n\nfunction qa(t) {\n return $a(t).then((t => t.remoteStore));\n}\n\nfunction Ua(t) {\n return $a(t).then((t => t.syncEngine));\n}\n\nfunction Ka(t) {\n return $a(t).then((t => t.datastore));\n}\n\nasync function Ga(t) {\n const e = await $a(t), n = e.eventManager;\n return n.onListen = bc.bind(null, e.syncEngine), n.onUnlisten = vc.bind(null, e.syncEngine), \n n;\n}\n\n/** Enables the network connection and re-enqueues all pending operations. */ function Qa(t) {\n return t.asyncQueue.enqueue((async () => {\n const e = await Ba(t), n = await qa(t);\n return e.setNetworkEnabled(!0), function(t) {\n const e = $(t);\n return e._u.delete(0 /* OfflineCause.UserDisabled */), Vu(e);\n }(n);\n }));\n}\n\n/** Disables the network connection. Pending operations will not complete. */ function ja(t) {\n return t.asyncQueue.enqueue((async () => {\n const e = await Ba(t), n = await qa(t);\n return e.setNetworkEnabled(!1), async function(t) {\n const e = $(t);\n e._u.add(0 /* OfflineCause.UserDisabled */), await Su(e), \n // Set the OnlineState to Offline so get()s return from cache, etc.\n e.gu.set(\"Offline\" /* OnlineState.Offline */);\n }(n);\n }));\n}\n\n/**\n * Returns a Promise that resolves when all writes that were pending at the time\n * this method was called received server acknowledgement. An acknowledgement\n * can be either acceptance or rejection.\n */ function Wa(t, e) {\n const n = new q;\n return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {\n try {\n const s = await function(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"read document\", \"readonly\", (t => n.localDocuments.getDocument(t, e)));\n }(t, e);\n s.isFoundDocument() ? n.resolve(s) : s.isNoDocument() ? n.resolve(null) : n.reject(new L(B.UNAVAILABLE, \"Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)\"));\n } catch (t) {\n const s = sc(t, `Failed to get document '${e} from cache`);\n n.reject(s);\n }\n }\n /**\n * Retrieves a latency-compensated document from the backend via a\n * SnapshotListener.\n */ (await La(t), e, n))), n.promise;\n}\n\nfunction za(t, e, n = {}) {\n const s = new q;\n return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {\n const r = new va({\n next: r => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n e.enqueueAndForget((() => hc(t, o)));\n const u = r.docs.has(n);\n !u && r.fromCache ? \n // TODO(dimond): If we're online and the document doesn't\n // exist then we resolve with a doc.exists set to false. If\n // we're offline however, we reject the Promise in this\n // case. Two options: 1) Cache the negative response from\n // the server so we can deliver that even when you're\n // offline 2) Actually reject the Promise in the online case\n // if the document doesn't exist.\n i.reject(new L(B.UNAVAILABLE, \"Failed to get document because the client is offline.\")) : u && r.fromCache && s && \"server\" === s.source ? i.reject(new L(B.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to \"server\" to retrieve the cached document.)')) : i.resolve(r);\n },\n error: t => i.reject(t)\n }), o = new _c(ln(n.path), r, {\n includeMetadataChanges: !0,\n Nu: !0\n });\n return ac(t, o);\n }(await Ga(t), t.asyncQueue, e, n, s))), s.promise;\n}\n\nfunction Ha(t, e) {\n const n = new q;\n return t.asyncQueue.enqueueAndForget((async () => async function(t, e, n) {\n try {\n const s = await Jo(t, e, \n /* usePreviousResults= */ !0), i = new Tc(e, s.Hi), r = i.Wu(s.documents), o = i.applyChanges(r, \n /* updateLimboDocuments= */ !1);\n n.resolve(o.snapshot);\n } catch (t) {\n const s = sc(t, `Failed to execute query '${e} against cache`);\n n.reject(s);\n }\n }\n /**\n * Retrieves a latency-compensated query snapshot from the backend via a\n * SnapshotListener.\n */ (await La(t), e, n))), n.promise;\n}\n\nfunction Ja(t, e, n = {}) {\n const s = new q;\n return t.asyncQueue.enqueueAndForget((async () => function(t, e, n, s, i) {\n const r = new va({\n next: n => {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n e.enqueueAndForget((() => hc(t, o))), n.fromCache && \"server\" === s.source ? i.reject(new L(B.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to \"server\" to retrieve the cached documents.)')) : i.resolve(n);\n },\n error: t => i.reject(t)\n }), o = new _c(n, r, {\n includeMetadataChanges: !0,\n Nu: !0\n });\n return ac(t, o);\n }(await Ga(t), t.asyncQueue, e, n, s))), s.promise;\n}\n\nfunction Ya(t, e) {\n const n = new va(e);\n return t.asyncQueue.enqueueAndForget((async () => function(t, e) {\n $(t).Ru.add(e), \n // Immediately fire an initial event, indicating all existing listeners\n // are in-sync.\n e.next();\n }(await Ga(t), n))), () => {\n n.bc(), t.asyncQueue.enqueueAndForget((async () => function(t, e) {\n $(t).Ru.delete(e);\n }(await Ga(t), n)));\n };\n}\n\n/**\n * Takes an updateFunction in which a set of reads and writes can be performed\n * atomically. In the updateFunction, the client can read and write values\n * using the supplied transaction object. After the updateFunction, all\n * changes will be committed. If a retryable error occurs (ex: some other\n * client has changed any of the data referenced), then the updateFunction\n * will be called again after a backoff. If the updateFunction still fails\n * after all retries, then the transaction will be rejected.\n *\n * The transaction object passed to the updateFunction contains methods for\n * accessing documents and collections. Unlike other datastore access, data\n * accessed with the transaction will not reflect local changes that have not\n * been committed. For this reason, it is required that all reads are\n * performed before any writes. Transactions must be performed while online.\n */ function Xa(t, e, n, s) {\n const i = function(t, e) {\n let n;\n n = \"string\" == typeof t ? (new TextEncoder).encode(t) : t;\n return function(t, e) {\n return new Va(t, e);\n }(function(t, e) {\n if (t instanceof Uint8Array) return Pa(t, e);\n if (t instanceof ArrayBuffer) return Pa(new Uint8Array(t), e);\n if (t instanceof ReadableStream) return t.getReader();\n throw new Error(\"Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream\");\n }(n), e);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (n, pu(e));\n t.asyncQueue.enqueueAndForget((async () => {\n na(await Ua(t), i, s);\n }));\n}\n\nfunction Za(t, e) {\n return t.asyncQueue.enqueue((async () => function(t, e) {\n const n = $(t);\n return n.persistence.runTransaction(\"Get named query\", \"readonly\", (t => n.Ns.getNamedQuery(t, e)));\n }(await La(t), e)));\n}\n\nclass th {\n constructor() {\n // The last promise in the queue.\n this.Bc = Promise.resolve(), \n // A list of retryable operations. Retryable operations are run in order and\n // retried with backoff.\n this.Lc = [], \n // Is this AsyncQueue being shut down? Once it is set to true, it will not\n // be changed again.\n this.qc = !1, \n // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n this.Uc = [], \n // visible for testing\n this.Kc = null, \n // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n this.Gc = !1, \n // Enabled during shutdown on Safari to prevent future access to IndexedDB.\n this.Qc = !1, \n // List of TimerIds to fast-forward delays for.\n this.jc = [], \n // Backoff timer used to schedule retries for retryable operations\n this.xo = new Iu(this, \"async_queue_retry\" /* TimerId.AsyncQueueRetry */), \n // Visibility handler that triggers an immediate retry of all retryable\n // operations. Meant to speed up recovery when we regain file system access\n // after page comes into foreground.\n this.Wc = () => {\n const t = yu();\n t && C(\"AsyncQueue\", \"Visibility state changed to \" + t.visibilityState), this.xo.Po();\n };\n const t = yu();\n t && \"function\" == typeof t.addEventListener && t.addEventListener(\"visibilitychange\", this.Wc);\n }\n get isShuttingDown() {\n return this.qc;\n }\n /**\n * Adds a new operation to the queue without waiting for it to complete (i.e.\n * we ignore the Promise result).\n */ enqueueAndForget(t) {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.enqueue(t);\n }\n enqueueAndForgetEvenWhileRestricted(t) {\n this.zc(), \n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.Hc(t);\n }\n enterRestrictedMode(t) {\n if (!this.qc) {\n this.qc = !0, this.Qc = t || !1;\n const e = yu();\n e && \"function\" == typeof e.removeEventListener && e.removeEventListener(\"visibilitychange\", this.Wc);\n }\n }\n enqueue(t) {\n if (this.zc(), this.qc) \n // Return a Promise which never resolves.\n return new Promise((() => {}));\n // Create a deferred Promise that we can return to the callee. This\n // allows us to return a \"hanging Promise\" only to the callee and still\n // advance the queue even when the operation is not run.\n const e = new q;\n return this.Hc((() => this.qc && this.Qc ? Promise.resolve() : (t().then(e.resolve, e.reject), \n e.promise))).then((() => e.promise));\n }\n enqueueRetryable(t) {\n this.enqueueAndForget((() => (this.Lc.push(t), this.Jc())));\n }\n /**\n * Runs the next operation from the retryable queue. If the operation fails,\n * reschedules with backoff.\n */ async Jc() {\n if (0 !== this.Lc.length) {\n try {\n await this.Lc[0](), this.Lc.shift(), this.xo.reset();\n } catch (t) {\n if (!Vt(t)) throw t;\n // Failure will be handled by AsyncQueue\n C(\"AsyncQueue\", \"Operation failed with retryable error: \" + t);\n }\n this.Lc.length > 0 && \n // If there are additional operations, we re-schedule `retryNextOp()`.\n // This is necessary to run retryable operations that failed during\n // their initial attempt since we don't know whether they are already\n // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1`\n // needs to be re-run, we will run `op1`, `op1`, `op2` using the\n // already enqueued calls to `retryNextOp()`. `op3()` will then run in the\n // call scheduled here.\n // Since `backoffAndRun()` cancels an existing backoff and schedules a\n // new backoff on every call, there is only ever a single additional\n // operation in the queue.\n this.xo.Ro((() => this.Jc()));\n }\n }\n Hc(t) {\n const e = this.Bc.then((() => (this.Gc = !0, t().catch((t => {\n this.Kc = t, this.Gc = !1;\n const e = \n /**\n * Chrome includes Error.message in Error.stack. Other browsers do not.\n * This returns expected output of message + stack when available.\n * @param error - Error or FirestoreError\n */\n function(t) {\n let e = t.message || \"\";\n t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + \"\\n\" + t.stack);\n return e;\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ (t);\n // Re-throw the error so that this.tail becomes a rejected Promise and\n // all further attempts to chain (via .then) will just short-circuit\n // and return the rejected Promise.\n throw x(\"INTERNAL UNHANDLED ERROR: \", e), t;\n })).then((t => (this.Gc = !1, t))))));\n return this.Bc = e, e;\n }\n enqueueAfterDelay(t, e, n) {\n this.zc(), \n // Fast-forward delays for timerIds that have been overriden.\n this.jc.indexOf(t) > -1 && (e = 0);\n const s = nc.createAndSchedule(this, t, e, n, (t => this.Yc(t)));\n return this.Uc.push(s), s;\n }\n zc() {\n this.Kc && O();\n }\n verifyOperationInProgress() {}\n /**\n * Waits until all currently queued tasks are finished executing. Delayed\n * operations are not run.\n */ async Xc() {\n // Operations in the queue prior to draining may have enqueued additional\n // operations. Keep draining the queue until the tail is no longer advanced,\n // which indicates that no more new operations were enqueued and that all\n // operations were executed.\n let t;\n do {\n t = this.Bc, await t;\n } while (t !== this.Bc);\n }\n /**\n * For Tests: Determine if a delayed operation with a particular TimerId\n * exists.\n */ Zc(t) {\n for (const e of this.Uc) if (e.timerId === t) return !0;\n return !1;\n }\n /**\n * For Tests: Runs some or all delayed operations early.\n *\n * @param lastTimerId - Delayed operations up to and including this TimerId\n * will be drained. Pass TimerId.All to run all delayed operations.\n * @returns a Promise that resolves once all operations have been run.\n */ ta(t) {\n // Note that draining may generate more delayed ops, so we do that first.\n return this.Xc().then((() => {\n // Run ops in the same order they'd run if they ran naturally.\n this.Uc.sort(((t, e) => t.targetTimeMs - e.targetTimeMs));\n for (const e of this.Uc) if (e.skipDelay(), \"all\" /* TimerId.All */ !== t && e.timerId === t) break;\n return this.Xc();\n }));\n }\n /**\n * For Tests: Skip all subsequent delays for a timer id.\n */ ea(t) {\n this.jc.push(t);\n }\n /** Called once a DelayedOperation is run or canceled. */ Yc(t) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n const e = this.Uc.indexOf(t);\n this.Uc.splice(e, 1);\n }\n}\n\nfunction eh(t) {\n /**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\n return function(t, e) {\n if (\"object\" != typeof t || null === t) return !1;\n const n = t;\n for (const t of e) if (t in n && \"function\" == typeof n[t]) return !0;\n return !1;\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise<LoadBundleTaskProgress>`.\n */ (t, [ \"next\", \"error\", \"complete\" ]);\n}\n\nclass nh {\n constructor() {\n this._progressObserver = {}, this._taskCompletionResolver = new q, this._lastProgress = {\n taskState: \"Running\",\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n }\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */ onProgress(t, e, n) {\n this._progressObserver = {\n next: t,\n error: e,\n complete: n\n };\n }\n /**\n * Implements the `Promise<LoadBundleTaskProgress>.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */ catch(t) {\n return this._taskCompletionResolver.promise.catch(t);\n }\n /**\n * Implements the `Promise<LoadBundleTaskProgress>.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */ then(t, e) {\n return this._taskCompletionResolver.promise.then(t, e);\n }\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */ _completeWith(t) {\n this._updateProgress(t), this._progressObserver.complete && this._progressObserver.complete(), \n this._taskCompletionResolver.resolve(t);\n }\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */ _failWith(t) {\n this._lastProgress.taskState = \"Error\", this._progressObserver.next && this._progressObserver.next(this._lastProgress), \n this._progressObserver.error && this._progressObserver.error(t), this._taskCompletionResolver.reject(t);\n }\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */ _updateProgress(t) {\n this._lastProgress = t, this._progressObserver.next && this._progressObserver.next(t);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/** DOMException error code constants. */ const sh = -1;\n\n/**\n * The Cloud Firestore service interface.\n *\n * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}.\n */\nclass ih extends ma {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n super(t, e, n, s), \n /**\n * Whether it's a {@link Firestore} or Firestore Lite instance.\n */\n this.type = \"firestore\", this._queue = new th, this._persistenceKey = (null == s ? void 0 : s.name) || \"[DEFAULT]\";\n }\n _terminate() {\n return this._firestoreClient || \n // The client must be initialized to ensure that all subsequent API\n // usage throws an exception.\n ch(this), this._firestoreClient.terminate();\n }\n}\n\n/**\n * Initializes a new instance of {@link Firestore} with the provided settings.\n * Can only be called before any other function, including\n * {@link (getFirestore:1)}. If the custom settings are empty, this function is\n * equivalent to calling {@link (getFirestore:1)}.\n *\n * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will\n * be associated.\n * @param settings - A settings object to configure the {@link Firestore} instance.\n * @param databaseId - The name of database.\n * @returns A newly initialized {@link Firestore} instance.\n */ function rh(t, e, n) {\n n || (n = \"(default)\");\n const s = _getProvider(t, \"firestore\");\n if (s.isInitialized(n)) {\n const t = s.getImmediate({\n identifier: n\n }), i = s.getOptions(n);\n if (_(i, e)) return t;\n throw new L(B.FAILED_PRECONDITION, \"initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance.\");\n }\n if (void 0 !== e.cacheSizeBytes && -1 !== e.cacheSizeBytes && e.cacheSizeBytes < 1048576) throw new L(B.INVALID_ARGUMENT, \"cacheSizeBytes must be at least 1048576\");\n return s.initialize({\n options: e,\n instanceIdentifier: n\n });\n}\n\nfunction oh(e, n) {\n const s = \"object\" == typeof e ? e : t(), i = \"string\" == typeof e ? e : n || \"(default)\", r = _getProvider(s, \"firestore\").getImmediate({\n identifier: i\n });\n if (!r._initialized) {\n const t = w(\"firestore\");\n t && ga(r, ...t);\n }\n return r;\n}\n\n/**\n * @internal\n */ function uh(t) {\n return t._firestoreClient || ch(t), t._firestoreClient.verifyNotTerminated(), t._firestoreClient;\n}\n\nfunction ch(t) {\n var e;\n const n = t._freezeSettings(), s = function(t, e, n, s) {\n return new Mt(t, e, n, s.host, s.ssl, s.experimentalForceLongPolling, s.experimentalAutoDetectLongPolling, s.useFetchStreams);\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // settings() defaults:\n (t._databaseId, (null === (e = t._app) || void 0 === e ? void 0 : e.options.appId) || \"\", t._persistenceKey, n);\n t._firestoreClient = new ka(t._authCredentials, t._appCheckCredentials, t._queue, s);\n}\n\n/**\n * Attempts to enable persistent storage, if possible.\n *\n * Must be called before any other functions (other than\n * {@link initializeFirestore}, {@link (getFirestore:1)} or\n * {@link clearIndexedDbPersistence}.\n *\n * If this fails, `enableIndexedDbPersistence()` will reject the promise it\n * returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @param persistenceSettings - Optional settings object to configure\n * persistence.\n * @returns A `Promise` that represents successfully enabling persistent storage.\n */ function ah(t, e) {\n ph(t = fa(t, ih));\n const n = uh(t), s = t._freezeSettings(), i = new oa;\n return lh(n, i, new ia(i, s.cacheSizeBytes, null == e ? void 0 : e.forceOwnership));\n}\n\n/**\n * Attempts to enable multi-tab persistent storage, if possible. If enabled\n * across all tabs, all operations share access to local persistence, including\n * shared execution of queries and latency-compensated local document updates\n * across all connected instances.\n *\n * If this fails, `enableMultiTabIndexedDbPersistence()` will reject the promise\n * it returns. Note that even after this failure, the {@link Firestore} instance will\n * remain usable, however offline persistence will be disabled.\n *\n * There are several reasons why this can fail, which can be identified by\n * the `code` on the error.\n *\n * * failed-precondition: The app is already open in another browser tab and\n * multi-tab is not enabled.\n * * unimplemented: The browser is incompatible with the offline\n * persistence implementation.\n *\n * @param firestore - The {@link Firestore} instance to enable persistence for.\n * @returns A `Promise` that represents successfully enabling persistent\n * storage.\n */ function hh(t) {\n ph(t = fa(t, ih));\n const e = uh(t), n = t._freezeSettings(), s = new oa;\n return lh(e, s, new ra(s, n.cacheSizeBytes));\n}\n\n/**\n * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`.\n * If the operation fails with a recoverable error (see\n * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected\n * but the client remains usable.\n */ function lh(t, e, n) {\n const s = new q;\n return t.asyncQueue.enqueue((async () => {\n try {\n await Oa(t, n), await Ma(t, e), s.resolve();\n } catch (t) {\n const e = t;\n if (!\n /**\n * Decides whether the provided error allows us to gracefully disable\n * persistence (as opposed to crashing the client).\n */\n function(t) {\n if (\"FirebaseError\" === t.name) return t.code === B.FAILED_PRECONDITION || t.code === B.UNIMPLEMENTED;\n if (\"undefined\" != typeof DOMException && t instanceof DOMException) \n // There are a few known circumstances where we can open IndexedDb but\n // trying to read/write will fail (e.g. quota exceeded). For\n // well-understood cases, we attempt to detect these and then gracefully\n // fall back to memory persistence.\n // NOTE: Rather than continue to add to this list, we could decide to\n // always fall back, with the risk that we might accidentally hide errors\n // representing actual SDK bugs.\n // When the browser is out of quota we could get either quota exceeded\n // or an aborted error depending on whether the error happened during\n // schema migration.\n return 22 === t.code || 20 === t.code || \n // Firefox Private Browsing mode disables IndexedDb and returns\n // INVALID_STATE for any usage.\n 11 === t.code;\n return !0;\n }\n /**\n * Clears the persistent storage. This includes pending writes and cached\n * documents.\n *\n * Must be called while the {@link Firestore} instance is not started (after the app is\n * terminated or when the app is first initialized). On startup, this function\n * must be called before other functions (other than {@link\n * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore}\n * instance is still running, the promise will be rejected with the error code\n * of `failed-precondition`.\n *\n * Note: `clearIndexedDbPersistence()` is primarily intended to help write\n * reliable tests that use Cloud Firestore. It uses an efficient mechanism for\n * dropping existing data but does not attempt to securely overwrite or\n * otherwise make cached data unrecoverable. For applications that are sensitive\n * to the disclosure of cached data in between user sessions, we strongly\n * recommend not enabling persistence at all.\n *\n * @param firestore - The {@link Firestore} instance to clear persistence for.\n * @returns A `Promise` that is resolved when the persistent storage is\n * cleared. Otherwise, the promise is rejected with an error.\n */ (e)) throw e;\n N(\"Error enabling offline persistence. Falling back to persistence disabled: \" + e), \n s.reject(e);\n }\n })).then((() => s.promise));\n}\n\nfunction fh(t) {\n if (t._initialized && !t._terminated) throw new L(B.FAILED_PRECONDITION, \"Persistence can only be cleared before a Firestore instance is initialized or after it is terminated.\");\n const e = new q;\n return t._queue.enqueueAndForgetEvenWhileRestricted((async () => {\n try {\n await async function(t) {\n if (!bt.C()) return Promise.resolve();\n const e = t + \"main\";\n await bt.delete(e);\n }\n /**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Compares two array for equality using comparator. The method computes the\n * intersection and invokes `onAdd` for every element that is in `after` but not\n * `before`. `onRemove` is invoked for every element in `before` but missing\n * from `after`.\n *\n * The method creates a copy of both `before` and `after` and runs in O(n log\n * n), where n is the size of the two lists.\n *\n * @param before - The elements that exist in the original array.\n * @param after - The elements to diff against the original array.\n * @param comparator - The comparator for the elements in before and after.\n * @param onAdd - A function to invoke for every element that is part of `\n * after` but not `before`.\n * @param onRemove - A function to invoke for every element that is part of\n * `before` but not `after`.\n */ (Fo(t._databaseId, t._persistenceKey)), e.resolve();\n } catch (t) {\n e.reject(t);\n }\n })), e.promise;\n}\n\n/**\n * Waits until all currently pending writes for the active user have been\n * acknowledged by the backend.\n *\n * The returned promise resolves immediately if there are no outstanding writes.\n * Otherwise, the promise waits for all previously issued writes (including\n * those written in a previous app session), but it does not wait for writes\n * that were added after the function is called. If you want to wait for\n * additional writes, call `waitForPendingWrites()` again.\n *\n * Any outstanding `waitForPendingWrites()` promises are rejected during user\n * changes.\n *\n * @returns A `Promise` which resolves when all currently pending writes have been\n * acknowledged by the backend.\n */ function dh(t) {\n return function(t) {\n const e = new q;\n return t.asyncQueue.enqueueAndForget((async () => kc(await Ua(t), e))), e.promise;\n }(uh(t = fa(t, ih)));\n}\n\n/**\n * Re-enables use of the network for this {@link Firestore} instance after a prior\n * call to {@link disableNetwork}.\n *\n * @returns A `Promise` that is resolved once the network has been enabled.\n */ function _h(t) {\n return Qa(uh(t = fa(t, ih)));\n}\n\n/**\n * Disables network usage for this instance. It can be re-enabled via {@link\n * enableNetwork}. While the network is disabled, any snapshot listeners,\n * `getDoc()` or `getDocs()` calls will return results from cache, and any write\n * operations will be queued until the network is restored.\n *\n * @returns A `Promise` that is resolved once the network has been disabled.\n */ function wh(t) {\n return ja(uh(t = fa(t, ih)));\n}\n\n/**\n * Terminates the provided {@link Firestore} instance.\n *\n * After calling `terminate()` only the `clearIndexedDbPersistence()` function\n * may be used. Any other function will throw a `FirestoreError`.\n *\n * To restart after termination, create a new instance of FirebaseFirestore with\n * {@link (getFirestore:1)}.\n *\n * Termination does not cancel any pending writes, and any promises that are\n * awaiting a response from the server will not be resolved. If you have\n * persistence enabled, the next time you start this instance, it will resume\n * sending these writes to the server.\n *\n * Note: Under normal circumstances, calling `terminate()` is not required. This\n * function is useful only when you want to force this instance to release all\n * of its resources or in combination with `clearIndexedDbPersistence()` to\n * ensure that all local state is destroyed between test runs.\n *\n * @returns A `Promise` that is resolved when the instance has been successfully\n * terminated.\n */ function mh(t) {\n return e(t.app, \"firestore\", t._databaseId.database), t._delete();\n}\n\n/**\n * Loads a Firestore bundle into the local cache.\n *\n * @param firestore - The {@link Firestore} instance to load bundles for.\n * @param bundleData - An object representing the bundle to be loaded. Valid\n * objects are `ArrayBuffer`, `ReadableStream<Uint8Array>` or `string`.\n *\n * @returns A `LoadBundleTask` object, which notifies callers with progress\n * updates, and completion or error events. It can be used as a\n * `Promise<LoadBundleTaskProgress>`.\n */ function gh(t, e) {\n const n = uh(t = fa(t, ih)), s = new nh;\n return Xa(n, t._databaseId, e, s), s;\n}\n\n/**\n * Reads a Firestore {@link Query} from local cache, identified by the given\n * name.\n *\n * The named queries are packaged into bundles on the server side (along\n * with resulting documents), and loaded to local cache using `loadBundle`. Once\n * in local cache, use this method to extract a {@link Query} by name.\n *\n * @param firestore - The {@link Firestore} instance to read the query from.\n * @param name - The name of the query.\n * @returns A `Promise` that is resolved with the Query or `null`.\n */ function yh(t, e) {\n return Za(uh(t = fa(t, ih)), e).then((e => e ? new pa(t, null, e.query) : null));\n}\n\nfunction ph(t) {\n if (t._initialized || t._terminated) throw new L(B.FAILED_PRECONDITION, \"Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object.\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing an array of bytes.\n */\nclass Ih {\n /** @hideconstructor */\n constructor(t) {\n this._byteString = t;\n }\n /**\n * Creates a new `Bytes` object from the given Base64 string, converting it to\n * bytes.\n *\n * @param base64 - The Base64 string used to create the `Bytes` object.\n */ static fromBase64String(t) {\n try {\n return new Ih(Qt.fromBase64String(t));\n } catch (t) {\n throw new L(B.INVALID_ARGUMENT, \"Failed to construct data from Base64 string: \" + t);\n }\n }\n /**\n * Creates a new `Bytes` object from the given Uint8Array.\n *\n * @param array - The Uint8Array used to create the `Bytes` object.\n */ static fromUint8Array(t) {\n return new Ih(Qt.fromUint8Array(t));\n }\n /**\n * Returns the underlying bytes as a Base64-encoded string.\n *\n * @returns The Base64-encoded string created from the `Bytes` object.\n */ toBase64() {\n return this._byteString.toBase64();\n }\n /**\n * Returns the underlying bytes in a new `Uint8Array`.\n *\n * @returns The Uint8Array created from the `Bytes` object.\n */ toUint8Array() {\n return this._byteString.toUint8Array();\n }\n /**\n * Returns a string representation of the `Bytes` object.\n *\n * @returns A string representation of the `Bytes` object.\n */ toString() {\n return \"Bytes(base64: \" + this.toBase64() + \")\";\n }\n /**\n * Returns true if this `Bytes` object is equal to the provided one.\n *\n * @param other - The `Bytes` object to compare against.\n * @returns true if this `Bytes` object is equal to the provided one.\n */ isEqual(t) {\n return this._byteString.isEqual(t._byteString);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a\n * list of field names (referring to a nested field in the document).\n *\n * Create a `FieldPath` by providing field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n */ class Th {\n /**\n * Creates a `FieldPath` from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...t) {\n for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new L(B.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). Field names must not be empty.\");\n this._internalPath = new ut(t);\n }\n /**\n * Returns true if this `FieldPath` is equal to the provided one.\n *\n * @param other - The `FieldPath` to compare against.\n * @returns true if this `FieldPath` is equal to the provided one.\n */ isEqual(t) {\n return this._internalPath.isEqual(t._internalPath);\n }\n}\n\n/**\n * Returns a special sentinel `FieldPath` to refer to the ID of a document.\n * It can be used in queries to sort or filter by the document ID.\n */ function Eh() {\n return new Th(\"__name__\");\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Sentinel values that can be used when writing document fields with `set()`\n * or `update()`.\n */ class Ah {\n /**\n * @param _methodName - The public API endpoint that returns this class.\n * @hideconstructor\n */\n constructor(t) {\n this._methodName = t;\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * An immutable object representing a geographic location in Firestore. The\n * location is represented as latitude/longitude pair.\n *\n * Latitude values are in the range of [-90, 90].\n * Longitude values are in the range of [-180, 180].\n */ class Rh {\n /**\n * Creates a new immutable `GeoPoint` object with the provided latitude and\n * longitude values.\n * @param latitude - The latitude as number between -90 and 90.\n * @param longitude - The longitude as number between -180 and 180.\n */\n constructor(t, e) {\n if (!isFinite(t) || t < -90 || t > 90) throw new L(B.INVALID_ARGUMENT, \"Latitude must be a number between -90 and 90, but was: \" + t);\n if (!isFinite(e) || e < -180 || e > 180) throw new L(B.INVALID_ARGUMENT, \"Longitude must be a number between -180 and 180, but was: \" + e);\n this._lat = t, this._long = e;\n }\n /**\n * The latitude of this `GeoPoint` instance.\n */ get latitude() {\n return this._lat;\n }\n /**\n * The longitude of this `GeoPoint` instance.\n */ get longitude() {\n return this._long;\n }\n /**\n * Returns true if this `GeoPoint` is equal to the provided one.\n *\n * @param other - The `GeoPoint` to compare against.\n * @returns true if this `GeoPoint` is equal to the provided one.\n */ isEqual(t) {\n return this._lat === t._lat && this._long === t._long;\n }\n /** Returns a JSON-serializable representation of this GeoPoint. */ toJSON() {\n return {\n latitude: this._lat,\n longitude: this._long\n };\n }\n /**\n * Actually private to JS consumers of our API, so this function is prefixed\n * with an underscore.\n */ _compareTo(t) {\n return Z(this._lat, t._lat) || Z(this._long, t._long);\n }\n}\n\n/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const bh = /^__.*__$/;\n\n/** The result of parsing document data (e.g. for a setData call). */ class Ph {\n constructor(t, e, n) {\n this.data = t, this.fieldMask = e, this.fieldTransforms = n;\n }\n toMutation(t, e) {\n return null !== this.fieldMask ? new ts(t, this.data, this.fieldMask, e, this.fieldTransforms) : new Zn(t, this.data, e, this.fieldTransforms);\n }\n}\n\n/** The result of parsing \"update\" data (i.e. for an updateData call). */ class vh {\n constructor(t, \n // The fieldMask does not include document transforms.\n e, n) {\n this.data = t, this.fieldMask = e, this.fieldTransforms = n;\n }\n toMutation(t, e) {\n return new ts(t, this.data, this.fieldMask, e, this.fieldTransforms);\n }\n}\n\nfunction Vh(t) {\n switch (t) {\n case 0 /* UserDataSource.Set */ :\n // fall through\n case 2 /* UserDataSource.MergeSet */ :\n // fall through\n case 1 /* UserDataSource.Update */ :\n return !0;\n\n case 3 /* UserDataSource.Argument */ :\n case 4 /* UserDataSource.ArrayArgument */ :\n return !1;\n\n default:\n throw O();\n }\n}\n\n/** A \"context\" object passed around while parsing user data. */ class Sh {\n /**\n * Initializes a ParseContext with the given source and path.\n *\n * @param settings - The settings for the parser.\n * @param databaseId - The database ID of the Firestore instance.\n * @param serializer - The serializer to use to generate the Value proto.\n * @param ignoreUndefinedProperties - Whether to ignore undefined properties\n * rather than throw.\n * @param fieldTransforms - A mutable list of field transforms encountered\n * while parsing the data.\n * @param fieldMask - A mutable list of field paths encountered while parsing\n * the data.\n *\n * TODO(b/34871131): We don't support array paths right now, so path can be\n * null to indicate the context represents any location within an array (in\n * which case certain features will not work and errors will be somewhat\n * compromised).\n */\n constructor(t, e, n, s, i, r) {\n this.settings = t, this.databaseId = e, this.yt = n, this.ignoreUndefinedProperties = s, \n // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n void 0 === i && this.na(), this.fieldTransforms = i || [], this.fieldMask = r || [];\n }\n get path() {\n return this.settings.path;\n }\n get sa() {\n return this.settings.sa;\n }\n /** Returns a new context with the specified settings overwritten. */ ia(t) {\n return new Sh(Object.assign(Object.assign({}, this.settings), t), this.databaseId, this.yt, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask);\n }\n ra(t) {\n var e;\n const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.ia({\n path: n,\n oa: !1\n });\n return s.ua(t), s;\n }\n ca(t) {\n var e;\n const n = null === (e = this.path) || void 0 === e ? void 0 : e.child(t), s = this.ia({\n path: n,\n oa: !1\n });\n return s.na(), s;\n }\n aa(t) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // undefined.\n return this.ia({\n path: void 0,\n oa: !0\n });\n }\n ha(t) {\n return Hh(t, this.settings.methodName, this.settings.la || !1, this.path, this.settings.fa);\n }\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) {\n return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field)));\n }\n na() {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path) for (let t = 0; t < this.path.length; t++) this.ua(this.path.get(t));\n }\n ua(t) {\n if (0 === t.length) throw this.ha(\"Document fields must not be empty\");\n if (Vh(this.sa) && bh.test(t)) throw this.ha('Document fields cannot begin and end with \"__\"');\n }\n}\n\n/**\n * Helper for parsing raw user input (provided via the API) into internal model\n * classes.\n */ class Dh {\n constructor(t, e, n) {\n this.databaseId = t, this.ignoreUndefinedProperties = e, this.yt = n || pu(t);\n }\n /** Creates a new top-level parse context. */ da(t, e, n, s = !1) {\n return new Sh({\n sa: t,\n methodName: e,\n fa: n,\n path: ut.emptyPath(),\n oa: !1,\n la: s\n }, this.databaseId, this.yt, this.ignoreUndefinedProperties);\n }\n}\n\nfunction Ch(t) {\n const e = t._freezeSettings(), n = pu(t._databaseId);\n return new Dh(t._databaseId, !!e.ignoreUndefinedProperties, n);\n}\n\n/** Parse document data from a set() call. */ function xh(t, e, n, s, i, r = {}) {\n const o = t.da(r.merge || r.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, n, i);\n Qh(\"Data must be an object, but it was:\", o, s);\n const u = Kh(s, o);\n let c, a;\n if (r.merge) c = new Je(o.fieldMask), a = o.fieldTransforms; else if (r.mergeFields) {\n const t = [];\n for (const s of r.mergeFields) {\n const i = jh(e, s, n);\n if (!o.contains(i)) throw new L(B.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`);\n Jh(t, i) || t.push(i);\n }\n c = new Je(t), a = o.fieldTransforms.filter((t => c.covers(t.field)));\n } else c = null, a = o.fieldTransforms;\n return new Ph(new Ye(u), c, a);\n}\n\nclass Nh extends Ah {\n _toFieldTransform(t) {\n if (2 /* UserDataSource.MergeSet */ !== t.sa) throw 1 /* UserDataSource.Update */ === t.sa ? t.ha(`${this._methodName}() can only appear at the top level of your update data`) : t.ha(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`);\n // No transform to add for a delete, but we need to add it to our\n // fieldMask so it gets deleted.\n return t.fieldMask.push(t.path), null;\n }\n isEqual(t) {\n return t instanceof Nh;\n }\n}\n\n/**\n * Creates a child context for parsing SerializableFieldValues.\n *\n * This is different than calling `ParseContext.contextWith` because it keeps\n * the fieldTransforms and fieldMask separate.\n *\n * The created context has its `dataSource` set to `UserDataSource.Argument`.\n * Although these values are used with writes, any elements in these FieldValues\n * are not considered writes since they cannot contain any FieldValue sentinels,\n * etc.\n *\n * @param fieldValue - The sentinel FieldValue for which to create a child\n * context.\n * @param context - The parent context.\n * @param arrayElement - Whether or not the FieldValue has an array.\n */ function kh(t, e, n) {\n return new Sh({\n sa: 3 /* UserDataSource.Argument */ ,\n fa: e.settings.fa,\n methodName: t._methodName,\n oa: n\n }, e.databaseId, e.yt, e.ignoreUndefinedProperties);\n}\n\nclass Oh extends Ah {\n _toFieldTransform(t) {\n return new Un(t.path, new kn);\n }\n isEqual(t) {\n return t instanceof Oh;\n }\n}\n\nclass Mh extends Ah {\n constructor(t, e) {\n super(t), this._a = e;\n }\n _toFieldTransform(t) {\n const e = kh(this, t, \n /*array=*/ !0), n = this._a.map((t => Uh(t, e))), s = new On(n);\n return new Un(t.path, s);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\nclass Fh extends Ah {\n constructor(t, e) {\n super(t), this._a = e;\n }\n _toFieldTransform(t) {\n const e = kh(this, t, \n /*array=*/ !0), n = this._a.map((t => Uh(t, e))), s = new Fn(n);\n return new Un(t.path, s);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\nclass $h extends Ah {\n constructor(t, e) {\n super(t), this.wa = e;\n }\n _toFieldTransform(t) {\n const e = new Bn(t.yt, Sn(t.yt, this.wa));\n return new Un(t.path, e);\n }\n isEqual(t) {\n // TODO(mrschmidt): Implement isEquals\n return this === t;\n }\n}\n\n/** Parse update data from an update() call. */ function Bh(t, e, n, s) {\n const i = t.da(1 /* UserDataSource.Update */ , e, n);\n Qh(\"Data must be an object, but it was:\", i, s);\n const r = [], o = Ye.empty();\n Bt(s, ((t, s) => {\n const u = zh(e, t, n);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n s = d(s);\n const c = i.ca(u);\n if (s instanceof Nh) \n // Add it to the field mask, but don't add anything to updateData.\n r.push(u); else {\n const t = Uh(s, c);\n null != t && (r.push(u), o.set(u, t));\n }\n }));\n const u = new Je(r);\n return new vh(o, u, i.fieldTransforms);\n}\n\n/** Parse update data from a list of field/value arguments. */ function Lh(t, e, n, s, i, r) {\n const o = t.da(1 /* UserDataSource.Update */ , e, n), u = [ jh(e, s, n) ], c = [ i ];\n if (r.length % 2 != 0) throw new L(B.INVALID_ARGUMENT, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`);\n for (let t = 0; t < r.length; t += 2) u.push(jh(e, r[t])), c.push(r[t + 1]);\n const a = [], h = Ye.empty();\n // We iterate in reverse order to pick the last value for a field if the\n // user specified the field multiple times.\n for (let t = u.length - 1; t >= 0; --t) if (!Jh(a, u[t])) {\n const e = u[t];\n let n = c[t];\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n n = d(n);\n const s = o.ca(e);\n if (n instanceof Nh) \n // Add it to the field mask, but don't add anything to updateData.\n a.push(e); else {\n const t = Uh(n, s);\n null != t && (a.push(e), h.set(e, t));\n }\n }\n const l = new Je(a);\n return new vh(h, l, o.fieldTransforms);\n}\n\n/**\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\n * bound).\n *\n * @param allowArrays - Whether the query value is an array that may directly\n * contain additional arrays (e.g. the operand of an `in` query).\n */ function qh(t, e, n, s = !1) {\n return Uh(n, t.da(s ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e));\n}\n\n/**\n * Parses user data to Protobuf Values.\n *\n * @param input - Data to be parsed.\n * @param context - A context object representing the current path being parsed,\n * the source of the data being parsed, etc.\n * @returns The parsed value, or null if the value was a FieldValue sentinel\n * that should not be included in the resulting parsed data.\n */ function Uh(t, e) {\n if (Gh(\n // Unwrap the API type from the Compat SDK. This will return the API type\n // from firestore-exp.\n t = d(t))) return Qh(\"Unsupported field value:\", e, t), Kh(t, e);\n if (t instanceof Ah) \n // FieldValues usually parse into transforms (except deleteField())\n // in which case we do not want to include this field in our parsed data\n // (as doing so will overwrite the field directly prior to the transform\n // trying to transform it). So we don't add this location to\n // context.fieldMask and we return null as our parsing result.\n /**\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\n * context.fieldTransforms.\n */\n return function(t, e) {\n // Sentinels are only supported with writes, and not within arrays.\n if (!Vh(e.sa)) throw e.ha(`${t._methodName}() can only be used with update() and set()`);\n if (!e.path) throw e.ha(`${t._methodName}() is not currently supported inside arrays`);\n const n = t._toFieldTransform(e);\n n && e.fieldTransforms.push(n);\n }\n /**\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\n *\n * @returns The parsed value\n */ (t, e), null;\n if (void 0 === t && e.ignoreUndefinedProperties) \n // If the input is undefined it can never participate in the fieldMask, so\n // don't handle this below. If `ignoreUndefinedProperties` is false,\n // `parseScalarValue` will reject an undefined value.\n return null;\n if (\n // If context.path is null we are inside an array and we don't support\n // field mask paths more granular than the top-level array.\n e.path && e.fieldMask.push(e.path), t instanceof Array) {\n // TODO(b/34871131): Include the path containing the array in the error\n // message.\n // In the case of IN queries, the parsed data is an array (representing\n // the set of values to be included for the IN query) that may directly\n // contain additional arrays (each representing an individual field\n // value), so we disable this validation.\n if (e.settings.oa && 4 /* UserDataSource.ArrayArgument */ !== e.sa) throw e.ha(\"Nested arrays are not supported\");\n return function(t, e) {\n const n = [];\n let s = 0;\n for (const i of t) {\n let t = Uh(i, e.aa(s));\n null == t && (\n // Just include nulls in the array for fields being replaced with a\n // sentinel.\n t = {\n nullValue: \"NULL_VALUE\"\n }), n.push(t), s++;\n }\n return {\n arrayValue: {\n values: n\n }\n };\n }(t, e);\n }\n return function(t, e) {\n if (null === (t = d(t))) return {\n nullValue: \"NULL_VALUE\"\n };\n if (\"number\" == typeof t) return Sn(e.yt, t);\n if (\"boolean\" == typeof t) return {\n booleanValue: t\n };\n if (\"string\" == typeof t) return {\n stringValue: t\n };\n if (t instanceof Date) {\n const n = nt.fromDate(t);\n return {\n timestampValue: $s(e.yt, n)\n };\n }\n if (t instanceof nt) {\n // Firestore backend truncates precision down to microseconds. To ensure\n // offline mode works the same with regards to truncation, perform the\n // truncation immediately without waiting for the backend to do that.\n const n = new nt(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3));\n return {\n timestampValue: $s(e.yt, n)\n };\n }\n if (t instanceof Rh) return {\n geoPointValue: {\n latitude: t.latitude,\n longitude: t.longitude\n }\n };\n if (t instanceof Ih) return {\n bytesValue: Bs(e.yt, t._byteString)\n };\n if (t instanceof ya) {\n const n = e.databaseId, s = t.firestore._databaseId;\n if (!s.isEqual(n)) throw e.ha(`Document reference is for database ${s.projectId}/${s.database} but should be for database ${n.projectId}/${n.database}`);\n return {\n referenceValue: Us(t.firestore._databaseId || e.databaseId, t._key.path)\n };\n }\n throw e.ha(`Unsupported field value: ${la(t)}`);\n }\n /**\n * Checks whether an object looks like a JSON object that should be converted\n * into a struct. Normal class/prototype instances are considered to look like\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\n * GeoPoints, etc. are not considered to look like JSON objects since they map\n * to specific FieldValue types other than ObjectValue.\n */ (t, e);\n}\n\nfunction Kh(t, e) {\n const n = {};\n return Lt(t) ? \n // If we encounter an empty object, we explicitly add it to the update\n // mask to ensure that the server creates a map entry.\n e.path && e.path.length > 0 && e.fieldMask.push(e.path) : Bt(t, ((t, s) => {\n const i = Uh(s, e.ra(t));\n null != i && (n[t] = i);\n })), {\n mapValue: {\n fields: n\n }\n };\n}\n\nfunction Gh(t) {\n return !(\"object\" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof nt || t instanceof Rh || t instanceof Ih || t instanceof ya || t instanceof Ah);\n}\n\nfunction Qh(t, e, n) {\n if (!Gh(n) || !function(t) {\n return \"object\" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t));\n }(n)) {\n const s = la(n);\n throw \"an object\" === s ? e.ha(t + \" a custom object\") : e.ha(t + \" \" + s);\n }\n}\n\n/**\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\n */ function jh(t, e, n) {\n if ((\n // If required, replace the FieldPath Compat class with with the firestore-exp\n // FieldPath.\n e = d(e)) instanceof Th) return e._internalPath;\n if (\"string\" == typeof e) return zh(t, e);\n throw Hh(\"Field path arguments must be of type string or \", t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n}\n\n/**\n * Matches any characters in a field path string that are reserved.\n */ const Wh = new RegExp(\"[~\\\\*/\\\\[\\\\]]\");\n\n/**\n * Wraps fromDotSeparatedString with an error message about the method that\n * was thrown.\n * @param methodName - The publicly visible method name\n * @param path - The dot-separated string form of a field path which will be\n * split on dots.\n * @param targetDoc - The document against which the field path will be\n * evaluated.\n */ function zh(t, e, n) {\n if (e.search(Wh) >= 0) throw Hh(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n try {\n return new Th(...e.split(\".\"))._internalPath;\n } catch (s) {\n throw Hh(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, \n /* hasConverter= */ !1, \n /* path= */ void 0, n);\n }\n}\n\nfunction Hh(t, e, n, s, i) {\n const r = s && !s.isEmpty(), o = void 0 !== i;\n let u = `Function ${e}() called with invalid data`;\n n && (u += \" (via `toFirestore()`)\"), u += \". \";\n let c = \"\";\n return (r || o) && (c += \" (found\", r && (c += ` in field ${s}`), o && (c += ` in document ${i}`), \n c += \")\"), new L(B.INVALID_ARGUMENT, u + t + c);\n}\n\n/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function Jh(t, e) {\n return t.some((t => t.isEqual(e)));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class Yh {\n // Note: This class is stripped down version of the DocumentSnapshot in\n // the legacy SDK. The changes are:\n // - No support for SnapshotMetadata.\n // - No support for SnapshotOptions.\n /** @hideconstructor protected */\n constructor(t, e, n, s, i) {\n this._firestore = t, this._userDataWriter = e, this._key = n, this._document = s, \n this._converter = i;\n }\n /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() {\n return this._key.path.lastSegment();\n }\n /**\n * The `DocumentReference` for the document included in the `DocumentSnapshot`.\n */ get ref() {\n return new ya(this._firestore, this._converter, this._key);\n }\n /**\n * Signals whether or not the document at the snapshot's location exists.\n *\n * @returns true if the document exists.\n */ exists() {\n return null !== this._document;\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * @returns An `Object` containing all fields in the document or `undefined`\n * if the document doesn't exist.\n */ data() {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const t = new Xh(this._firestore, this._userDataWriter, this._key, this._document, \n /* converter= */ null);\n return this._converter.fromFirestore(t);\n }\n return this._userDataWriter.convertValue(this._document.data.value);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(t) {\n if (this._document) {\n const e = this._document.data.field(Zh(\"DocumentSnapshot.get\", t));\n if (null !== e) return this._userDataWriter.convertValue(e);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class Xh extends Yh {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * @override\n * @returns An `Object` containing all fields in the document.\n */\n data() {\n return super.data();\n }\n}\n\n/**\n * Helper that calls `fromDotSeparatedString()` but wraps any error thrown.\n */ function Zh(t, e) {\n return \"string\" == typeof e ? zh(t, e) : e instanceof Th ? e._internalPath : e._delegate._internalPath;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function tl(t) {\n if (\"L\" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new L(B.UNIMPLEMENTED, \"limitToLast() queries require specifying at least one orderBy() clause\");\n}\n\n/**\n * An `AppliableConstraint` is an abstraction of a constraint that can be applied\n * to a Firestore query.\n */ class el {}\n\n/**\n * A `QueryConstraint` is used to narrow the set of documents returned by a\n * Firestore query. `QueryConstraint`s are created by invoking {@link where},\n * {@link orderBy}, {@link startAt}, {@link startAfter}, {@link\n * endBefore}, {@link endAt}, {@link limit}, {@link limitToLast} and\n * can then be passed to {@link query} to create a new query instance that\n * also contains this `QueryConstraint`.\n */ class nl extends el {}\n\nfunction sl(t, e, ...n) {\n let s = [];\n e instanceof el && s.push(e), s = s.concat(n), function(t) {\n const e = t.filter((t => t instanceof ol)).length, n = t.filter((t => t instanceof il)).length;\n if (e > 1 || e > 0 && n > 0) throw new L(B.INVALID_ARGUMENT, \"InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`.\");\n }\n /**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n /**\n * Converts Firestore's internal types to the JavaScript types that we expose\n * to the user.\n *\n * @internal\n */ (s);\n for (const e of s) t = e._apply(t);\n return t;\n}\n\n/**\n * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by\n * a Firestore query by filtering on one or more document fields.\n * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then\n * be passed to {@link query} to create a new query instance that also contains\n * this `QueryFieldFilterConstraint`.\n */ class il extends nl {\n /**\n * @internal\n */\n constructor(t, e, n) {\n super(), this._field = t, this._op = e, this._value = n, \n /** The type of this query constraint */\n this.type = \"where\";\n }\n static _create(t, e, n) {\n return new il(t, e, n);\n }\n _apply(t) {\n const e = this._parse(t);\n return Al(t._query, e), new pa(t.firestore, t.converter, yn(t._query, e));\n }\n _parse(t) {\n const e = Ch(t.firestore), n = function(t, e, n, s, i, r, o) {\n let u;\n if (i.isKeyField()) {\n if (\"array-contains\" /* Operator.ARRAY_CONTAINS */ === r || \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ === r) throw new L(B.INVALID_ARGUMENT, `Invalid Query. You can't perform '${r}' queries on documentId().`);\n if (\"in\" /* Operator.IN */ === r || \"not-in\" /* Operator.NOT_IN */ === r) {\n El(o, r);\n const e = [];\n for (const n of o) e.push(Tl(s, t, n));\n u = {\n arrayValue: {\n values: e\n }\n };\n } else u = Tl(s, t, o);\n } else \"in\" /* Operator.IN */ !== r && \"not-in\" /* Operator.NOT_IN */ !== r && \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ !== r || El(o, r), \n u = qh(n, e, o, \n /* allowArrays= */ \"in\" /* Operator.IN */ === r || \"not-in\" /* Operator.NOT_IN */ === r);\n return Re.create(i, r, u);\n }(t._query, \"where\", e, t.firestore._databaseId, this._field, this._op, this._value);\n return n;\n }\n}\n\n/**\n * Creates a {@link QueryFieldFilterConstraint} that enforces that documents\n * must contain the specified field and that the value should satisfy the\n * relation constraint provided.\n *\n * @param fieldPath - The path to compare\n * @param opStr - The operation string (e.g \"&lt;\", \"&lt;=\", \"==\", \"&lt;\",\n * \"&lt;=\", \"!=\").\n * @param value - The value for comparison\n * @returns The created {@link QueryFieldFilterConstraint}.\n */ function rl(t, e, n) {\n const s = e, i = Zh(\"where\", t);\n return il._create(i, s, n);\n}\n\n/**\n * A `QueryCompositeFilterConstraint` is used to narrow the set of documents\n * returned by a Firestore query by performing the logical OR or AND of multiple\n * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s.\n * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or\n * {@link and} and can then be passed to {@link query} to create a new query\n * instance that also contains the `QueryCompositeFilterConstraint`.\n * @internal TODO remove this internal tag with OR Query support in the server\n */ class ol extends el {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e) {\n super(), this.type = t, this._queryConstraints = e;\n }\n static _create(t, e) {\n return new ol(t, e);\n }\n _parse(t) {\n const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0));\n return 1 === e.length ? e[0] : be.create(e, this._getOperator());\n }\n _apply(t) {\n const e = this._parse(t);\n return 0 === e.getFilters().length ? t : (function(t, e) {\n let n = t;\n const s = e.getFlattenedFilters();\n for (const t of s) Al(n, t), n = yn(n, t);\n }\n // Checks if any of the provided filter operators are included in the given list of filters and\n // returns the first one that is, or null if none are.\n (t._query, e), new pa(t.firestore, t.converter, yn(t._query, e)));\n }\n _getQueryConstraints() {\n return this._queryConstraints;\n }\n _getOperator() {\n return \"and\" === this.type ? \"and\" /* CompositeOperator.AND */ : \"or\" /* CompositeOperator.OR */;\n }\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of\n * the given filter constraints. A disjunction filter includes a document if it\n * satisfies any of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a disjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n * @internal TODO remove this internal tag with OR Query support in the server\n */ function ul(...t) {\n // Only support QueryFilterConstraints\n return t.forEach((t => bl(\"or\", t))), ol._create(\"or\" /* CompositeOperator.OR */ , t);\n}\n\n/**\n * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of\n * the given filter constraints. A conjunction filter includes a document if it\n * satisfies all of the given filters.\n *\n * @param queryConstraints - Optional. The list of\n * {@link QueryFilterConstraint}s to perform a conjunction for. These must be\n * created with calls to {@link where}, {@link or}, or {@link and}.\n * @returns The newly created {@link QueryCompositeFilterConstraint}.\n * @internal TODO remove this internal tag with OR Query support in the server\n */ function cl(...t) {\n // Only support QueryFilterConstraints\n return t.forEach((t => bl(\"and\", t))), ol._create(\"and\" /* CompositeOperator.AND */ , t);\n}\n\n/**\n * A `QueryOrderByConstraint` is used to sort the set of documents returned by a\n * Firestore query. `QueryOrderByConstraint`s are created by invoking\n * {@link orderBy} and can then be passed to {@link query} to create a new query\n * instance that also contains this `QueryOrderByConstraint`.\n *\n * Note: Documents that do not contain the orderBy field will not be present in\n * the query result.\n */ class al extends nl {\n /**\n * @internal\n */\n constructor(t, e) {\n super(), this._field = t, this._direction = e, \n /** The type of this query constraint */\n this.type = \"orderBy\";\n }\n static _create(t, e) {\n return new al(t, e);\n }\n _apply(t) {\n const e = function(t, e, n) {\n if (null !== t.startAt) throw new L(B.INVALID_ARGUMENT, \"Invalid query. You must not call startAt() or startAfter() before calling orderBy().\");\n if (null !== t.endAt) throw new L(B.INVALID_ARGUMENT, \"Invalid query. You must not call endAt() or endBefore() before calling orderBy().\");\n const s = new Ue(e, n);\n return function(t, e) {\n if (null === dn(t)) {\n // This is the first order by. It must match any inequality.\n const n = _n(t);\n null !== n && Rl(t, n, e.field);\n }\n }(t, s), s;\n }\n /**\n * Create a `Bound` from a query and a document.\n *\n * Note that the `Bound` will always include the key of the document\n * and so only the provided document will compare equal to the returned\n * position.\n *\n * Will throw if the document does not contain all fields of the order by\n * of the query or if any of the fields in the order by are an uncommitted\n * server timestamp.\n */ (t._query, this._field, this._direction);\n return new pa(t.firestore, t.converter, function(t, e) {\n // TODO(dimond): validate that orderBy does not list the same key twice.\n const n = t.explicitOrderBy.concat([ e ]);\n return new an(t.path, t.collectionGroup, n, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt);\n }(t._query, e));\n }\n}\n\n/**\n * Creates a {@link QueryOrderByConstraint} that sorts the query result by the\n * specified field, optionally in descending order instead of ascending.\n *\n * Note: Documents that do not contain the specified field will not be present\n * in the query result.\n *\n * @param fieldPath - The field to sort by.\n * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If\n * not specified, order will be ascending.\n * @returns The created {@link QueryOrderByConstraint}.\n */ function hl(t, e = \"asc\") {\n const n = e, s = Zh(\"orderBy\", t);\n return al._create(s, n);\n}\n\n/**\n * A `QueryLimitConstraint` is used to limit the number of documents returned by\n * a Firestore query.\n * `QueryLimitConstraint`s are created by invoking {@link limit} or\n * {@link limitToLast} and can then be passed to {@link query} to create a new\n * query instance that also contains this `QueryLimitConstraint`.\n */ class ll extends nl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._limit = e, this._limitType = n;\n }\n static _create(t, e, n) {\n return new ll(t, e, n);\n }\n _apply(t) {\n return new pa(t.firestore, t.converter, pn(t._query, this._limit, this._limitType));\n }\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the first matching\n * documents.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function fl(t) {\n return da(\"limit\", t), ll._create(\"limit\", t, \"F\" /* LimitType.First */);\n}\n\n/**\n * Creates a {@link QueryLimitConstraint} that only returns the last matching\n * documents.\n *\n * You must specify at least one `orderBy` clause for `limitToLast` queries,\n * otherwise an exception will be thrown during execution.\n *\n * @param limit - The maximum number of items to return.\n * @returns The created {@link QueryLimitConstraint}.\n */ function dl(t) {\n return da(\"limitToLast\", t), ll._create(\"limitToLast\", t, \"L\" /* LimitType.Last */);\n}\n\n/**\n * A `QueryStartAtConstraint` is used to exclude documents from the start of a\n * result set returned by a Firestore query.\n * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or\n * {@link (startAfter:1)} and can then be passed to {@link query} to create a\n * new query instance that also contains this `QueryStartAtConstraint`.\n */ class _l extends nl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._docOrFields = e, this._inclusive = n;\n }\n static _create(t, e, n) {\n return new _l(t, e, n);\n }\n _apply(t) {\n const e = Il(t, this.type, this._docOrFields, this._inclusive);\n return new pa(t.firestore, t.converter, function(t, e) {\n return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt);\n }(t._query, e));\n }\n}\n\nfunction wl(...t) {\n return _l._create(\"startAt\", t, \n /*inclusive=*/ !0);\n}\n\nfunction ml(...t) {\n return _l._create(\"startAfter\", t, \n /*inclusive=*/ !1);\n}\n\n/**\n * A `QueryEndAtConstraint` is used to exclude documents from the end of a\n * result set returned by a Firestore query.\n * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or\n * {@link (endBefore:1)} and can then be passed to {@link query} to create a new\n * query instance that also contains this `QueryEndAtConstraint`.\n */ class gl extends nl {\n /**\n * @internal\n */\n constructor(\n /** The type of this query constraint */\n t, e, n) {\n super(), this.type = t, this._docOrFields = e, this._inclusive = n;\n }\n static _create(t, e, n) {\n return new gl(t, e, n);\n }\n _apply(t) {\n const e = Il(t, this.type, this._docOrFields, this._inclusive);\n return new pa(t.firestore, t.converter, function(t, e) {\n return new an(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e);\n }(t._query, e));\n }\n}\n\nfunction yl(...t) {\n return gl._create(\"endBefore\", t, \n /*inclusive=*/ !1);\n}\n\nfunction pl(...t) {\n return gl._create(\"endAt\", t, \n /*inclusive=*/ !0);\n}\n\n/** Helper function to create a bound from a document or fields */ function Il(t, e, n, s) {\n if (n[0] = d(n[0]), n[0] instanceof Yh) return function(t, e, n, s, i) {\n if (!s) throw new L(B.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`);\n const r = [];\n // Because people expect to continue/end a query at the exact document\n // provided, we need to use the implicit sort order rather than the explicit\n // sort order, because it's guaranteed to contain the document key. That way\n // the position becomes unambiguous and the query continues/ends exactly at\n // the provided document. Without the key (by using the explicit sort\n // orders), multiple documents could match the position, yielding duplicate\n // results.\n for (const n of mn(t)) if (n.field.isKeyField()) r.push(ce(e, s.key)); else {\n const t = s.data.field(n.field);\n if (Jt(t)) throw new L(B.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field \"' + n.field + '\" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)');\n if (null === t) {\n const t = n.field.canonicalString();\n throw new L(B.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`);\n }\n r.push(t);\n }\n return new Ie(r, i);\n }\n /**\n * Converts a list of field values to a `Bound` for the given query.\n */ (t._query, t.firestore._databaseId, e, n[0]._document, s);\n {\n const i = Ch(t.firestore);\n return function(t, e, n, s, i, r) {\n // Use explicit order by's because it has to match the query the user made\n const o = t.explicitOrderBy;\n if (i.length > o.length) throw new L(B.INVALID_ARGUMENT, `Too many arguments provided to ${s}(). The number of arguments must be less than or equal to the number of orderBy() clauses`);\n const u = [];\n for (let r = 0; r < i.length; r++) {\n const c = i[r];\n if (o[r].field.isKeyField()) {\n if (\"string\" != typeof c) throw new L(B.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${s}(), but got a ${typeof c}`);\n if (!wn(t) && -1 !== c.indexOf(\"/\")) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${s}() must be a plain document ID, but '${c}' contains a slash.`);\n const n = t.path.child(rt.fromString(c));\n if (!ct.isDocumentKey(n)) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${s}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`);\n const i = new ct(n);\n u.push(ce(e, i));\n } else {\n const t = qh(n, s, c);\n u.push(t);\n }\n }\n return new Ie(u, r);\n }\n /**\n * Parses the given `documentIdValue` into a `ReferenceValue`, throwing\n * appropriate errors if the value is anything other than a `DocumentReference`\n * or `string`, or if the string is malformed.\n */ (t._query, t.firestore._databaseId, i, e, n, s);\n }\n}\n\nfunction Tl(t, e, n) {\n if (\"string\" == typeof (n = d(n))) {\n if (\"\" === n) throw new L(B.INVALID_ARGUMENT, \"Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string.\");\n if (!wn(e) && -1 !== n.indexOf(\"/\")) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`);\n const s = e.path.child(rt.fromString(n));\n if (!ct.isDocumentKey(s)) throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${s}' is not because it has an odd number of segments (${s.length}).`);\n return ce(t, new ct(s));\n }\n if (n instanceof ya) return ce(t, n._key);\n throw new L(B.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${la(n)}.`);\n}\n\n/**\n * Validates that the value passed into a disjunctive filter satisfies all\n * array requirements.\n */ function El(t, e) {\n if (!Array.isArray(t) || 0 === t.length) throw new L(B.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`);\n if (t.length > 10) throw new L(B.INVALID_ARGUMENT, `Invalid Query. '${e.toString()}' filters support a maximum of 10 elements in the value array.`);\n}\n\n/**\n * Given an operator, returns the set of operators that cannot be used with it.\n *\n * Operators in a query must adhere to the following set of rules:\n * 1. Only one array operator is allowed.\n * 2. Only one disjunctive operator is allowed.\n * 3. `NOT_EQUAL` cannot be used with another `NOT_EQUAL` operator.\n * 4. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators.\n *\n * Array operators: `ARRAY_CONTAINS`, `ARRAY_CONTAINS_ANY`\n * Disjunctive operators: `IN`, `ARRAY_CONTAINS_ANY`, `NOT_IN`\n */ function Al(t, e) {\n if (e.isInequality()) {\n const n = _n(t), s = e.field;\n if (null !== n && !n.isEqual(s)) throw new L(B.INVALID_ARGUMENT, `Invalid query. All where filters with an inequality (<, <=, !=, not-in, >, or >=) must be on the same field. But you have inequality filters on '${n.toString()}' and '${s.toString()}'`);\n const i = dn(t);\n null !== i && Rl(t, s, i);\n }\n const n = function(t, e) {\n for (const n of t) for (const t of n.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op;\n return null;\n }(t.filters, function(t) {\n switch (t) {\n case \"!=\" /* Operator.NOT_EQUAL */ :\n return [ \"!=\" /* Operator.NOT_EQUAL */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"array-contains\" /* Operator.ARRAY_CONTAINS */ :\n return [ \"array-contains\" /* Operator.ARRAY_CONTAINS */ , \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"in\" /* Operator.IN */ :\n return [ \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ :\n return [ \"array-contains\" /* Operator.ARRAY_CONTAINS */ , \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ ];\n\n case \"not-in\" /* Operator.NOT_IN */ :\n return [ \"array-contains\" /* Operator.ARRAY_CONTAINS */ , \"array-contains-any\" /* Operator.ARRAY_CONTAINS_ANY */ , \"in\" /* Operator.IN */ , \"not-in\" /* Operator.NOT_IN */ , \"!=\" /* Operator.NOT_EQUAL */ ];\n\n default:\n return [];\n }\n }(e.op));\n if (null !== n) \n // Special case when it's a duplicate op to give a slightly clearer error message.\n throw n === e.op ? new L(B.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new L(B.INVALID_ARGUMENT, `Invalid query. You cannot use '${e.op.toString()}' filters with '${n.toString()}' filters.`);\n}\n\nfunction Rl(t, e, n) {\n if (!n.isEqual(e)) throw new L(B.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality (<, <=, !=, not-in, >, or >=) on field '${e.toString()}' and so you must also use '${e.toString()}' as your first argument to orderBy(), but your first orderBy() is on field '${n.toString()}' instead.`);\n}\n\nfunction bl(t, e) {\n if (!(e instanceof il || e instanceof ol)) throw new L(B.INVALID_ARGUMENT, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`);\n}\n\nclass Pl {\n convertValue(t, e = \"none\") {\n switch (ee(t)) {\n case 0 /* TypeOrder.NullValue */ :\n return null;\n\n case 1 /* TypeOrder.BooleanValue */ :\n return t.booleanValue;\n\n case 2 /* TypeOrder.NumberValue */ :\n return zt(t.integerValue || t.doubleValue);\n\n case 3 /* TypeOrder.TimestampValue */ :\n return this.convertTimestamp(t.timestampValue);\n\n case 4 /* TypeOrder.ServerTimestampValue */ :\n return this.convertServerTimestamp(t, e);\n\n case 5 /* TypeOrder.StringValue */ :\n return t.stringValue;\n\n case 6 /* TypeOrder.BlobValue */ :\n return this.convertBytes(Ht(t.bytesValue));\n\n case 7 /* TypeOrder.RefValue */ :\n return this.convertReference(t.referenceValue);\n\n case 8 /* TypeOrder.GeoPointValue */ :\n return this.convertGeoPoint(t.geoPointValue);\n\n case 9 /* TypeOrder.ArrayValue */ :\n return this.convertArray(t.arrayValue, e);\n\n case 10 /* TypeOrder.ObjectValue */ :\n return this.convertObject(t.mapValue, e);\n\n default:\n throw O();\n }\n }\n convertObject(t, e) {\n const n = {};\n return Bt(t.fields, ((t, s) => {\n n[t] = this.convertValue(s, e);\n })), n;\n }\n convertGeoPoint(t) {\n return new Rh(zt(t.latitude), zt(t.longitude));\n }\n convertArray(t, e) {\n return (t.values || []).map((t => this.convertValue(t, e)));\n }\n convertServerTimestamp(t, e) {\n switch (e) {\n case \"previous\":\n const n = Yt(t);\n return null == n ? null : this.convertValue(n, e);\n\n case \"estimate\":\n return this.convertTimestamp(Xt(t));\n\n default:\n return null;\n }\n }\n convertTimestamp(t) {\n const e = Wt(t);\n return new nt(e.seconds, e.nanos);\n }\n convertDocumentKey(t, e) {\n const n = rt.fromString(t);\n M(wi(n));\n const s = new Ft(n.get(1), n.get(3)), i = new ct(n.popFirst(5));\n return s.isEqual(e) || \n // TODO(b/64130202): Somehow support foreign references.\n x(`Document ${i} contains a document reference within a different database (${s.projectId}/${s.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), \n i;\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */ function vl(t, e, n) {\n let s;\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return s = t ? n && (n.merge || n.mergeFields) ? t.toFirestore(e, n) : t.toFirestore(e) : e, \n s;\n}\n\nclass Vl extends Pl {\n constructor(t) {\n super(), this.firestore = t;\n }\n convertBytes(t) {\n return new Ih(t);\n }\n convertReference(t) {\n const e = this.convertDocumentKey(t, this.firestore._databaseId);\n return new ya(this.firestore, /* converter= */ null, e);\n }\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Metadata about a snapshot, describing the state of the snapshot.\n */ class Sl {\n /** @hideconstructor */\n constructor(t, e) {\n this.hasPendingWrites = t, this.fromCache = e;\n }\n /**\n * Returns true if this `SnapshotMetadata` is equal to the provided one.\n *\n * @param other - The `SnapshotMetadata` to compare against.\n * @returns true if this `SnapshotMetadata` is equal to the provided one.\n */ isEqual(t) {\n return this.hasPendingWrites === t.hasPendingWrites && this.fromCache === t.fromCache;\n }\n}\n\n/**\n * A `DocumentSnapshot` contains data read from a document in your Firestore\n * database. The data can be extracted with `.data()` or `.get(<field>)` to\n * get a specific field.\n *\n * For a `DocumentSnapshot` that points to a non-existing document, any data\n * access will return 'undefined'. You can use the `exists()` method to\n * explicitly verify a document's existence.\n */ class Dl extends Yh {\n /** @hideconstructor protected */\n constructor(t, e, n, s, i, r) {\n super(t, e, n, s, r), this._firestore = t, this._firestoreImpl = t, this.metadata = i;\n }\n /**\n * Returns whether or not the data exists. True if the document exists.\n */ exists() {\n return super.exists();\n }\n /**\n * Retrieves all fields in the document as an `Object`. Returns `undefined` if\n * the document doesn't exist.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document or `undefined` if\n * the document doesn't exist.\n */ data(t = {}) {\n if (this._document) {\n if (this._converter) {\n // We only want to use the converter and create a new DocumentSnapshot\n // if a converter has been provided.\n const e = new Cl(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, \n /* converter= */ null);\n return this._converter.fromFirestore(e, t);\n }\n return this._userDataWriter.convertValue(this._document.data.value, t.serverTimestamps);\n }\n }\n /**\n * Retrieves the field specified by `fieldPath`. Returns `undefined` if the\n * document or field doesn't exist.\n *\n * By default, a `serverTimestamp()` that has not yet been set to\n * its final value will be returned as `null`. You can override this by\n * passing an options object.\n *\n * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific\n * field.\n * @param options - An options object to configure how the field is retrieved\n * from the snapshot (for example the desired behavior for server timestamps\n * that have not yet been set to their final value).\n * @returns The data at the specified field location or undefined if no such\n * field exists in the document.\n */\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get(t, e = {}) {\n if (this._document) {\n const n = this._document.data.field(Zh(\"DocumentSnapshot.get\", t));\n if (null !== n) return this._userDataWriter.convertValue(n, e.serverTimestamps);\n }\n }\n}\n\n/**\n * A `QueryDocumentSnapshot` contains data read from a document in your\n * Firestore database as part of a query. The document is guaranteed to exist\n * and its data can be extracted with `.data()` or `.get(<field>)` to get a\n * specific field.\n *\n * A `QueryDocumentSnapshot` offers the same API surface as a\n * `DocumentSnapshot`. Since query results contain only existing documents, the\n * `exists` property will always be true and `data()` will never return\n * 'undefined'.\n */ class Cl extends Dl {\n /**\n * Retrieves all fields in the document as an `Object`.\n *\n * By default, `serverTimestamp()` values that have not yet been\n * set to their final value will be returned as `null`. You can override\n * this by passing an options object.\n *\n * @override\n * @param options - An options object to configure how data is retrieved from\n * the snapshot (for example the desired behavior for server timestamps that\n * have not yet been set to their final value).\n * @returns An `Object` containing all fields in the document.\n */\n data(t = {}) {\n return super.data(t);\n }\n}\n\n/**\n * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects\n * representing the results of a query. The documents can be accessed as an\n * array via the `docs` property or enumerated using the `forEach` method. The\n * number of documents can be determined via the `empty` and `size`\n * properties.\n */ class xl {\n /** @hideconstructor */\n constructor(t, e, n, s) {\n this._firestore = t, this._userDataWriter = e, this._snapshot = s, this.metadata = new Sl(s.hasPendingWrites, s.fromCache), \n this.query = n;\n }\n /** An array of all the documents in the `QuerySnapshot`. */ get docs() {\n const t = [];\n return this.forEach((e => t.push(e))), t;\n }\n /** The number of documents in the `QuerySnapshot`. */ get size() {\n return this._snapshot.docs.size;\n }\n /** True if there are no documents in the `QuerySnapshot`. */ get empty() {\n return 0 === this.size;\n }\n /**\n * Enumerates all of the documents in the `QuerySnapshot`.\n *\n * @param callback - A callback to be called with a `QueryDocumentSnapshot` for\n * each document in the snapshot.\n * @param thisArg - The `this` binding for the callback.\n */ forEach(t, e) {\n this._snapshot.docs.forEach((n => {\n t.call(e, new Cl(this._firestore, this._userDataWriter, n.key, n, new Sl(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter));\n }));\n }\n /**\n * Returns an array of the documents changes since the last snapshot. If this\n * is the first snapshot, all documents will be in the list as 'added'\n * changes.\n *\n * @param options - `SnapshotListenOptions` that control whether metadata-only\n * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger\n * snapshot events.\n */ docChanges(t = {}) {\n const e = !!t.includeMetadataChanges;\n if (e && this._snapshot.excludesMetadataChanges) throw new L(B.INVALID_ARGUMENT, \"To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot().\");\n return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === e || (this._cachedChanges = \n /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */\n function(t, e) {\n if (t._snapshot.oldDocs.isEmpty()) {\n let e = 0;\n return t._snapshot.docChanges.map((n => {\n const s = new Cl(t._firestore, t._userDataWriter, n.doc.key, n.doc, new Sl(t._snapshot.mutatedKeys.has(n.doc.key), t._snapshot.fromCache), t.query.converter);\n return n.doc, {\n type: \"added\",\n doc: s,\n oldIndex: -1,\n newIndex: e++\n };\n }));\n }\n {\n // A `DocumentSet` that is updated incrementally as changes are applied to use\n // to lookup the index of a document.\n let n = t._snapshot.oldDocs;\n return t._snapshot.docChanges.filter((t => e || 3 /* ChangeType.Metadata */ !== t.type)).map((e => {\n const s = new Cl(t._firestore, t._userDataWriter, e.doc.key, e.doc, new Sl(t._snapshot.mutatedKeys.has(e.doc.key), t._snapshot.fromCache), t.query.converter);\n let i = -1, r = -1;\n return 0 /* ChangeType.Added */ !== e.type && (i = n.indexOf(e.doc.key), n = n.delete(e.doc.key)), \n 1 /* ChangeType.Removed */ !== e.type && (n = n.add(e.doc), r = n.indexOf(e.doc.key)), \n {\n type: Nl(e.type),\n doc: s,\n oldIndex: i,\n newIndex: r\n };\n }));\n }\n }(this, e), this._cachedChangesIncludeMetadataChanges = e), this._cachedChanges;\n }\n}\n\nfunction Nl(t) {\n switch (t) {\n case 0 /* ChangeType.Added */ :\n return \"added\";\n\n case 2 /* ChangeType.Modified */ :\n case 3 /* ChangeType.Metadata */ :\n return \"modified\";\n\n case 1 /* ChangeType.Removed */ :\n return \"removed\";\n\n default:\n return O();\n }\n}\n\n// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot\n// metadata\n/**\n * Returns true if the provided snapshots are equal.\n *\n * @param left - A snapshot to compare.\n * @param right - A snapshot to compare.\n * @returns true if the snapshots are equal.\n */ function kl(t, e) {\n return t instanceof Dl && e instanceof Dl ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof xl && e instanceof xl && (t._firestore === e._firestore && ba(t.query, e.query) && t.metadata.isEqual(e.metadata) && t._snapshot.isEqual(e._snapshot));\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Reads the document referred to by this `DocumentReference`.\n *\n * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting\n * for data from the server, but it may return cached data or fail if you are\n * offline and the server cannot be reached. To specify this behavior, invoke\n * {@link getDocFromCache} or {@link getDocFromServer}.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function Ol(t) {\n t = fa(t, ya);\n const e = fa(t.firestore, ih);\n return za(uh(e), t._key).then((n => Hl(e, t, n)));\n}\n\nclass Ml extends Pl {\n constructor(t) {\n super(), this.firestore = t;\n }\n convertBytes(t) {\n return new Ih(t);\n }\n convertReference(t) {\n const e = this.convertDocumentKey(t, this.firestore._databaseId);\n return new ya(this.firestore, /* converter= */ null, e);\n }\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from cache.\n * Returns an error if the document is not currently cached.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function Fl(t) {\n t = fa(t, ya);\n const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);\n return Wa(n, t._key).then((n => new Dl(e, s, t._key, n, new Sl(null !== n && n.hasLocalMutations, \n /* fromCache= */ !0), t.converter)));\n}\n\n/**\n * Reads the document referred to by this `DocumentReference` from the server.\n * Returns an error if the network is not available.\n *\n * @returns A `Promise` resolved with a `DocumentSnapshot` containing the\n * current document contents.\n */ function $l(t) {\n t = fa(t, ya);\n const e = fa(t.firestore, ih);\n return za(uh(e), t._key, {\n source: \"server\"\n }).then((n => Hl(e, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot`.\n *\n * Note: `getDocs()` attempts to provide up-to-date data when possible by\n * waiting for data from the server, but it may return cached data or fail if\n * you are offline and the server cannot be reached. To specify this behavior,\n * invoke {@link getDocsFromCache} or {@link getDocsFromServer}.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function Bl(t) {\n t = fa(t, pa);\n const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);\n return tl(t._query), Ja(n, t._query).then((n => new xl(e, s, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from cache.\n * Returns an empty result set if no documents matching the query are currently\n * cached.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function Ll(t) {\n t = fa(t, pa);\n const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);\n return Ha(n, t._query).then((n => new xl(e, s, t, n)));\n}\n\n/**\n * Executes the query and returns the results as a `QuerySnapshot` from the\n * server. Returns an error if the network is not available.\n *\n * @returns A `Promise` that will be resolved with the results of the query.\n */ function ql(t) {\n t = fa(t, pa);\n const e = fa(t.firestore, ih), n = uh(e), s = new Ml(e);\n return Ja(n, t._query, {\n source: \"server\"\n }).then((n => new xl(e, s, t, n)));\n}\n\nfunction Ul(t, e, n) {\n t = fa(t, ya);\n const s = fa(t.firestore, ih), i = vl(t.converter, e, n);\n return zl(s, [ xh(Ch(s), \"setDoc\", t._key, i, null !== t.converter, n).toMutation(t._key, Qn.none()) ]);\n}\n\nfunction Kl(t, e, n, ...s) {\n t = fa(t, ya);\n const i = fa(t.firestore, ih), r = Ch(i);\n let o;\n o = \"string\" == typeof (\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n e = d(e)) || e instanceof Th ? Lh(r, \"updateDoc\", t._key, e, n, s) : Bh(r, \"updateDoc\", t._key, e);\n return zl(i, [ o.toMutation(t._key, Qn.exists(!0)) ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * @param reference - A reference to the document to delete.\n * @returns A Promise resolved once the document has been successfully\n * deleted from the backend (note that it won't resolve while you're offline).\n */ function Gl(t) {\n return zl(fa(t.firestore, ih), [ new is(t._key, Qn.none()) ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend (Note that it\n * won't resolve while you're offline).\n */ function Ql(t, e) {\n const n = fa(t.firestore, ih), s = Aa(t), i = vl(t.converter, e);\n return zl(n, [ xh(Ch(t.firestore), \"addDoc\", s._key, i, null !== t.converter, {}).toMutation(s._key, Qn.exists(!1)) ]).then((() => s));\n}\n\nfunction jl(t, ...e) {\n var n, s, i;\n t = d(t);\n let r = {\n includeMetadataChanges: !1\n }, o = 0;\n \"object\" != typeof e[o] || eh(e[o]) || (r = e[o], o++);\n const u = {\n includeMetadataChanges: r.includeMetadataChanges\n };\n if (eh(e[o])) {\n const t = e[o];\n e[o] = null === (n = t.next) || void 0 === n ? void 0 : n.bind(t), e[o + 1] = null === (s = t.error) || void 0 === s ? void 0 : s.bind(t), \n e[o + 2] = null === (i = t.complete) || void 0 === i ? void 0 : i.bind(t);\n }\n let c, a, h;\n if (t instanceof ya) a = fa(t.firestore, ih), h = ln(t._key.path), c = {\n next: n => {\n e[o] && e[o](Hl(a, t, n));\n },\n error: e[o + 1],\n complete: e[o + 2]\n }; else {\n const n = fa(t, pa);\n a = fa(n.firestore, ih), h = n._query;\n const s = new Ml(a);\n c = {\n next: t => {\n e[o] && e[o](new xl(a, s, n, t));\n },\n error: e[o + 1],\n complete: e[o + 2]\n }, tl(t._query);\n }\n return function(t, e, n, s) {\n const i = new va(s), r = new _c(e, i, n);\n return t.asyncQueue.enqueueAndForget((async () => ac(await Ga(t), r))), () => {\n i.bc(), t.asyncQueue.enqueueAndForget((async () => hc(await Ga(t), r)));\n };\n }(uh(a), h, u, c);\n}\n\nfunction Wl(t, e) {\n return Ya(uh(t = fa(t, ih)), eh(e) ? e : {\n next: e\n });\n}\n\n/**\n * Locally writes `mutations` on the async queue.\n * @internal\n */ function zl(t, e) {\n return function(t, e) {\n const n = new q;\n return t.asyncQueue.enqueueAndForget((async () => Vc(await Ua(t), e, n))), n.promise;\n }(uh(t), e);\n}\n\n/**\n * Converts a {@link ViewSnapshot} that contains the single document specified by `ref`\n * to a {@link DocumentSnapshot}.\n */ function Hl(t, e, n) {\n const s = n.docs.get(e._key), i = new Ml(t);\n return new Dl(t, i, e._key, s, new Sl(n.hasPendingWrites, n.fromCache), e.converter);\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */ function Jl(t, e) {\n return ba(t.query, e.query) && _(t.data(), e.data());\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Calculates the number of documents in the result set of the given query,\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can even\n * count the documents if the result set would be prohibitively large to\n * download entirely (e.g. thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used: every request using this source necessarily involves a round trip to\n * the server.\n *\n * @param query - The query whose result set size to calculate.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */ function Yl(t) {\n const e = fa(t.firestore, ih);\n return function(t, e, n) {\n const s = new q;\n return t.asyncQueue.enqueueAndForget((async () => {\n try {\n if (Mu(await qa(t))) {\n const i = await Ka(t), r = new Ca(e, i, n).run();\n s.resolve(r);\n } else s.reject(new L(B.UNAVAILABLE, \"Failed to get count result because the client is offline.\"));\n } catch (t) {\n s.reject(t);\n }\n })), s.promise;\n }(uh(e), t, new Ml(e));\n}\n\n/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ const Xl = {\n maxAttempts: 5\n};\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nclass Zl {\n /** @hideconstructor */\n constructor(t, e) {\n this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, \n this._dataReader = Ch(t);\n }\n set(t, e, n) {\n this._verifyNotCommitted();\n const s = tf(t, this._firestore), i = vl(s.converter, e, n), r = xh(this._dataReader, \"WriteBatch.set\", s._key, i, null !== s.converter, n);\n return this._mutations.push(r.toMutation(s._key, Qn.none())), this;\n }\n update(t, e, n, ...s) {\n this._verifyNotCommitted();\n const i = tf(t, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let r;\n return r = \"string\" == typeof (e = d(e)) || e instanceof Th ? Lh(this._dataReader, \"WriteBatch.update\", i._key, e, n, s) : Bh(this._dataReader, \"WriteBatch.update\", i._key, e), \n this._mutations.push(r.toMutation(i._key, Qn.exists(!0))), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */ delete(t) {\n this._verifyNotCommitted();\n const e = tf(t, this._firestore);\n return this._mutations = this._mutations.concat(new is(e._key, Qn.none())), this;\n }\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */ commit() {\n return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve();\n }\n _verifyNotCommitted() {\n if (this._committed) throw new L(B.FAILED_PRECONDITION, \"A write batch can no longer be used after commit() has been called.\");\n }\n}\n\nfunction tf(t, e) {\n if ((t = d(t)).firestore !== e) throw new L(B.INVALID_ARGUMENT, \"Provided document reference is from a different Firestore instance.\");\n return t;\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nclass ef extends class {\n /** @hideconstructor */\n constructor(t, e) {\n this._firestore = t, this._transaction = e, this._dataReader = Ch(t);\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(t) {\n const e = tf(t, this._firestore), n = new Vl(this._firestore);\n return this._transaction.lookup([ e._key ]).then((t => {\n if (!t || 1 !== t.length) return O();\n const s = t[0];\n if (s.isFoundDocument()) return new Yh(this._firestore, n, s.key, s, e.converter);\n if (s.isNoDocument()) return new Yh(this._firestore, n, e._key, null, e.converter);\n throw O();\n }));\n }\n set(t, e, n) {\n const s = tf(t, this._firestore), i = vl(s.converter, e, n), r = xh(this._dataReader, \"Transaction.set\", s._key, i, null !== s.converter, n);\n return this._transaction.set(s._key, r), this;\n }\n update(t, e, n, ...s) {\n const i = tf(t, this._firestore);\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n let r;\n return r = \"string\" == typeof (e = d(e)) || e instanceof Th ? Lh(this._dataReader, \"Transaction.update\", i._key, e, n, s) : Bh(this._dataReader, \"Transaction.update\", i._key, e), \n this._transaction.update(i._key, r), this;\n }\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */ delete(t) {\n const e = tf(t, this._firestore);\n return this._transaction.delete(e._key), this;\n }\n} {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n /** @hideconstructor */\n constructor(t, e) {\n super(t, e), this._firestore = t;\n }\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */ get(t) {\n const e = tf(t, this._firestore), n = new Ml(this._firestore);\n return super.get(t).then((t => new Dl(this._firestore, n, e._key, t._document, new Sl(\n /* hasPendingWrites= */ !1, \n /* fromCache= */ !1), e.converter)));\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */ function nf(t, e, n) {\n t = fa(t, ih);\n const s = Object.assign(Object.assign({}, Xl), n);\n !function(t) {\n if (t.maxAttempts < 1) throw new L(B.INVALID_ARGUMENT, \"Max attempts must be at least 1\");\n }(s);\n return function(t, e, n) {\n const s = new q;\n return t.asyncQueue.enqueueAndForget((async () => {\n const i = await Ka(t);\n new Na(t.asyncQueue, i, n, e, s).run();\n })), s.promise;\n }(uh(t), (n => e(new ef(t, n))), s);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */ function sf() {\n return new Nh(\"deleteField\");\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */ function rf() {\n return new Oh(\"serverTimestamp\");\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */ function of(...t) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new Mh(\"arrayUnion\", t);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function uf(...t) {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new Fh(\"arrayRemove\", t);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */ function cf(t) {\n return new $h(\"increment\", t);\n}\n\n/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */ function af(t) {\n return uh(t = fa(t, ih)), new Zl(t, (e => zl(t, e)));\n}\n\n/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */ function hf(t, e) {\n var n;\n const s = uh(t = fa(t, ih));\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n if (!(null === (n = s.offlineComponents) || void 0 === n ? void 0 : n.indexBackfillerScheduler)) return N(\"Cannot enable indexes when persistence is disabled\"), \n Promise.resolve();\n const i = function(t) {\n const e = \"string\" == typeof t ? function(t) {\n try {\n return JSON.parse(t);\n } catch (t) {\n throw new L(B.INVALID_ARGUMENT, \"Failed to parse JSON: \" + (null == t ? void 0 : t.message));\n }\n }(t) : t, n = [];\n if (Array.isArray(e.indexes)) for (const t of e.indexes) {\n const e = lf(t, \"collectionGroup\"), s = [];\n if (Array.isArray(t.fields)) for (const e of t.fields) {\n const t = zh(\"setIndexConfiguration\", lf(e, \"fieldPath\"));\n \"CONTAINS\" === e.arrayConfig ? s.push(new dt(t, 2 /* IndexKind.CONTAINS */)) : \"ASCENDING\" === e.order ? s.push(new dt(t, 0 /* IndexKind.ASCENDING */)) : \"DESCENDING\" === e.order && s.push(new dt(t, 1 /* IndexKind.DESCENDING */));\n }\n n.push(new at(at.UNKNOWN_ID, e, s, wt.empty()));\n }\n return n;\n }(e);\n return La(s).then((t => async function(t, e) {\n const n = $(t), s = n.indexManager, i = [];\n return n.persistence.runTransaction(\"Configure indexes\", \"readwrite\", (t => s.getFieldIndexes(t).next((n => function(t, e, n, s, i) {\n t = [ ...t ], e = [ ...e ], t.sort(n), e.sort(n);\n const r = t.length, o = e.length;\n let u = 0, c = 0;\n for (;u < o && c < r; ) {\n const r = n(t[c], e[u]);\n r < 0 ? \n // The element was removed if the next element in our ordered\n // walkthrough is only in `before`.\n i(t[c++]) : r > 0 ? \n // The element was added if the next element in our ordered walkthrough\n // is only in `after`.\n s(e[u++]) : (u++, c++);\n }\n for (;u < o; ) s(e[u++]);\n for (;c < r; ) i(t[c++]);\n }(n, e, ft, (e => {\n i.push(s.addFieldIndex(t, e));\n }), (e => {\n i.push(s.deleteFieldIndex(t, e));\n })))).next((() => At.waitFor(i)))));\n }\n /**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n // The format of the LocalStorage key that stores the client state is:\n // firestore_clients_<persistence_prefix>_<instance_key>\n (t, i)));\n}\n\nfunction lf(t, e) {\n if (\"string\" != typeof t[e]) throw new L(B.INVALID_ARGUMENT, \"Missing string value for: \" + e);\n return t[e];\n}\n\n/**\n * Cloud Firestore\n *\n * @packageDocumentation\n */ !function(t, e = !0) {\n !function(t) {\n v = t;\n }(i), n(new r(\"firestore\", ((t, {instanceIdentifier: n, options: s}) => {\n const i = t.getProvider(\"app\").getImmediate(), r = new ih(new Q(t.getProvider(\"auth-internal\")), new H(t.getProvider(\"app-check-internal\")), function(t, e) {\n if (!Object.prototype.hasOwnProperty.apply(t.options, [ \"projectId\" ])) throw new L(B.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n return new Ft(t.options.projectId, e);\n }(i, n), i);\n return s = Object.assign({\n useFetchStreams: e\n }, s), r._setSettings(s), r;\n }), \"PUBLIC\").setMultipleInstances(!0)), s(b, \"3.8.1\", t), \n // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation\n s(b, \"3.8.1\", \"__BUILD_TARGET__\");\n}();\n\nexport { Pl as AbstractUserDataWriter, Sa as AggregateField, Da as AggregateQuerySnapshot, Ih as Bytes, sh as CACHE_SIZE_UNLIMITED, Ia as CollectionReference, ya as DocumentReference, Dl as DocumentSnapshot, Th as FieldPath, Ah as FieldValue, ih as Firestore, L as FirestoreError, Rh as GeoPoint, nh as LoadBundleTask, pa as Query, ol as QueryCompositeFilterConstraint, nl as QueryConstraint, Cl as QueryDocumentSnapshot, gl as QueryEndAtConstraint, il as QueryFieldFilterConstraint, ll as QueryLimitConstraint, al as QueryOrderByConstraint, xl as QuerySnapshot, _l as QueryStartAtConstraint, Sl as SnapshotMetadata, nt as Timestamp, ef as Transaction, Zl as WriteBatch, Ft as _DatabaseId, ct as _DocumentKey, J as _EmptyAppCheckTokenProvider, K as _EmptyAuthCredentialsProvider, ut as _FieldPath, fa as _cast, F as _debugAssert, Gt as _isBase64Available, N as _logWarn, ca as _validateIsNotUsedTogether, Ql as addDoc, Jl as aggregateQuerySnapshotEqual, cl as and, uf as arrayRemove, of as arrayUnion, fh as clearIndexedDbPersistence, Ta as collection, Ea as collectionGroup, ga as connectFirestoreEmulator, Gl as deleteDoc, sf as deleteField, wh as disableNetwork, Aa as doc, Eh as documentId, ah as enableIndexedDbPersistence, hh as enableMultiTabIndexedDbPersistence, _h as enableNetwork, pl as endAt, yl as endBefore, uh as ensureFirestoreConfigured, zl as executeWrite, Yl as getCountFromServer, Ol as getDoc, Fl as getDocFromCache, $l as getDocFromServer, Bl as getDocs, Ll as getDocsFromCache, ql as getDocsFromServer, oh as getFirestore, cf as increment, rh as initializeFirestore, fl as limit, dl as limitToLast, gh as loadBundle, yh as namedQuery, jl as onSnapshot, Wl as onSnapshotsInSync, ul as or, hl as orderBy, sl as query, ba as queryEqual, Ra as refEqual, nf as runTransaction, rf as serverTimestamp, Ul as setDoc, hf as setIndexConfiguration, D as setLogLevel, kl as snapshotEqual, ml as startAfter, wl as startAt, mh as terminate, Kl as updateDoc, dh as waitForPendingWrites, rl as where, af as writeBatch };\n//# sourceMappingURL=index.esm2017.js.map\n","/**\n * @license\n * Copyright The Closure Library Authors.\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * @fileoverview Default factory for <code>WebChannelTransport</code> to\n * avoid exposing concrete classes to clients.\n */\n\ngoog.provide('goog.net.createWebChannelTransport');\n\ngoog.require('goog.labs.net.webChannel.WebChannelBaseTransport');\ngoog.requireType('goog.net.WebChannelTransport');\n\n\n/**\n * Create a new WebChannelTransport instance using the default implementation.\n * Throws an error message if no default transport available in the current\n * environment.\n *\n * @return {!goog.net.WebChannelTransport} the newly created transport instance.\n */\ngoog.net.createWebChannelTransport = function() {\n 'use strict';\n return new goog.labs.net.webChannel.WebChannelBaseTransport();\n};\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { base64urlEncodeWithoutPadding } from './crypt';\n\n// Firebase Auth tokens contain snake_case claims following the JWT standard / convention.\n/* eslint-disable camelcase */\n\nexport type FirebaseSignInProvider =\n | 'custom'\n | 'email'\n | 'password'\n | 'phone'\n | 'anonymous'\n | 'google.com'\n | 'facebook.com'\n | 'github.com'\n | 'twitter.com'\n | 'microsoft.com'\n | 'apple.com';\n\ninterface FirebaseIdToken {\n // Always set to https://securetoken.google.com/PROJECT_ID\n iss: string;\n\n // Always set to PROJECT_ID\n aud: string;\n\n // The user's unique ID\n sub: string;\n\n // The token issue time, in seconds since epoch\n iat: number;\n\n // The token expiry time, normally 'iat' + 3600\n exp: number;\n\n // The user's unique ID. Must be equal to 'sub'\n user_id: string;\n\n // The time the user authenticated, normally 'iat'\n auth_time: number;\n\n // The sign in provider, only set when the provider is 'anonymous'\n provider_id?: 'anonymous';\n\n // The user's primary email\n email?: string;\n\n // The user's email verification status\n email_verified?: boolean;\n\n // The user's primary phone number\n phone_number?: string;\n\n // The user's display name\n name?: string;\n\n // The user's profile photo URL\n picture?: string;\n\n // Information on all identities linked to this user\n firebase: {\n // The primary sign-in provider\n sign_in_provider: FirebaseSignInProvider;\n\n // A map of providers to the user's list of unique identifiers from\n // each provider\n identities?: { [provider in FirebaseSignInProvider]?: string[] };\n };\n\n // Custom claims set by the developer\n [claim: string]: unknown;\n\n uid?: never; // Try to catch a common mistake of \"uid\" (should be \"sub\" instead).\n}\n\nexport type EmulatorMockTokenOptions = ({ user_id: string } | { sub: string }) &\n Partial<FirebaseIdToken>;\n\nexport function createMockUserToken(\n token: EmulatorMockTokenOptions,\n projectId?: string\n): string {\n if (token.uid) {\n throw new Error(\n 'The \"uid\" field is no longer supported by mockUserToken. Please use \"sub\" instead for Firebase Auth User ID.'\n );\n }\n // Unsecured JWTs use \"none\" as the algorithm.\n const header = {\n alg: 'none',\n type: 'JWT'\n };\n\n const project = projectId || 'demo-project';\n const iat = token.iat || 0;\n const sub = token.sub || token.user_id;\n if (!sub) {\n throw new Error(\"mockUserToken must contain 'sub' or 'user_id' field!\");\n }\n\n const payload: FirebaseIdToken = {\n // Set all required fields to decent defaults\n iss: `https://securetoken.google.com/${project}`,\n aud: project,\n iat,\n exp: iat + 3600,\n auth_time: iat,\n sub,\n user_id: sub,\n firebase: {\n sign_in_provider: 'custom',\n identities: {}\n },\n\n // Override with user options\n ...token\n };\n\n // Unsecured JWTs use the empty string as a signature.\n const signature = '';\n return [\n base64urlEncodeWithoutPadding(JSON.stringify(header)),\n base64urlEncodeWithoutPadding(JSON.stringify(payload)),\n signature\n ].join('.');\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport firebase from '@firebase/app-compat';\nimport type { FirebaseNamespace } from '@firebase/app-types';\nimport * as types from '@firebase/firestore-types';\n\nimport { name, version } from '../package.json';\n\nimport { Firestore, IndexedDbPersistenceProvider } from './api/database';\nimport { configureForFirebase } from './config';\n\nimport './register-module';\n\n/**\n * Registers the main Firestore build with the components framework.\n * Persistence can be enabled via `firebase.firestore().enablePersistence()`.\n */\nexport function registerFirestore(instance: FirebaseNamespace): void {\n configureForFirebase(\n instance,\n (app, firestoreExp) =>\n new Firestore(app, firestoreExp, new IndexedDbPersistenceProvider())\n );\n instance.registerVersion(name, version);\n}\n\nregisterFirestore(firebase as unknown as FirebaseNamespace);\n\ndeclare module '@firebase/app-compat' {\n interface FirebaseNamespace {\n firestore: {\n (app?: FirebaseApp): types.FirebaseFirestore;\n Blob: typeof types.Blob;\n CollectionReference: typeof types.CollectionReference;\n DocumentReference: typeof types.DocumentReference;\n DocumentSnapshot: typeof types.DocumentSnapshot;\n FieldPath: typeof types.FieldPath;\n FieldValue: typeof types.FieldValue;\n Firestore: typeof types.FirebaseFirestore;\n GeoPoint: typeof types.GeoPoint;\n Query: typeof types.Query;\n QueryDocumentSnapshot: typeof types.QueryDocumentSnapshot;\n QuerySnapshot: typeof types.QuerySnapshot;\n Timestamp: typeof types.Timestamp;\n Transaction: typeof types.Transaction;\n WriteBatch: typeof types.WriteBatch;\n setLogLevel: typeof types.setLogLevel;\n };\n }\n interface FirebaseApp {\n firestore?(): types.FirebaseFirestore;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { FirebaseApp } from '@firebase/app-compat';\nimport { FirebaseNamespace } from '@firebase/app-types';\nimport { _FirebaseNamespace } from '@firebase/app-types/private';\nimport { Component, ComponentType } from '@firebase/component';\nimport {\n Firestore as ModularFirestore,\n CACHE_SIZE_UNLIMITED,\n GeoPoint,\n Timestamp\n} from '@firebase/firestore';\n\nimport { Blob } from './api/blob';\nimport {\n Firestore,\n Transaction,\n CollectionReference,\n DocumentReference,\n DocumentSnapshot,\n Query,\n QueryDocumentSnapshot,\n QuerySnapshot,\n WriteBatch,\n setLogLevel\n} from './api/database';\nimport { FieldPath } from './api/field_path';\nimport { FieldValue } from './api/field_value';\n\nconst firestoreNamespace = {\n Firestore,\n GeoPoint,\n Timestamp,\n Blob,\n Transaction,\n WriteBatch,\n DocumentReference,\n DocumentSnapshot,\n Query,\n QueryDocumentSnapshot,\n QuerySnapshot,\n CollectionReference,\n FieldPath,\n FieldValue,\n setLogLevel,\n CACHE_SIZE_UNLIMITED\n};\n\n/**\n * Configures Firestore as part of the Firebase SDK by calling registerComponent.\n *\n * @param firebase - The FirebaseNamespace to register Firestore with\n * @param firestoreFactory - A factory function that returns a new Firestore\n * instance.\n */\nexport function configureForFirebase(\n firebase: FirebaseNamespace,\n firestoreFactory: (\n app: FirebaseApp,\n firestoreExp: ModularFirestore\n ) => Firestore\n): void {\n (firebase as _FirebaseNamespace).INTERNAL.registerComponent(\n new Component(\n 'firestore-compat',\n container => {\n const app = container.getProvider('app-compat').getImmediate()!;\n const firestoreExp = container.getProvider('firestore').getImmediate()!;\n return firestoreFactory(app, firestoreExp);\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setServiceProps({ ...firestoreNamespace })\n );\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '@firebase/firestore';\nimport { SetOptions } from '@firebase/firestore-types';\n\nexport function validateSetOptions(\n methodName: string,\n options: SetOptions | undefined\n): SetOptions {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n\n if (options.mergeFields !== undefined && options.merge !== undefined) {\n throw new FirestoreError(\n 'invalid-argument',\n `Invalid options passed to function ${methodName}(): You cannot ` +\n 'specify both \"merge\" and \"mergeFields\".'\n );\n }\n\n return options;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Bytes, FirestoreError, _isBase64Available } from '@firebase/firestore';\nimport { Compat } from '@firebase/util';\n\n/** Helper function to assert Uint8Array is available at runtime. */\nfunction assertUint8ArrayAvailable(): void {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(\n 'unimplemented',\n 'Uint8Arrays are not available in this environment.'\n );\n }\n}\n\n/** Helper function to assert Base64 functions are available at runtime. */\nfunction assertBase64Available(): void {\n if (!_isBase64Available()) {\n throw new FirestoreError(\n 'unimplemented',\n 'Blobs are unavailable in Firestore in this environment.'\n );\n }\n}\n\n/** Immutable class holding a blob (binary data) */\nexport class Blob implements Compat<Bytes> {\n constructor(readonly _delegate: Bytes) {}\n static fromBase64String(base64: string): Blob {\n assertBase64Available();\n return new Blob(Bytes.fromBase64String(base64));\n }\n\n static fromUint8Array(array: Uint8Array): Blob {\n assertUint8ArrayAvailable();\n return new Blob(Bytes.fromUint8Array(array));\n }\n\n toBase64(): string {\n assertBase64Available();\n return this._delegate.toBase64();\n }\n\n toUint8Array(): Uint8Array {\n assertUint8ArrayAvailable();\n return this._delegate.toUint8Array();\n }\n\n isEqual(other: Blob): boolean {\n return this._delegate.isEqual(other._delegate);\n }\n\n toString(): string {\n return 'Blob(base64: ' + this.toBase64() + ')';\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '@firebase/firestore';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn<T> = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver<T> {\n next?: NextFn<T>;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver<T>(obj: unknown): obj is PartialObserver<T> {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as Record<string, unknown>;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirebaseApp } from '@firebase/app-types';\nimport { _FirebaseApp, FirebaseService } from '@firebase/app-types/private';\nimport {\n LoadBundleTask,\n Bytes,\n clearIndexedDbPersistence,\n disableNetwork,\n enableIndexedDbPersistence,\n enableMultiTabIndexedDbPersistence,\n enableNetwork,\n ensureFirestoreConfigured,\n Firestore as ExpFirestore,\n connectFirestoreEmulator,\n waitForPendingWrites,\n FieldPath as ExpFieldPath,\n limit,\n limitToLast,\n where,\n orderBy,\n startAfter,\n startAt,\n query,\n endBefore,\n endAt,\n doc,\n collection,\n collectionGroup,\n queryEqual,\n Query as ExpQuery,\n CollectionReference as ExpCollectionReference,\n DocumentReference as ExpDocumentReference,\n refEqual,\n addDoc,\n deleteDoc,\n executeWrite,\n getDoc,\n getDocFromCache,\n getDocFromServer,\n getDocs,\n getDocsFromCache,\n getDocsFromServer,\n onSnapshot,\n onSnapshotsInSync,\n setDoc,\n updateDoc,\n Unsubscribe,\n DocumentChange as ExpDocumentChange,\n DocumentSnapshot as ExpDocumentSnapshot,\n QueryDocumentSnapshot as ExpQueryDocumentSnapshot,\n QuerySnapshot as ExpQuerySnapshot,\n snapshotEqual,\n SnapshotMetadata,\n runTransaction,\n Transaction as ExpTransaction,\n WriteBatch as ExpWriteBatch,\n AbstractUserDataWriter,\n FirestoreError,\n FirestoreDataConverter as ModularFirestoreDataConverter,\n setLogLevel as setClientLogLevel,\n _DatabaseId,\n _validateIsNotUsedTogether,\n _cast,\n _DocumentKey,\n _debugAssert,\n _FieldPath,\n _ResourcePath,\n _ByteString,\n _logWarn,\n namedQuery,\n loadBundle,\n PartialWithFieldValue,\n WithFieldValue\n} from '@firebase/firestore';\nimport {\n CollectionReference as PublicCollectionReference,\n DocumentChange as PublicDocumentChange,\n DocumentChangeType as PublicDocumentChangeType,\n DocumentData,\n DocumentData as PublicDocumentData,\n DocumentReference as PublicDocumentReference,\n DocumentSnapshot as PublicDocumentSnapshot,\n FieldPath as PublicFieldPath,\n FirebaseFirestore as PublicFirestore,\n FirestoreDataConverter as PublicFirestoreDataConverter,\n GetOptions as PublicGetOptions,\n LogLevel as PublicLogLevel,\n OrderByDirection as PublicOrderByDirection,\n PersistenceSettings as PublicPersistenceSettings,\n Query as PublicQuery,\n QueryDocumentSnapshot as PublicQueryDocumentSnapshot,\n QuerySnapshot as PublicQuerySnapshot,\n SetOptions as PublicSetOptions,\n Settings as PublicSettings,\n SnapshotListenOptions as PublicSnapshotListenOptions,\n SnapshotOptions as PublicSnapshotOptions,\n Transaction as PublicTransaction,\n UpdateData as PublicUpdateData,\n WhereFilterOp as PublicWhereFilterOp,\n WriteBatch as PublicWriteBatch\n} from '@firebase/firestore-types';\nimport {\n Compat,\n EmulatorMockTokenOptions,\n getModularInstance\n} from '@firebase/util';\n\nimport { validateSetOptions } from '../util/input_validation';\n\nimport { Blob } from './blob';\nimport {\n CompleteFn,\n ErrorFn,\n isPartialObserver,\n NextFn,\n PartialObserver\n} from './observer';\n\n/**\n * A persistence provider for either memory-only or IndexedDB persistence.\n * Mainly used to allow optional inclusion of IndexedDB code.\n */\nexport interface PersistenceProvider {\n enableIndexedDbPersistence(\n firestore: Firestore,\n forceOwnership: boolean\n ): Promise<void>;\n enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>;\n clearIndexedDbPersistence(firestore: Firestore): Promise<void>;\n}\n\n/**\n * The persistence provider included with the full Firestore SDK.\n */\nexport class IndexedDbPersistenceProvider implements PersistenceProvider {\n enableIndexedDbPersistence(\n firestore: Firestore,\n forceOwnership: boolean\n ): Promise<void> {\n return enableIndexedDbPersistence(firestore._delegate, { forceOwnership });\n }\n enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void> {\n return enableMultiTabIndexedDbPersistence(firestore._delegate);\n }\n clearIndexedDbPersistence(firestore: Firestore): Promise<void> {\n return clearIndexedDbPersistence(firestore._delegate);\n }\n}\n\n/**\n * Compat class for Firestore. Exposes Firestore Legacy API, but delegates\n * to the functional API of firestore-exp.\n */\nexport class Firestore\n implements PublicFirestore, FirebaseService, Compat<ExpFirestore>\n{\n _appCompat?: FirebaseApp;\n constructor(\n databaseIdOrApp: _DatabaseId | FirebaseApp,\n readonly _delegate: ExpFirestore,\n private _persistenceProvider: PersistenceProvider\n ) {\n if (!(databaseIdOrApp instanceof _DatabaseId)) {\n this._appCompat = databaseIdOrApp as FirebaseApp;\n }\n }\n\n get _databaseId(): _DatabaseId {\n return this._delegate._databaseId;\n }\n\n settings(settingsLiteral: PublicSettings): void {\n const currentSettings = this._delegate._getSettings();\n if (\n !settingsLiteral.merge &&\n currentSettings.host !== settingsLiteral.host\n ) {\n _logWarn(\n 'You are overriding the original host. If you did not intend ' +\n 'to override your settings, use {merge: true}.'\n );\n }\n\n if (settingsLiteral.merge) {\n settingsLiteral = {\n ...currentSettings,\n ...settingsLiteral\n };\n // Remove the property from the settings once the merge is completed\n delete settingsLiteral.merge;\n }\n\n this._delegate._setSettings(settingsLiteral);\n }\n\n useEmulator(\n host: string,\n port: number,\n options: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {}\n ): void {\n connectFirestoreEmulator(this._delegate, host, port, options);\n }\n\n enableNetwork(): Promise<void> {\n return enableNetwork(this._delegate);\n }\n\n disableNetwork(): Promise<void> {\n return disableNetwork(this._delegate);\n }\n\n enablePersistence(settings?: PublicPersistenceSettings): Promise<void> {\n let synchronizeTabs = false;\n let experimentalForceOwningTab = false;\n\n if (settings) {\n synchronizeTabs = !!settings.synchronizeTabs;\n experimentalForceOwningTab = !!settings.experimentalForceOwningTab;\n\n _validateIsNotUsedTogether(\n 'synchronizeTabs',\n synchronizeTabs,\n 'experimentalForceOwningTab',\n experimentalForceOwningTab\n );\n }\n\n return synchronizeTabs\n ? this._persistenceProvider.enableMultiTabIndexedDbPersistence(this)\n : this._persistenceProvider.enableIndexedDbPersistence(\n this,\n experimentalForceOwningTab\n );\n }\n\n clearPersistence(): Promise<void> {\n return this._persistenceProvider.clearIndexedDbPersistence(this);\n }\n\n terminate(): Promise<void> {\n if (this._appCompat) {\n (this._appCompat as _FirebaseApp)._removeServiceInstance(\n 'firestore-compat'\n );\n (this._appCompat as _FirebaseApp)._removeServiceInstance('firestore');\n }\n return this._delegate._delete();\n }\n\n waitForPendingWrites(): Promise<void> {\n return waitForPendingWrites(this._delegate);\n }\n\n onSnapshotsInSync(observer: PartialObserver<void>): Unsubscribe;\n onSnapshotsInSync(onSync: () => void): Unsubscribe;\n onSnapshotsInSync(arg: unknown): Unsubscribe {\n return onSnapshotsInSync(this._delegate, arg as PartialObserver<void>);\n }\n\n get app(): FirebaseApp {\n if (!this._appCompat) {\n throw new FirestoreError(\n 'failed-precondition',\n \"Firestore was not initialized using the Firebase SDK. 'app' is \" +\n 'not available'\n );\n }\n return this._appCompat as FirebaseApp;\n }\n\n INTERNAL = {\n delete: () => this.terminate()\n };\n\n collection(pathString: string): PublicCollectionReference {\n try {\n return new CollectionReference(\n this,\n collection(this._delegate, pathString)\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collection()',\n 'Firestore.collection()'\n );\n }\n }\n\n doc(pathString: string): PublicDocumentReference {\n try {\n return new DocumentReference(this, doc(this._delegate, pathString));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'doc()', 'Firestore.doc()');\n }\n }\n\n collectionGroup(collectionId: string): PublicQuery {\n try {\n return new Query(this, collectionGroup(this._delegate, collectionId));\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collectionGroup()',\n 'Firestore.collectionGroup()'\n );\n }\n }\n\n runTransaction<T>(\n updateFunction: (transaction: PublicTransaction) => Promise<T>\n ): Promise<T> {\n return runTransaction(this._delegate, transaction =>\n updateFunction(new Transaction(this, transaction))\n );\n }\n\n batch(): PublicWriteBatch {\n ensureFirestoreConfigured(this._delegate);\n return new WriteBatch(\n new ExpWriteBatch(this._delegate, mutations =>\n executeWrite(this._delegate, mutations)\n )\n );\n }\n\n loadBundle(\n bundleData: ArrayBuffer | ReadableStream<Uint8Array> | string\n ): LoadBundleTask {\n return loadBundle(this._delegate, bundleData);\n }\n\n namedQuery(name: string): Promise<PublicQuery<DocumentData> | null> {\n return namedQuery(this._delegate, name).then(expQuery => {\n if (!expQuery) {\n return null;\n }\n return new Query(\n this,\n // We can pass `expQuery` here directly since named queries don't have a UserDataConverter.\n // Otherwise, we would have to create a new ExpQuery and pass the old UserDataConverter.\n expQuery\n );\n });\n }\n}\n\nexport class UserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: _ByteString): Blob {\n return new Blob(new Bytes(bytes));\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return DocumentReference.forKey(key, this.firestore, /* converter= */ null);\n }\n}\n\nexport function setLogLevel(level: PublicLogLevel): void {\n setClientLogLevel(level);\n}\n\n/**\n * A reference to a transaction.\n */\nexport class Transaction implements PublicTransaction, Compat<ExpTransaction> {\n private _userDataWriter: UserDataWriter;\n\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpTransaction\n ) {\n this._userDataWriter = new UserDataWriter(_firestore);\n }\n\n get<T>(\n documentRef: PublicDocumentReference<T>\n ): Promise<PublicDocumentSnapshot<T>> {\n const ref = castReference(documentRef);\n return this._delegate\n .get(ref)\n .then(\n result =>\n new DocumentSnapshot(\n this._firestore,\n new ExpDocumentSnapshot<T>(\n this._firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n ref.converter\n )\n )\n );\n }\n\n set<T>(\n documentRef: DocumentReference<T>,\n data: Partial<T>,\n options: PublicSetOptions\n ): Transaction;\n set<T>(documentRef: DocumentReference<T>, data: T): Transaction;\n set<T>(\n documentRef: PublicDocumentReference<T>,\n data: T | Partial<T>,\n options?: PublicSetOptions\n ): Transaction {\n const ref = castReference(documentRef);\n if (options) {\n validateSetOptions('Transaction.set', options);\n this._delegate.set(ref, data as PartialWithFieldValue<T>, options);\n } else {\n this._delegate.set(ref, data as WithFieldValue<T>);\n }\n return this;\n }\n\n update(\n documentRef: PublicDocumentReference<unknown>,\n data: PublicUpdateData\n ): Transaction;\n update(\n documentRef: PublicDocumentReference<unknown>,\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction;\n update(\n documentRef: PublicDocumentReference<unknown>,\n dataOrField: unknown,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Transaction {\n const ref = castReference(documentRef);\n if (arguments.length === 2) {\n this._delegate.update(ref, dataOrField as PublicUpdateData);\n } else {\n this._delegate.update(\n ref,\n dataOrField as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n\n return this;\n }\n\n delete(documentRef: PublicDocumentReference<unknown>): Transaction {\n const ref = castReference(documentRef);\n this._delegate.delete(ref);\n return this;\n }\n}\n\nexport class WriteBatch implements PublicWriteBatch, Compat<ExpWriteBatch> {\n constructor(readonly _delegate: ExpWriteBatch) {}\n set<T>(\n documentRef: DocumentReference<T>,\n data: Partial<T>,\n options: PublicSetOptions\n ): WriteBatch;\n set<T>(documentRef: DocumentReference<T>, data: T): WriteBatch;\n set<T>(\n documentRef: PublicDocumentReference<T>,\n data: T | Partial<T>,\n options?: PublicSetOptions\n ): WriteBatch {\n const ref = castReference(documentRef);\n if (options) {\n validateSetOptions('WriteBatch.set', options);\n this._delegate.set(ref, data as PartialWithFieldValue<T>, options);\n } else {\n this._delegate.set(ref, data as WithFieldValue<T>);\n }\n return this;\n }\n\n update(\n documentRef: PublicDocumentReference<unknown>,\n data: PublicUpdateData\n ): WriteBatch;\n update(\n documentRef: PublicDocumentReference<unknown>,\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: PublicDocumentReference<unknown>,\n dataOrField: string | PublicFieldPath | PublicUpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n const ref = castReference(documentRef);\n if (arguments.length === 2) {\n this._delegate.update(ref, dataOrField as PublicUpdateData);\n } else {\n this._delegate.update(\n ref,\n dataOrField as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n return this;\n }\n\n delete(documentRef: PublicDocumentReference<unknown>): WriteBatch {\n const ref = castReference(documentRef);\n this._delegate.delete(ref);\n return this;\n }\n\n commit(): Promise<void> {\n return this._delegate.commit();\n }\n}\n\n/**\n * Wraps a `PublicFirestoreDataConverter` translating the types from the\n * experimental SDK into corresponding types from the Classic SDK before passing\n * them to the wrapped converter.\n */\nclass FirestoreDataConverter<U>\n implements\n ModularFirestoreDataConverter<U>,\n Compat<PublicFirestoreDataConverter<U>>\n{\n private static readonly INSTANCES = new WeakMap();\n\n private constructor(\n private readonly _firestore: Firestore,\n private readonly _userDataWriter: UserDataWriter,\n readonly _delegate: PublicFirestoreDataConverter<U>\n ) {}\n\n fromFirestore(\n snapshot: ExpQueryDocumentSnapshot,\n options?: PublicSnapshotOptions\n ): U {\n const expSnapshot = new ExpQueryDocumentSnapshot(\n this._firestore._delegate,\n this._userDataWriter,\n snapshot._key,\n snapshot._document,\n snapshot.metadata,\n /* converter= */ null\n );\n return this._delegate.fromFirestore(\n new QueryDocumentSnapshot(this._firestore, expSnapshot),\n options ?? {}\n );\n }\n\n toFirestore(modelObject: WithFieldValue<U>): PublicDocumentData;\n toFirestore(\n modelObject: PartialWithFieldValue<U>,\n options: PublicSetOptions\n ): PublicDocumentData;\n toFirestore(\n modelObject: WithFieldValue<U> | PartialWithFieldValue<U>,\n options?: PublicSetOptions\n ): PublicDocumentData {\n if (!options) {\n return this._delegate.toFirestore(modelObject as U);\n } else {\n return this._delegate.toFirestore(modelObject as Partial<U>, options);\n }\n }\n\n // Use the same instance of `FirestoreDataConverter` for the given instances\n // of `Firestore` and `PublicFirestoreDataConverter` so that isEqual() will\n // compare equal for two objects created with the same converter instance.\n static getInstance<U>(\n firestore: Firestore,\n converter: PublicFirestoreDataConverter<U>\n ): FirestoreDataConverter<U> {\n const converterMapByFirestore = FirestoreDataConverter.INSTANCES;\n let untypedConverterByConverter = converterMapByFirestore.get(firestore);\n if (!untypedConverterByConverter) {\n untypedConverterByConverter = new WeakMap();\n converterMapByFirestore.set(firestore, untypedConverterByConverter);\n }\n\n let instance = untypedConverterByConverter.get(converter);\n if (!instance) {\n instance = new FirestoreDataConverter(\n firestore,\n new UserDataWriter(firestore),\n converter\n );\n untypedConverterByConverter.set(converter, instance);\n }\n\n return instance;\n }\n}\n\n/**\n * A reference to a particular document in a collection in the database.\n */\nexport class DocumentReference<T = PublicDocumentData>\n implements PublicDocumentReference<T>, Compat<ExpDocumentReference<T>>\n{\n private _userDataWriter: UserDataWriter;\n\n constructor(\n readonly firestore: Firestore,\n readonly _delegate: ExpDocumentReference<T>\n ) {\n this._userDataWriter = new UserDataWriter(firestore);\n }\n\n static forPath<U>(\n path: _ResourcePath,\n firestore: Firestore,\n converter: ModularFirestoreDataConverter<U> | null\n ): DocumentReference<U> {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(\n 'invalid-argument',\n 'Invalid document reference. Document ' +\n 'references must have an even number of segments, but ' +\n `${path.canonicalString()} has ${path.length}`\n );\n }\n return new DocumentReference(\n firestore,\n new ExpDocumentReference(\n firestore._delegate,\n converter,\n new _DocumentKey(path)\n )\n );\n }\n\n static forKey<U>(\n key: _DocumentKey,\n firestore: Firestore,\n converter: ModularFirestoreDataConverter<U> | null\n ): DocumentReference<U> {\n return new DocumentReference(\n firestore,\n new ExpDocumentReference(firestore._delegate, converter, key)\n );\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get parent(): PublicCollectionReference<T> {\n return new CollectionReference(this.firestore, this._delegate.parent);\n }\n\n get path(): string {\n return this._delegate.path;\n }\n\n collection(\n pathString: string\n ): PublicCollectionReference<PublicDocumentData> {\n try {\n return new CollectionReference(\n this.firestore,\n collection(this._delegate, pathString)\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'collection()',\n 'DocumentReference.collection()'\n );\n }\n }\n\n isEqual(other: PublicDocumentReference<T>): boolean {\n other = getModularInstance<PublicDocumentReference<T>>(other);\n\n if (!(other instanceof ExpDocumentReference)) {\n return false;\n }\n return refEqual(this._delegate, other);\n }\n\n set(value: Partial<T>, options: PublicSetOptions): Promise<void>;\n set(value: T): Promise<void>;\n set(value: T | Partial<T>, options?: PublicSetOptions): Promise<void> {\n options = validateSetOptions('DocumentReference.set', options);\n try {\n if (options) {\n return setDoc(\n this._delegate,\n value as PartialWithFieldValue<T>,\n options\n );\n } else {\n return setDoc(this._delegate, value as WithFieldValue<T>);\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'setDoc()',\n 'DocumentReference.set()'\n );\n }\n }\n\n update(value: PublicUpdateData): Promise<void>;\n update(\n field: string | PublicFieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void>;\n update(\n fieldOrUpdateData: string | PublicFieldPath | PublicUpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): Promise<void> {\n try {\n if (arguments.length === 1) {\n return updateDoc(this._delegate, fieldOrUpdateData as PublicUpdateData);\n } else {\n return updateDoc(\n this._delegate,\n fieldOrUpdateData as string | ExpFieldPath,\n value,\n ...moreFieldsAndValues\n );\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'updateDoc()',\n 'DocumentReference.update()'\n );\n }\n }\n\n delete(): Promise<void> {\n return deleteDoc(this._delegate);\n }\n\n onSnapshot(observer: PartialObserver<PublicDocumentSnapshot<T>>): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n observer: PartialObserver<PublicDocumentSnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<PublicDocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n onNext: NextFn<PublicDocumentSnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n const options = extractSnapshotOptions(args);\n const observer = wrapObserver<DocumentSnapshot<T>, ExpDocumentSnapshot<T>>(\n args,\n result =>\n new DocumentSnapshot(\n this.firestore,\n new ExpDocumentSnapshot(\n this.firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n this._delegate.converter\n )\n )\n );\n return onSnapshot(this._delegate, options, observer);\n }\n\n get(options?: PublicGetOptions): Promise<PublicDocumentSnapshot<T>> {\n let snap: Promise<ExpDocumentSnapshot<T>>;\n if (options?.source === 'cache') {\n snap = getDocFromCache(this._delegate);\n } else if (options?.source === 'server') {\n snap = getDocFromServer(this._delegate);\n } else {\n snap = getDoc(this._delegate);\n }\n\n return snap.then(\n result =>\n new DocumentSnapshot(\n this.firestore,\n new ExpDocumentSnapshot(\n this.firestore._delegate,\n this._userDataWriter,\n result._key,\n result._document,\n result.metadata,\n this._delegate.converter\n )\n )\n );\n }\n\n withConverter(converter: null): PublicDocumentReference<PublicDocumentData>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U>\n ): PublicDocumentReference<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): PublicDocumentReference<U> {\n return new DocumentReference<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpDocumentReference<U>)\n );\n }\n}\n\n/**\n * Replaces the function name in an error thrown by the firestore-exp API\n * with the function names used in the classic API.\n */\nfunction replaceFunctionName(\n e: Error,\n original: string | RegExp,\n updated: string\n): Error {\n e.message = e.message.replace(original, updated);\n return e;\n}\n\n/**\n * Iterates the list of arguments from an `onSnapshot` call and returns the\n * first argument that may be an `SnapshotListenOptions` object. Returns an\n * empty object if none is found.\n */\nexport function extractSnapshotOptions(\n args: unknown[]\n): PublicSnapshotListenOptions {\n for (const arg of args) {\n if (typeof arg === 'object' && !isPartialObserver(arg)) {\n return arg as PublicSnapshotListenOptions;\n }\n }\n return {};\n}\n\n/**\n * Creates an observer that can be passed to the firestore-exp SDK. The\n * observer converts all observed values into the format expected by the classic\n * SDK.\n *\n * @param args - The list of arguments from an `onSnapshot` call.\n * @param wrapper - The function that converts the firestore-exp type into the\n * type used by this shim.\n */\nexport function wrapObserver<CompatType, ExpType>(\n args: unknown[],\n wrapper: (val: ExpType) => CompatType\n): PartialObserver<ExpType> {\n let userObserver: PartialObserver<CompatType>;\n if (isPartialObserver(args[0])) {\n userObserver = args[0] as PartialObserver<CompatType>;\n } else if (isPartialObserver(args[1])) {\n userObserver = args[1];\n } else if (typeof args[0] === 'function') {\n userObserver = {\n next: args[0] as NextFn<CompatType> | undefined,\n error: args[1] as ErrorFn | undefined,\n complete: args[2] as CompleteFn | undefined\n };\n } else {\n userObserver = {\n next: args[1] as NextFn<CompatType> | undefined,\n error: args[2] as ErrorFn | undefined,\n complete: args[3] as CompleteFn | undefined\n };\n }\n\n return {\n next: val => {\n if (userObserver!.next) {\n userObserver!.next(wrapper(val));\n }\n },\n error: userObserver.error?.bind(userObserver),\n complete: userObserver.complete?.bind(userObserver)\n };\n}\n\n/**\n * Options interface that can be provided to configure the deserialization of\n * DocumentSnapshots.\n */\nexport interface SnapshotOptions extends PublicSnapshotOptions {}\n\nexport class DocumentSnapshot<T = PublicDocumentData>\n implements PublicDocumentSnapshot<T>, Compat<ExpDocumentSnapshot<T>>\n{\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpDocumentSnapshot<T>\n ) {}\n\n get ref(): DocumentReference<T> {\n return new DocumentReference<T>(this._firestore, this._delegate.ref);\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get metadata(): SnapshotMetadata {\n return this._delegate.metadata;\n }\n\n get exists(): boolean {\n return this._delegate.exists();\n }\n\n data(options?: PublicSnapshotOptions): T | undefined {\n return this._delegate.data(options);\n }\n\n get(\n fieldPath: string | PublicFieldPath,\n options?: PublicSnapshotOptions\n // We are using `any` here to avoid an explicit cast by our users.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ): any {\n return this._delegate.get(fieldPath as string | ExpFieldPath, options);\n }\n\n isEqual(other: DocumentSnapshot<T>): boolean {\n return snapshotEqual(this._delegate, other._delegate);\n }\n}\n\nexport class QueryDocumentSnapshot<T = PublicDocumentData>\n extends DocumentSnapshot<T>\n implements PublicQueryDocumentSnapshot<T>\n{\n data(options?: PublicSnapshotOptions): T {\n const data = this._delegate.data(options);\n _debugAssert(\n data !== undefined,\n 'Document in a QueryDocumentSnapshot should exist'\n );\n return data;\n }\n}\n\nexport class Query<T = PublicDocumentData>\n implements PublicQuery<T>, Compat<ExpQuery<T>>\n{\n private readonly _userDataWriter: UserDataWriter;\n\n constructor(readonly firestore: Firestore, readonly _delegate: ExpQuery<T>) {\n this._userDataWriter = new UserDataWriter(firestore);\n }\n\n where(\n fieldPath: string | _FieldPath,\n opStr: PublicWhereFilterOp,\n value: unknown\n ): Query<T> {\n try {\n // The \"as string\" cast is a little bit of a hack. `where` accepts the\n // FieldPath Compat type as input, but is not typed as such in order to\n // not expose this via our public typings file.\n return new Query<T>(\n this.firestore,\n query(this._delegate, where(fieldPath as string, opStr, value))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n /(orderBy|where)\\(\\)/,\n 'Query.$1()'\n );\n }\n }\n\n orderBy(\n fieldPath: string | _FieldPath,\n directionStr?: PublicOrderByDirection\n ): Query<T> {\n try {\n // The \"as string\" cast is a little bit of a hack. `orderBy` accepts the\n // FieldPath Compat type as input, but is not typed as such in order to\n // not expose this via our public typings file.\n return new Query<T>(\n this.firestore,\n query(this._delegate, orderBy(fieldPath as string, directionStr))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n /(orderBy|where)\\(\\)/,\n 'Query.$1()'\n );\n }\n }\n\n limit(n: number): Query<T> {\n try {\n return new Query<T>(this.firestore, query(this._delegate, limit(n)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'limit()', 'Query.limit()');\n }\n }\n\n limitToLast(n: number): Query<T> {\n try {\n return new Query<T>(\n this.firestore,\n query(this._delegate, limitToLast(n))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'limitToLast()',\n 'Query.limitToLast()'\n );\n }\n }\n\n startAt(...args: any[]): Query<T> {\n try {\n return new Query(this.firestore, query(this._delegate, startAt(...args)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'startAt()', 'Query.startAt()');\n }\n }\n\n startAfter(...args: any[]): Query<T> {\n try {\n return new Query(\n this.firestore,\n query(this._delegate, startAfter(...args))\n );\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'startAfter()',\n 'Query.startAfter()'\n );\n }\n }\n\n endBefore(...args: any[]): Query<T> {\n try {\n return new Query(\n this.firestore,\n query(this._delegate, endBefore(...args))\n );\n } catch (e) {\n throw replaceFunctionName(e as Error, 'endBefore()', 'Query.endBefore()');\n }\n }\n\n endAt(...args: any[]): Query<T> {\n try {\n return new Query(this.firestore, query(this._delegate, endAt(...args)));\n } catch (e) {\n throw replaceFunctionName(e as Error, 'endAt()', 'Query.endAt()');\n }\n }\n\n isEqual(other: PublicQuery<T>): boolean {\n return queryEqual(this._delegate, (other as Query<T>)._delegate);\n }\n\n get(options?: PublicGetOptions): Promise<QuerySnapshot<T>> {\n let query: Promise<ExpQuerySnapshot<T>>;\n if (options?.source === 'cache') {\n query = getDocsFromCache(this._delegate);\n } else if (options?.source === 'server') {\n query = getDocsFromServer(this._delegate);\n } else {\n query = getDocs(this._delegate);\n }\n return query.then(\n result =>\n new QuerySnapshot(\n this.firestore,\n new ExpQuerySnapshot<T>(\n this.firestore._delegate,\n this._userDataWriter,\n this._delegate,\n result._snapshot\n )\n )\n );\n }\n\n onSnapshot(observer: PartialObserver<PublicQuerySnapshot<T>>): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n observer: PartialObserver<PublicQuerySnapshot<T>>\n ): Unsubscribe;\n onSnapshot(\n onNext: NextFn<PublicQuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n onSnapshot(\n options: PublicSnapshotListenOptions,\n onNext: NextFn<PublicQuerySnapshot<T>>,\n onError?: ErrorFn,\n onCompletion?: CompleteFn\n ): Unsubscribe;\n\n onSnapshot(...args: unknown[]): Unsubscribe {\n const options = extractSnapshotOptions(args);\n const observer = wrapObserver<QuerySnapshot<T>, ExpQuerySnapshot<T>>(\n args,\n snap =>\n new QuerySnapshot(\n this.firestore,\n new ExpQuerySnapshot<T>(\n this.firestore._delegate,\n this._userDataWriter,\n this._delegate,\n snap._snapshot\n )\n )\n );\n return onSnapshot(this._delegate, options, observer);\n }\n\n withConverter(converter: null): Query<PublicDocumentData>;\n withConverter<U>(converter: PublicFirestoreDataConverter<U>): Query<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): Query<U> {\n return new Query<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpQuery<U>)\n );\n }\n}\n\nexport class DocumentChange<T = PublicDocumentData>\n implements PublicDocumentChange<T>, Compat<ExpDocumentChange<T>>\n{\n constructor(\n private readonly _firestore: Firestore,\n readonly _delegate: ExpDocumentChange<T>\n ) {}\n\n get type(): PublicDocumentChangeType {\n return this._delegate.type;\n }\n\n get doc(): QueryDocumentSnapshot<T> {\n return new QueryDocumentSnapshot<T>(this._firestore, this._delegate.doc);\n }\n\n get oldIndex(): number {\n return this._delegate.oldIndex;\n }\n\n get newIndex(): number {\n return this._delegate.newIndex;\n }\n}\n\nexport class QuerySnapshot<T = PublicDocumentData>\n implements PublicQuerySnapshot<T>, Compat<ExpQuerySnapshot<T>>\n{\n constructor(\n readonly _firestore: Firestore,\n readonly _delegate: ExpQuerySnapshot<T>\n ) {}\n\n get query(): Query<T> {\n return new Query(this._firestore, this._delegate.query);\n }\n\n get metadata(): SnapshotMetadata {\n return this._delegate.metadata;\n }\n\n get size(): number {\n return this._delegate.size;\n }\n\n get empty(): boolean {\n return this._delegate.empty;\n }\n\n get docs(): Array<QueryDocumentSnapshot<T>> {\n return this._delegate.docs.map(\n doc => new QueryDocumentSnapshot<T>(this._firestore, doc)\n );\n }\n\n docChanges(\n options?: PublicSnapshotListenOptions\n ): Array<PublicDocumentChange<T>> {\n return this._delegate\n .docChanges(options)\n .map(docChange => new DocumentChange<T>(this._firestore, docChange));\n }\n\n forEach(\n callback: (result: QueryDocumentSnapshot<T>) => void,\n thisArg?: unknown\n ): void {\n this._delegate.forEach(snapshot => {\n callback.call(\n thisArg,\n new QueryDocumentSnapshot(this._firestore, snapshot)\n );\n });\n }\n\n isEqual(other: QuerySnapshot<T>): boolean {\n return snapshotEqual(this._delegate, other._delegate);\n }\n}\n\nexport class CollectionReference<T = PublicDocumentData>\n extends Query<T>\n implements PublicCollectionReference<T>\n{\n constructor(\n readonly firestore: Firestore,\n readonly _delegate: ExpCollectionReference<T>\n ) {\n super(firestore, _delegate);\n }\n\n get id(): string {\n return this._delegate.id;\n }\n\n get path(): string {\n return this._delegate.path;\n }\n\n get parent(): DocumentReference<PublicDocumentData> | null {\n const docRef = this._delegate.parent;\n return docRef ? new DocumentReference(this.firestore, docRef) : null;\n }\n\n doc(documentPath?: string): DocumentReference<T> {\n try {\n if (documentPath === undefined) {\n // Call `doc` without `documentPath` if `documentPath` is `undefined`\n // as `doc` validates the number of arguments to prevent users from\n // accidentally passing `undefined`.\n return new DocumentReference(this.firestore, doc(this._delegate));\n } else {\n return new DocumentReference(\n this.firestore,\n doc(this._delegate, documentPath)\n );\n }\n } catch (e) {\n throw replaceFunctionName(\n e as Error,\n 'doc()',\n 'CollectionReference.doc()'\n );\n }\n }\n\n add(data: T): Promise<DocumentReference<T>> {\n return addDoc(this._delegate, data as WithFieldValue<T>).then(\n docRef => new DocumentReference(this.firestore, docRef)\n );\n }\n\n isEqual(other: CollectionReference<T>): boolean {\n return refEqual(this._delegate, other._delegate);\n }\n\n withConverter(converter: null): CollectionReference<PublicDocumentData>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U>\n ): CollectionReference<U>;\n withConverter<U>(\n converter: PublicFirestoreDataConverter<U> | null\n ): CollectionReference<U> {\n return new CollectionReference<U>(\n this.firestore,\n converter\n ? this._delegate.withConverter(\n FirestoreDataConverter.getInstance(this.firestore, converter)\n )\n : (this._delegate.withConverter(null) as ExpCollectionReference<U>)\n );\n }\n}\n\nfunction castReference<T>(\n documentRef: PublicDocumentReference<T>\n): ExpDocumentReference<T> {\n return _cast<ExpDocumentReference<T>>(documentRef, ExpDocumentReference);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n FieldPath as ExpFieldPath,\n _FieldPath as InternalFieldPath\n} from '@firebase/firestore';\nimport { FieldPath as PublicFieldPath } from '@firebase/firestore-types';\nimport { Compat, getModularInstance } from '@firebase/util';\n\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n\n/**\n * A `FieldPath` refers to a field in a document. The path may consist of a\n * single field name (referring to a top-level field in the document), or a list\n * of field names (referring to a nested field in the document).\n */\nexport class FieldPath implements PublicFieldPath, Compat<ExpFieldPath> {\n readonly _delegate: ExpFieldPath;\n /**\n * Creates a FieldPath from the provided field names. If more than one field\n * name is provided, the path will point to a nested field in a document.\n *\n * @param fieldNames - A list of field names.\n */\n constructor(...fieldNames: string[]) {\n this._delegate = new ExpFieldPath(...fieldNames);\n }\n\n static documentId(): FieldPath {\n /**\n * Internal Note: The backend doesn't technically support querying by\n * document ID. Instead it queries by the entire document name (full path\n * included), but in the cases we currently support documentId(), the net\n * effect is the same.\n */\n return new FieldPath(InternalFieldPath.keyField().canonicalString());\n }\n\n isEqual(other: PublicFieldPath): boolean {\n other = getModularInstance(other);\n\n if (!(other instanceof ExpFieldPath)) {\n return false;\n }\n return this._delegate._internalPath.isEqual(other._internalPath);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n arrayRemove,\n arrayUnion,\n deleteField,\n FieldValue as FieldValue1,\n increment,\n serverTimestamp\n} from '@firebase/firestore';\nimport { FieldValue as PublicFieldValue } from '@firebase/firestore-types';\nimport { Compat } from '@firebase/util';\n\nexport class FieldValue implements PublicFieldValue, Compat<FieldValue1> {\n static serverTimestamp(): FieldValue {\n const delegate = serverTimestamp();\n delegate._methodName = 'FieldValue.serverTimestamp';\n return new FieldValue(delegate);\n }\n\n static delete(): FieldValue {\n const delegate = deleteField();\n delegate._methodName = 'FieldValue.delete';\n return new FieldValue(delegate);\n }\n\n static arrayUnion(...elements: unknown[]): FieldValue {\n const delegate = arrayUnion(...elements);\n delegate._methodName = 'FieldValue.arrayUnion';\n return new FieldValue(delegate);\n }\n\n static arrayRemove(...elements: unknown[]): FieldValue {\n const delegate = arrayRemove(...elements);\n delegate._methodName = 'FieldValue.arrayRemove';\n return new FieldValue(delegate);\n }\n\n static increment(n: number): FieldValue {\n const delegate = increment(n);\n delegate._methodName = 'FieldValue.increment';\n return new FieldValue(delegate);\n }\n\n constructor(readonly _delegate: FieldValue1) {}\n\n isEqual(other: FieldValue): boolean {\n return this._delegate.isEqual(other._delegate);\n }\n}\n"],"names":["LogLevel","stringToByteArray","str","out","p","i","length","c","charCodeAt","base64","byteToCharMap_","charToByteMap_","byteToCharMapWebSafe_","charToByteMapWebSafe_","ENCODED_VALS_BASE","ENCODED_VALS","this","ENCODED_VALS_WEBSAFE","HAS_NATIVE_SUPPORT","atob","encodeByteArray","input","webSafe","Array","isArray","Error","init_","byteToCharMap","output","byte1","haveByte2","byte2","haveByte3","byte3","outByte3","outByte4","push","join","encodeString","btoa","decodeString","bytes","pos","c2","c3","c1","String","fromCharCode","u","byteArrayToString","decodeStringToByteArray","charToByteMap","charAt","byte4","base64urlEncodeWithoutPadding","utf8Bytes","replace","getDefaultsFromGlobal","self","window","global","getGlobal","__FIREBASE_DEFAULTS__","getDefaultsFromCookie","document","match","cookie","e","decoded","console","error","base64Decode","JSON","parse","getDefaults","process","env","defaultsJsonString","getDefaultsFromEnvVariable","info","getUA","navigator","isSafari","forceEnvironment","_a","Object","prototype","toString","call","isNode","userAgent","includes","FirebaseError","constructor","code","message","customData","super","name","setPrototypeOf","captureStackTrace","ErrorFactory","create","service","serviceName","errors","data","fullCode","template","PATTERN","_","key","value","fullMessage","getModularInstance","_delegate","Component","instanceFactory","type","multipleInstances","serviceProps","instantiationMode","onInstanceCreated","setInstantiationMode","mode","setMultipleInstances","setServiceProps","props","setInstanceCreatedCallback","callback","levelStringToEnum","debug","DEBUG","verbose","VERBOSE","INFO","warn","WARN","ERROR","silent","SILENT","defaultLogLevel","ConsoleMethod","defaultLogHandler","instance","logType","args","logLevel","now","Date","toISOString","method","k","goog","goog.global","aa","goog.isArrayLike","ba","val","s","b","goog.isObject","goog.UID_PROPERTY_","Math","random","goog.uidCounter_","fa","fn","selfObj","var_args","apply","bind","arguments","goog.bindJs_","ha","boundArgs","slice","newArgs","unshift","goog.bind","goog.bind.apply","Function","indexOf","goog.bindNative_","goog.partial","ia","goog.inherits","t","childCtor","parentCtor","tempCtor","superClass_","base","childCtor.base","me","methodName","goog.Disposable","v","disposed_","onDisposeCallbacks_","dispose","goog.Disposable.prototype.dispose","goog.getUid","obj","disposeInternal","goog.Disposable.MONITORING_MODE","hasOwnProperty","goog.Disposable.prototype.disposeInternal","shift","arr","opt_fromIndex","a","fromIndex","toArray","object","rv","extend","arr1","arr2","len1","len2","j","goog.events.Event","w","opt_target","currentTarget","target","defaultPrevented","preventDefault","goog.events.Event.prototype.preventDefault","PASSIVE_EVENTS","goog.global.addEventListener","addEventListener","defineProperty","passive","options","get","goog.nullFunction","goog.global.removeEventListener","removeEventListener","goog.string.internal.isEmptyOrWhitespace","pa","test","goog.string.internal.trim","trim","exec","ra","left","right","getNativeUserAgentString","sa","goog.global.navigator","matchUserAgent","x","goog.reflect.sinkValue","ta","goog.userAgent.VERSION","goog.userAgent.OPERA","goog.userAgent.IE","goog.userAgent.EDGE","goog.userAgent.EDGE_OR_IE","goog.userAgent.GECKO","toLowerCase","subString","goog.userAgent.WEBKIT","Ba","doc","documentMode","undefined","version","docMode","goog.userAgent.getDocumentMode_","parseFloat","Ea","goog.userAgent.isVersionOrHigherCache_","Ia","valueFn","order","v1Subs","split","v2Subs","subCount","max","subIdx","v1Sub","v2Sub","v1Comp","v2Comp","goog.string.internal.compareElements_","parseInt","cacheObj","goog.userAgent.DOCUMENT_MODE","goog.events.BrowserEvent","z","opt_e","opt_currentTarget","goog.events.Event.call","goog.events.BrowserEvent.base","relatedTarget","button","screenY","screenX","clientY","clientX","metaKey","shiftKey","altKey","ctrlKey","state","pointerId","pointerType","event_","init","relevantTouch","changedTouches","srcElement","nodeName","MOUSEOVER","fromElement","MOUSEOUT","toElement","pageX","pageY","goog.events.BrowserEvent.IE_POINTER_TYPE_MAP","goog.events.BrowserEvent.superClass_.preventDefault.call","arg","2","TOUCH","3","PEN","4","MOUSE","goog.events.BrowserEvent.prototype.preventDefault","be","returnValue","goog.events.Listenable.IMPLEMENTED_BY_PROP","goog.events.ListenableKey.counter_","goog.events.Listener","Oa","listener","src","capture","opt_handler","proxy","handler","removed","callOnce","goog.events.Listener.prototype.markAsRemoved","forEach","f","opt_obj","clone","Ra","res","PROTOTYPE_FIELDS","Ta","source","goog.events.ListenerMap","Ua","listeners","typeCount_","Wa","goog.events.ListenerMap.prototype.removeByKey","d","splice","markAsRemoved","goog.events.ListenerMap.findListenerIndex_","Va","listenerArray","opt_useCapture","opt_listenerScope","listenerObj","add","goog.events.ListenerMap.prototype.add","typeStr","index","goog.events.LISTENER_MAP_PROP_","goog.events.onStringMap_","goog.events.listen","opt_options","once","goog.events.listenOnce","ab","goog.events.wrapListener","listenOnce","goog.events.listen_","listen","cb","listenerMap","goog.events.getListenerMap_","n","goog.events.getProxy","proxyCallbackFunction","goog.events.handleBrowserEvent_","eventObject","goog.events.BrowserFeature.PASSIVE_EVENTS","attachEvent","goog.events.getOnString_","addListener","removeListener","goog.events.unlistenByKey","ib","removeByKey","eventTargetListeners_","detachEvent","fb","Ya","goog.events.onString_","gb","opt_evt","listenerFn","listenerHandler","db","goog.events.LISTENER_WRAPPER_PROP_","bb","handleEvent","goog.events.EventTarget","B","goog.Disposable.call","actualEventTarget_","parentEventTarget_","C","goog.events.EventTarget.prototype.dispatchEvent","ancestorsTree","ancestor","getParentEventTarget","oldEvent","opt_ancestorsTree","fireListeners","kb","goog.events.EventTarget.prototype.fireListeners","concat","unlistenByKey","goog.events.EventTarget.prototype.removeEventListener","opt_capture","opt_handlerScope","goog.events.unlisten","hb","goog.events.EventTarget.prototype.disposeInternal","goog.events.EventTarget.superClass_.disposeInternal.call","removeAllListeners","goog.events.EventTarget.prototype.listen","goog.events.EventTarget.prototype.listenOnce","goog.json.serialize","stringify","ub","module$contents$goog$async$WorkQueue_WorkQueue.freelist_","reset","create_","reset_","occupants_","head_","item","next","WorkItem","qb","scope","set","goog.async.run","sb","opt_context","promise","goog.async.run.schedule_","goog.global.Promise.resolve","Promise","resolve","then","goog.async.run.processWorkQueue","wb","goog.async.run.workQueueScheduled_","goog.async.run.workQueue_","workTail_","workHead_","module$contents$goog$async$WorkQueue_WorkQueue.freelist_.get","remove","goog.async.run.workQueue_.remove","throwException","exception","goog.global.setTimeout","setTimeout","put","module$contents$goog$async$WorkQueue_WorkQueue.freelist_.put","goog.Timer","opt_interval","opt_timerObject","goog.events.EventTarget.call","interval_","timerObject_","boundTick_","tick_","last_","zb","goog.Timer.prototype.stop","enabled","timer_","clearTimeout","goog.Timer.callOnce","Ab","opt_delay","Number","yb","JSC$2088_enabled","goog.Timer.prototype","JSC$2088_timer_","goog.Timer.prototype.tick_","elapsed","goog.Timer.intervalScale","dispatchEvent","dispatchTick","goog.Timer.TICK","stop","start","goog.Timer.prototype.start","goog.Timer.prototype.disposeInternal","goog.Timer.superClass_.disposeInternal.call","Throttle","interval","listener_","args_","shouldFire_","fire","doAction_","Bb","onTimer_","goog.global.clearTimeout","goog.events.EventHandler","D","opt_scope","handler_","keys_","goog.events.EventHandler.typeArray_","Eb","goog.events.EventHandler.prototype.listen_","opt_fn","goog.events.EventHandler.prototype.removeAll","Fb","goog.labs.net.webChannel.WebChannelDebug","Gb","redactEnabled_","WebChannelDebug.prototype.xmlHttpChannelResponseText","E","id","responseText","opt_desc","WebChannelDebug.prototype.redactResponse_","responseArray","array","dataPart","redactResponse_","goog.events.EventHandler.prototype.disposeInternal","goog.events.EventHandler.superClass_.disposeInternal.call","removeAll","goog.events.EventHandler.prototype.handleEvent","disableRedact","WebChannelDebug.prototype.disableRedact","WebChannelDebug.prototype.info","goog.labs.net.webChannel.requestStats.Event","goog.labs.net.webChannel.requestStats.eventTarget_","Mb","Lb","Nb","goog.labs.net.webChannel.requestStats.Event.SERVER_REACHABILITY_EVENT","SERVER_REACHABILITY_EVENT","requestStats.notifyServerReachabilityEvent","H","goog.labs.net.webChannel.requestStats.getStatEventTarget_","goog.labs.net.webChannel.requestStats.ServerReachabilityEvent","Ob","eventTarget","stat","goog.labs.net.webChannel.requestStats.Event.STAT_EVENT","STAT_EVENT","requestStats.notifyStatEvent","goog.labs.net.webChannel.requestStats.StatEvent","Pb","size","goog.labs.net.webChannel.requestStats.Event.TIMING_EVENT","TIMING_EVENT","J","ms","goog.labs.net.webChannel.requestStats.TimingEvent","goog.net.ErrorCode","NO_ERROR","ACCESS_DENIED","FILE_NOT_FOUND","FF_SILENT_ERROR","CUSTOM_ERROR","EXCEPTION","HTTP_ERROR","ABORT","TIMEOUT","OFFLINE","goog.net.EventType","COMPLETE","SUCCESS","READY","READY_STATE_CHANGE","INCREMENTAL_DATA","PROGRESS","DOWNLOAD_PROGRESS","UPLOAD_PROGRESS","goog.net.XmlHttpFactory","Sb","goog.net.XmlHttpFactory.prototype.getOptions","Tb","cachedOptions_","internalGetOptions","goog.net.WebChannel","Ub","goog.net.WebChannel.EventType","OPEN","CLOSE","MESSAGE","goog.net.WebChannel.MessageEvent","Vb","goog.net.WebChannel.MessageEvent.base","goog.net.WebChannel.ErrorEvent","Wb","goog.net.WebChannel.ErrorEvent.base","goog.net.DefaultXmlHttpFactory","Yb","goog.labs.net.webChannel.ChannelRequest","L","channel","channelDebug","opt_requestId","opt_retryId","channel_","channelDebug_","rid_","retryId_","eventHandler_","timeout_","goog.labs.net.webChannel.ChannelRequest.TIMEOUT_MS_","pollingTimer_","EDGE_POLLING_INTERVAL_","extraHeaders_","successful_","postData_","requestUri_","baseUri_","type_","requestStartTime_","watchDogTimeoutTime_","watchDogTimerId_","pendingMessages_","xmlHttp_","xmlHttpChunkStart_","lastError_","verb_","lastStatusCode_","cancelled_","readyStateChangeThrottleMs_","readyStateChangeThrottle_","firstByteReceived_","initialResponseDecoded_","decodeInitialResponse_","decodeChunks_","fetchResponseState_","goog.labs.net.webChannel.FetchResponseState","$b","textDecoder","responseBuffer","responseArrivedForFetch","createInstance","goog.net.DefaultXmlHttpFactory.prototype.createInstance","XMLHttpRequest","goog.net.DefaultXmlHttpFactory.prototype.internalGetOptions","goog.net.XmlHttp.factory_","factory","goog.labs.net.webChannel.ChannelRequest.INVALID_CHUNK_","goog.labs.net.webChannel.ChannelRequest.INCOMPLETE_CHUNK_","cc","ChannelRequest.prototype.xmlHttpPost","uri","postData","XML_HTTP","makeUnique","decodeChunks","sendXmlHttp_","ChannelRequest.prototype.sendXmlHttp_","ec","hostPrefix","N","ensureWatchDogTimer_","WebChannelDebug.prototype.xmlHttpChannelRequest","verb","attempt","values","fc","queryData_","useSecondaryDomains","supportsCrossDomainXhrs_","createXhrIo","xmlHttpHandler_","readyStateChangeHandler_","headers","send","goog.labs.net.webChannel.requestStats.notifyServerReachabilityEvent","params","keyParts","keyValue","h","ChannelRequest.prototype.useFetchStreamsForResponse_","jc","CLOSE_REQUEST","usesFetchStreams_","ChannelRequest.prototype.decodeNextChunks_","lc","readyState","decodeNextChunksSuccessful","chunkText","sizeEndIndex","sizeStartIndex","ChannelRequest.prototype.getNextChunk_","getNextChunk_","substring","isNaN","chunkStartIndex","substr","BAD_DATA","goog.labs.net.webChannel.requestStats.notifyStatEvent","REQUEST_INCOMPLETE_DATA","REQUEST_BAD_DATA","safeOnRequestData_","maybeResetBuffer_","NO_DATA","REQUEST_NO_DATA","backChannelRequest_","request","detectBufferingProxy_","bpDetectionDone_","clearBpDetectionTimer_","NOPROXY","xmlHttpChannelResponseText","cleanup_","dispatchFailure_","ChannelRequest.prototype.ensureWatchDogTimer_","pc","startWatchDogTimer_","ChannelRequest.prototype.startWatchDogTimer_","time","goog.labs.net.webChannel.requestStats.setTimeout","onWatchDogTimeout_","ChannelRequest.prototype.cancelWatchDogTimer_","ic","Q","ChannelRequest.prototype.dispatchFailure_","CLOSED","state_","onRequestComplete","ChannelRequest.prototype.cleanup_","P","cancelWatchDogTimer_","xmlhttp","abort","ChannelRequest.prototype.safeOnRequestData_","hasRequest","forwardChannelRequestPool_","OPENED","response","wireCodec_","parser_","ex","responseValues","handlePostResponse_","backChannelTimerId_","goog.labs.net.webChannel.WebChannelBase.RTT_ESTIMATE","clearDeadBackchannelTimer_","cancelBackChannelRequest_","tc","BACKCHANNEL_MISSING","lastPostResponseArrayId_","lastArrayId_","goog.labs.net.webChannel.WebChannelBase.OUTSTANDING_DATA_BACKCHANNEL_RETRY_CUTOFF","enableStreaming_","backChannelRetryCount_","deadBackChannelTimerId_","onBackChannelDead_","getRequestCount","onForwardChannelFlushed_","forwardChannelFlushedCallback_","signalError_","BAD_RESPONSE","respArray","nextArray","onInput_","OPENING","sid_","hostPrefix_","negotiatedVersion","channelVersion_","negotiatedServerVersion","serverVersion_","httpSessionIdHeader","serverKeepaliveMs","Ca","timeout","backChannelRequestTimeoutMs_","applyControlHeaders_","xhr","clientProtocol","xhr_","getResponseHeader","goog.net.WebChannel.X_CLIENT_WIRE_PROTOCOL","requestPool_","maxSize_","maxPoolSizeConfigured_","Set","request_","addRequest","getHttpSessionIdParam","httpSessionIdParam_","goog.net.WebChannel.X_HTTP_SESSION_ID","setHttpSessionId","httpSessionId_","setParameterValue","forwardChannelUri_","channelOpened","handshakeRttMs_","startBackchannelAfterHandshake_","backChannelUri_","createDataUri","getBackChannelUri","path_","removeRequest","opt_timeout","ensureBackChannel_","outgoingMaps_","ensureForwardChannel_","STOP","disconnect","channelHandleArray","goog.structs.forEach","Dc","col","keys","goog.structs.getKeys","getKeys","getValues","Map","from","l","goog.structs.getValues","ChannelRequest.prototype.setTimeout","goog.labs.net.webChannel.ChannelRequest.prototype","ChannelRequest.prototype.readyStateChangeHandler_","evt","throttle","INTERACTIVE","getReadyState","ChannelRequest.prototype.xmlHttpHandler_","onXmlHttpReadyStateChanged_","errorCode","getLastErrorCode","getStatus","getResponseText","getResponse","status","useFetchStreamsForResponse_","responseChunks","responseLength","requestCompleted","TextDecoder","goog.global.TextDecoder","decode","stream","WebChannelDebug.prototype.xmlHttpChannelResponseMetaData","statusCode","goog.net.WebChannel.X_HTTP_INITIAL_RESPONSE","m","initialResponse","UNKNOWN_SESSION_ID","I","REQUEST_UNKNOWN_SESSION_ID","decodeNextChunks_","listen_","pollResponse_","STATUS","REQUEST_BAD_STATUS","ChannelRequest.prototype.pollResponse_","cancel","ChannelRequest.prototype.cancel","ChannelRequest.prototype.onWatchDogTimeout_","WebChannelDebug.prototype.timeoutResponse","handleTimeout_","REQUEST_TIMEOUT","goog.uri.utils.splitRe_","RegExp","goog.Uri","T","opt_uri","opt_ignoreCase","domain_","userInfo_","scheme_","port_","fragment_","ignoreCase_","Gc","setScheme","setUserInfo","setPort","setPath","goog.Uri.QueryData","encodedQuery_","keyMap_","count_","Jc","setQueryData","SCHEME","goog.Uri.decodeOrEmpty_","USER_INFO","setDomain","DOMAIN","PORT","PATH","QUERY_DATA","setFragment","FRAGMENT","goog.Uri.prototype.clone","M","goog.Uri.prototype.setScheme","newScheme","opt_decode","goog.Uri.prototype.setPort","Hc","newPort","goog.Uri.prototype.setQueryData","queryData","goog.Uri.QueryData.prototype.setIgnoreCase","ignoreCase","ensureKeyMapInitialized_","invalidateCache_","lowerCase","setValues","goog.Uri.encodeSpecialChars_","goog.Uri.reDisallowedInQuery_","goog.Uri.prototype.setParameterValue","S","goog.Uri.prototype.makeUnique","RANDOM","floor","abs","opt_preserveReserved","decodeURI","decodeURIComponent","Lc","unescapedPart","extra","opt_removeDoubleEncoding","encoded","encodeURI","goog.Uri.encodeChar_","Sc","ch","goog.Uri.prototype.toString","scheme","getScheme","goog.Uri.reDisallowedInSchemeOrUserInfo_","domain","getDomain","userInfo","getUserInfo","encodeURIComponent","port","getPort","path","getPath","hasDomain","goog.Uri.reDisallowedInAbsolutePath_","goog.Uri.reDisallowedInRelativePath_","query","getEncodedQuery","fragment","getFragment","goog.Uri.reDisallowedInFragment_","Ic","opt_query","goog.Uri.QueryData.prototype.ensureKeyMapInitialized_","U","goog.uri.utils.parseQueryData","encodedQuery","pairs","indexOfEquals","Tc","goog.Uri.QueryData.prototype.remove","getKeyName_","has","delete","goog.Uri.QueryData.prototype.containsKey","Uc","goog.Uri.QueryData.prototype.setValues","goog.Uri.QueryData.prototype.getKeyName_","V","keyName","goog.Uri.QueryData.prototype.add","goog.Uri.QueryData.prototype","goog.Uri.QueryData.prototype.forEach","goog.Uri.QueryData.prototype.getKeys","vals","goog.Uri.QueryData.prototype.getValues","opt_key","containsKey","goog.Uri.QueryData.prototype.set","goog.Uri.QueryData.prototype.get","opt_default","goog.Uri.QueryData.prototype.toString","encodedKey","param","goog.labs.net.webChannel.Wire.QueuedMap","mapId","map","ForwardChannelRequestPool","Wc","opt_maxPoolSize","goog.global.PerformanceNavigationTiming","PerformanceNavigationTiming","entrys","goog.global.performance.getEntriesByType","performance","getEntriesByType","nextHopProtocol","goog.global.chrome","chrome","goog.global.chrome.loadTimes","loadTimes","wasFetchedViaSpdy","retValue","Yc","ForwardChannelRequestPool.prototype.isFull","ForwardChannelRequestPool.prototype.getRequestCount","uc","ForwardChannelRequestPool.prototype.hasRequest","req","ForwardChannelRequestPool.prototype.addRequest","vc","ForwardChannelRequestPool.prototype.removeRequest","ForwardChannelRequestPool.prototype.getPendingMessages","Zc","result","goog.json.NativeJsonProcessor","goog.labs.net.webChannel.WireV8","netUtils.imageCallback_","dd","img","debugText","onload","onerror","onabort","ontimeout","goog.net.FetchXmlHttpFactory","opts","worker_","worker","streamBinaryChunks_","streamBinaryChunks","goog.net.FetchXmlHttp","goog.net.FetchXmlHttp.base","credentialsMode_","goog.net.FetchXmlHttp.RequestState.UNSENT","responseType","statusText","onreadystatechange","requestHeaders_","Headers","responseHeaders_","method_","url_","inProgress_","textDecoder_","currentReader_","fetchResponse_","ForwardChannelRequestPool.prototype.cancel","getPendingMessages","clear","goog.json.NativeJsonProcessor.prototype.stringify","opt_replacer","goog.json.NativeJsonProcessor.prototype.parse","opt_reviver","goog.net.FetchXmlHttpFactory.prototype.createInstance","UNSENT","goog.net.FetchXmlHttp.prototype.readInputFromFetch_","read","handleDataFromStream_","catch","handleSendFailure_","goog.net.FetchXmlHttp.prototype.requestDone_","DONE","hd","dispatchCallback_","goog.net.FetchXmlHttp.prototype.dispatchCallback_","fd","open","goog.net.FetchXmlHttp.prototype.open","url","goog.net.FetchXmlHttp.prototype","goog.net.FetchXmlHttp.prototype.send","opt_data","requestInit","credentials","cache","body","fetch","Request","handleResponse_","goog.net.FetchXmlHttp.prototype.abort","requestDone_","goog.net.FetchXmlHttp.prototype.handleResponse_","HEADER_RECEIVED","LOADING","arrayBuffer","handleResponseArrayBuffer_","ReadableStream","getReader","readInputFromFetch_","text","handleResponseText_","goog.net.FetchXmlHttp.prototype.handleDataFromStream_","dataPacket","Uint8Array","newText","done","goog.net.FetchXmlHttp.prototype.handleResponseText_","goog.net.FetchXmlHttp.prototype.handleResponseArrayBuffer_","responseArrayBuffer","goog.net.FetchXmlHttp.prototype.handleSendFailure_","setRequestHeader","goog.net.FetchXmlHttp.prototype.setRequestHeader","header","append","goog.net.FetchXmlHttp.prototype.getResponseHeader","getAllResponseHeaders","goog.net.FetchXmlHttp.prototype.getAllResponseHeaders","lines","iter","entries","entry","pair","getCredentialsMode","setCredentialsMode","goog.json.hybrid.parse","goog.net.XhrIo","W","opt_xmlHttpFactory","goog.net.XhrIo.base","xmlHttpFactory_","active_","xhrOptions_","lastUri_","lastErrorCode_","inAbort_","inOpen_","inSend_","errorDispatched_","timeoutInterval_","timeoutId_","responseType_","goog.net.XhrIo.ResponseType.DEFAULT","useXhr2Timeout_","withCredentials_","DEFAULT","goog.net.XhrIo.HTTP_SCHEME_PATTERN","goog.net.XhrIo.METHODS_WITH_FORM_DATA","od","goog.net.XhrIo.prototype.error_","err","rd","dispatchErrors_","sd","cleanUpXhr_","goog.net.XhrIo.prototype.dispatchErrors_","td","goog.net.XhrIo.prototype.onReadyStateChangeHelper_","LOCAL_REQUEST_ERROR","onReadyStateChange_","isComplete","protocol","isSuccess","OK","CREATED","ACCEPTED","NO_CONTENT","PARTIAL_CONTENT","NOT_MODIFIED","QUIRK_IE_NO_CONTENT","goog.global.self","goog.global.self.location","location","goog.global.self.location.protocol","goog.net.XhrIo.HTTP_SCHEME_PATTERN.test","LOADED","getStatusText","goog.net.XhrIo.prototype.cleanUpXhr_","opt_fromDispose","cleanUpTimeoutTimer_","clearedOnReadyStateChange","USE_NULL_FUNCTION","goog.net.XhrIo.prototype.cleanUpTimeoutTimer_","pd","goog.net.XhrIo.prototype.getReadyState","O","UNINITIALIZED","hc","goog.net.XhrIo.prototype.getResponse","TEXT","ARRAY_BUFFER","mozResponseArrayBuffer","exports.generateHttpHeadersOverwriteParam","Qa","exports.setHttpHeadersWithOverwriteParam","urlParam","extraHeaders","httpHeaders","module$exports$goog$net$rpc$HttpCors.generateHttpHeadersOverwriteParam","getInternalChannelParam","paramName","defaultValue","internalChannelParams","goog.labs.net.webChannel.WebChannelBase","xd","extraParams_","httpHeadersOverwriteParam_","initHeaders_","nextMapId_","nextRid_","failFast_","$jscomp.scope.getInternalChannelParam","forwardChannelTimerId_","allowStreamingMode_","backChannelAttemptId_","forwardChannelRetryCount_","baseRetryDelayMs_","retryDelaySeedMs_","forwardChannelMaxRetries_","forwardChannelRequestTimeoutMs_","xmlHttpFactory","useFetchStreams","supportsCrossDomainXhr","concurrentRequestLimit","fastHandshake_","fastHandshake","encodeInitMessageHeaders_","encodeInitMessageHeaders","blockingHandshake_","blockingHandshake","forceLongPolling","detectBufferingProxy","nonAckedMapsAtChannelClose_","bpDetectionTimerId_","Ac","WebChannelBase.prototype.disconnect","rid","cancelRequests_","zd","addAdditionalParams_","requestSent","goog.global.navigator.sendBeacon","sendBeacon","goog.global.Image","Image","onClose_","WebChannelBase.prototype.cancelBackChannelRequest_","sc","WebChannelBase.prototype.cancelRequests_","yd","clearForwardChannelTimer_","WebChannelBase.prototype.ensureForwardChannel_","zc","isFull","onStartForwardChannelTimer_","Ed","WebChannelBase.prototype.makeForwardChannelRequest_","opt_retryRequest","module$exports$goog$net$rpc$HttpCors.setHttpHeadersWithOverwriteParam","requeuePendingMaps_","requestText","dequeueOutgoingMaps_","goog.labs.net.webChannel.WebChannelBase.MAX_MAPS_PER_REQUEST_","round","WebChannelBase.prototype.addAdditionalParams_","WebChannelBase.prototype.dequeueOutgoingMaps_","Dd","maxNum","count","min","badMapHandler","badMapError","offset","messageQueue","WireV8.prototype.encodeMessage","buffer","opt_prefix","prefix","encodedValue","encodeMessage","pendingMessages","WebChannelBase.prototype.ensureBackChannel_","yc","onStartBackChannelTimer_","WebChannelBase.prototype.maybeRetryBackChannel_","goog.labs.net.webChannel.WebChannelBase.BACK_CHANNEL_MAX_RETRIES","getRetryTime_","oc","WebChannelBase.prototype.clearBpDetectionTimer_","WebChannelBase.prototype.startBackChannel_","Fd","WebChannelBase.prototype.clearDeadBackchannelTimer_","rc","WebChannelBase.prototype.onRequestComplete","mc","WebChannelBase.prototype.maybeRetryForwardChannel_","BACK_CHANNEL","FORWARD_CHANNEL","lastError","maybeRetryForwardChannel_","INIT","getForwardChannelMaxRetries","maybeRetryBackChannel_","REQUEST_FAILED","WebChannelBase.prototype.getRetryTime_","Cd","retryCount","retryTime","goog.labs.net.webChannel.WebChannelBase.INACTIVE_CHANNEL_RETRY_FACTOR","WebChannelBase.prototype.signalError_","R","imageUri","testNetworkCallback_","goog.global.location","goog.global.location.protocol","netUtils.testLoadImage","goog.labs.net.webChannel.netUtils.imageCallback_","goog.labs.net.webChannel.netUtils.NETWORK_TIMEOUT","cd","ERROR_OTHER","onError_","channelError","Ad","WebChannelBase.prototype.onClose_","channelClosed","WebChannelBase.prototype.createDataUri","wc","locationPage","hostName","hostname","opt_scheme","opt_domain","opt_port","getHttpSessionId","WebChannelBase.prototype.createXhrIo","isStreaming","setWithCredentials","WebChannelBase.Handler","Gd","goog.labs.net.webChannel.WebChannelBaseTransport","Hd","X","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.base","messageUrlParams_","messageUrlParams","messageHeaders","clientProtocolHeaderRequired","goog.net.WebChannel.X_CLIENT_PROTOCOL","goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL","initHeaders","initMessageHeaders","messageContentType","goog.net.WebChannel.X_WEBCHANNEL_CONTENT_TYPE","clientProfile","goog.net.WebChannel.X_WEBCHANNEL_CLIENT_PROFILE","httpHeadersOverwriteParam","supportsCrossDomainXhr_","sendRawJson_","sendRawJson","httpSessionIdParam","channelHandler_","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.Handler_","WebChannelBaseTransport.Channel.MessageEvent","Id","goog.net.WebChannel.MessageEvent.call","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.MessageEvent.base","metadata","__sm__","metadataKey","Jd","goog.net.WebChannel.ErrorEvent.call","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.ErrorEvent.base","NETWORK_ERROR","Y","goog.net.XhrIo.prototype.setWithCredentials","withCredentials","JSC$2188_send","goog.net.XhrIo.prototype.send","opt_method","opt_content","opt_headers","toUpperCase","createXhr","goog.net.XmlHttp.factory_.createInstance","getOptions","goog.net.XmlHttp.factory_.getOptions","error_","content","getPrototypeOf","contentTypeKey","find","contentIsFormData","FormData","goog.net.XhrIo.CONTENT_TYPE_HEADER","goog.net.XhrIo.FORM_CONTENT_TYPE","y","goog.userAgent.isVersionOrHigher","goog.net.XhrIo.shouldUseXhr2Timeout_","goog.net.XhrIo.prototype","JSC$2188_timeout_","goog.net.XhrIo.prototype.timeout_","goog.net.XhrIo.prototype.abort","opt_failureCode","goog.net.XhrIo.prototype.disposeInternal","goog.net.XhrIo.prototype.disposeInternal.base","goog.net.XhrIo.prototype.onReadyStateChange_","isDisposed","onReadyStateChangeHelper_","onReadyStateChangeEntryPoint_","goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_","goog.net.XhrIo.prototype.getStatus","goog.net.XhrIo.prototype.getResponseText","getResponseJson","goog.net.XhrIo.prototype.getResponseJson","opt_xssiPrefix","kd","goog.net.XhrIo.prototype.getLastErrorCode","JSC$2188_getLastError","goog.net.XhrIo.prototype.getLastError","goog.labs.net.webChannel.Wire.LATEST_CHANNEL_VERSION","goog.labs.net.webChannel.WebChannelBase.prototype","JSC$2195_state_","WebChannelBase.prototype.onStartForwardChannelTimer_","startForwardChannel_","total","goog.labs.net.webChannel.Wire.RAW_DATA_KEY","__data__","goog.labs.net.webChannel.WebChannelBase.MAX_CHARS_PER_GET_","goog.net.WebChannelTransport.CLIENT_VERSION","xmlHttpPost","makeForwardChannelRequest_","WebChannelBase.prototype.onStartBackChannelTimer_","bpDetectionTimeout","startBackChannel_","onBpDetectionTimer_","WebChannelBase.prototype.onBpDetectionTimer_","PROXY","WebChannelBase.prototype.onBackChannelDead_","BACKCHANNEL_DEAD","WebChannelBase.prototype.testNetworkCallback_","networkUp","ERROR_NETWORK","WebChannelBase.Handler.prototype.channelOpened","goog.labs.net.webChannel.WebChannelBase.Handler.prototype","WebChannelBase.Handler.prototype.channelHandleArray","WebChannelBase.Handler.prototype.channelError","WebChannelBase.Handler.prototype.channelClosed","WebChannelBase.Handler.prototype.badMapError","createWebChannel","WebChannelBaseTransport.prototype.createWebChannel","goog.labs.net.webChannel.WebChannelBaseTransport.Channel","WebChannelBaseTransport.Channel.prototype.open","supportCrossDomain","CONNECT_ATTEMPT","channelPath","opt_extraParams","connectChannel_","close","WebChannelBaseTransport.Channel.prototype.close","WebChannelBaseTransport.Channel.prototype.send","rawJson","messageToMapObject_","WebChannelBaseTransport.Channel.prototype.disposeInternal","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.superClass_.disposeInternal.call","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.prototype.disposeInternal.base","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.MessageEvent","goog.labs.net.webChannel.WebChannelBaseTransport.Channel.ErrorEvent","goog.labs.net.webChannel.WebChannelBase.Handler","WebChannelBaseTransport.Channel.Handler_.prototype.channelOpened","WebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray","WebChannelBaseTransport.Channel.Handler_.prototype.channelError","WebChannelBaseTransport.Channel.Handler_.prototype.channelClosed","Qb","Rb","EventType","K","getLastError","us","getStatEventTarget","ErrorCode","module","Event","FetchXmlHttpFactory","WebChannel","XhrIo","uid","isAuthenticated","toKey","isEqual","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","_logLevel","_logHandler","_userLogHandler","TypeError","setLogLevel","logHandler","userLogHandler","log","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","q","reject","user","getToken","invalidateToken","enqueueRetryable","shutdown","G","token","changeListener","currentUser","forceRefresh","auth","o","r","addAuthTokenListener","onInit","getImmediate","optional","accessToken","removeAuthTokenListener","getUid","g","getAuthHeaderValueForFirstParty","appCheck","A","addTokenListener","removeTokenListener","crypto","msCrypto","getRandomValues","Z","tt","every","et","nt","seconds","nanoseconds","fromMillis","fromDate","getTime","toDate","toMillis","_compareTo","toJSON","valueOf","padStart","st","timestamp","fromTimestamp","compareTo","toMicroseconds","toTimestamp","it","segments","len","comparator","child","limit","construct","popFirst","popLast","firstSegment","lastSegment","isEmpty","isPrefixOf","isImmediateParentOf","rt","canonicalString","fromString","filter","emptyPath","ot","ut","isValidIdentifier","isKeyField","keyField","fromServerFormat","ct","fromPath","fromName","empty","collectionGroup","hasCollectionId","getCollectionGroup","getCollectionPath","isDocumentKey","fromSegments","at","indexId","fields","indexState","ht","kind","lt","UNKNOWN_ID","dt","fieldPath","wt","sequenceNumber","yt","mt","gt","readTime","documentKey","largestBatchId","pt","It","Tt","onCommittedListeners","addOnCommittedListener","raiseOnCommittedEvent","async","Et","At","nextCallback","catchCallback","isDone","callbackAttached","wrapFailure","wrapSuccess","toPromise","wrapUserFunction","waitFor","or","mapArray","doWhile","Rt","action","transaction","aborted","oncomplete","vt","xt","commit","store","objectStore","St","bt","Dt","indexedDB","deleteDatabase","F","onsuccess","onblocked","onupgradeneeded","oldVersion","$","onversionchange","runTransaction","Pt","cursor","Vt","getAll","range","primaryKey","continue","reverse","openKeyCursor","openCursor","Ct","Nt","asyncQueue","task","started","enqueueAfterDelay","kt","localStore","persistence","indexManager","getNextCollectionGroupToUpdate","getMinOffsetFromCollectionGroup","localDocuments","getNextDocuments","changes","updateIndexEntries","updateCollectionGroup","batchId","Ot","previousValue","sequenceNumberHandler","writeSequenceNumber","Mt","databaseId","appId","persistenceKey","host","ssl","autoDetectLongPolling","Ft","projectId","database","isDefaultDatabase","$t","Bt","Lt","qt","Ut","Kt","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","Qt","binaryString","fromBase64String","fromUint8Array","Symbol","iterator","toBase64","toUint8Array","approximateByteSize","EMPTY_BYTE_STRING","jt","Wt","zt","nanos","Ht","Jt","mapValue","__type__","stringValue","Xt","__local_write_time__","timestampValue","Zt","te","nullValue","ee","we","ne","booleanValue","bytesValue","referenceValue","geoPointValue","latitude","longitude","integerValue","doubleValue","arrayValue","se","ie","re","sort","oe","ue","ce","ae","he","le","fe","de","_e","assign","ye","inclusive","pe","Ie","position","Te","field","dir","Ee","Ae","Re","op","createKeyFieldInFilter","ke","$e","Be","Le","qe","Oe","Me","matches","matchesComparison","isInequality","getFlattenedFilters","getFilters","getFirstInequalityField","filters","Pe","reduce","ve","Ve","Se","xe","Ne","Fe","some","Ue","Ge","root","je","EMPTY","insert","copy","BLACK","minKey","maxKey","inorderTraversal","reverseTraversal","getIterator","Qe","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","rotateRight","moveRedRight","rotateLeft","colorFlip","checkMaxDepth","check","pow","We","first","last","forEachInRange","forEachWhile","firstAfterOrEqual","ze","unionWith","He","Je","covers","Ye","getFieldsMap","setAll","applyChanges","Ze","documentType","createTime","documentState","newInvalidDocument","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","tn","orderBy","startAt","endAt","ft","en","nn","De","sn","Ce","rn","on","un","NaN","cn","an","explicitOrderBy","limitType","_t","hn","ln","dn","_n","wn","mn","gn","yn","pn","In","Tn","En","An","Rn","bn","Pn","vn","Vn","Sn","Dn","Nn","Bn","kn","On","elements","Mn","qn","Fn","$n","Ln","Un","transform","Gn","transformResults","Qn","updateTime","exists","none","isNone","jn","Wn","zn","is","Zn","ts","Hn","ns","fieldTransforms","precondition","es","Jn","ss","fieldMask","Xn","Kn","getFieldMask","__previous_value__","rs","os","as","hs","cs","ls","mapKeyFn","equalsFn","inner","innerSize","fs","_s","ws","overlayedDocument","ps","Is","Ts","Es","As","bs","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","Ps","createSynthesizedTargetChangeForCurrentChange","resumeToken","current","addedDocuments","modifiedDocuments","removedDocuments","vs","removedTargetIds","Vs","targetId","Ss","targetIds","cause","Ds","Ns","Cs","xs","Gt","forEachTarget","removeTarget","Yt","purpose","getRemoteKeysForTarget","ks","asc","desc","Os","<","<=",">",">=","==","!=","array-contains","in","not-in","array-contains-any","Ms","and","Fs","$s","Bs","qs","Us","Ks","wi","Gs","Qs","Hs","js","Ws","zs","Js","Ys","ti","update","updateMask","fieldPaths","_i","verify","updateTransforms","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","ei","si","documents","ii","structuredQuery","parent","collectionId","allDescendants","di","unaryFilter","li","fieldFilter","ai","compositeFilter","hi","where","direction","before","ri","ui","fi","mi","yi","gi","pi","Ii","Ti","Ei","Ai","Ri","bi","Pi","vi","Vi","Si","Di","Ci","xi","Ni","ki","Oi","Mi","Fi","$i","Bi","Li","qi","Ui","Ki","currentSequenceNumber","Gi","Qi","localWriteTime","baseMutations","mutations","applyToRemoteDocument","mutationResults","applyToLocalView","applyToLocalDocumentSet","mutatedFields","ji","batch","commitVersion","docVersions","Wi","mutation","getKey","zi","lastLimboFreeSnapshotVersion","withSequenceNumber","withResumeToken","withLastLimboFreeSnapshotVersion","Hi","Yi","prefixPath","documentId","Xi","noDocument","Zi","unknownDocument","tr","er","localWriteTimeMs","nr","lastListenSequenceNumber","sr","canonicalId","ir","rr","overlayMutation","ur","cr","getBundleMetadata","ar","bundleId","saveBundleMetadata","getNamedQuery","hr","bundledQuery","saveNamedQuery","lr","userId","getOverlay","fr","getOverlays","saveOverlays","removeOverlaysForBatchId","IDBKeyRange","bound","getOverlaysForCollection","POSITIVE_INFINITY","getOverlaysForCollectionGroup","collectionPath","dr","ge","wr","_r","ceil","mr","codePointAt","seed","DataView","ArrayBuffer","setFloat64","gr","yr","pr","Ir","directionalValue","Tr","Er","Ar","Ke","br","Sr","xr","Vr","Dr","Rr","Pr","vr","Cr","Nr","kr","addToCollectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getMinOffset","Or","Mr","Xe","Fr","Br","Lr","$r","createRange","orderedDocumentKey","only","upperBound","qr","Ur","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","Kr","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","withCacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","Gr","Qr","DISABLED","jr","referenceDelegate","checkEmpty","NEGATIVE_INFINITY","zr","addMutationBatch","Hr","lookupMutationBatch","getNextMutationBatchAfterBatchId","lowerBound","getHighestUnacknowledgedBatchId","getAllMutationBatches","getAllMutationBatchesAffectingDocumentKey","getAllMutationBatchesAffectingDocumentKeys","getAllMutationBatchesAffectingQuery","removeMutationBatch","markPotentiallyOrphaned","performConsistencyCheck","Wr","Jr","lastAcknowledgedBatchId","lastStreamToken","Yr","Xr","allocateTargetId","highestTargetId","getLastRemoteSnapshotVersion","lastRemoteSnapshotVersion","getHighestSequenceNumber","highestListenSequenceNumber","setTargetsMetadata","addTargetData","targetCount","Cn","updateTargetData","removeTargetData","removeMatchingKeysForTargetId","Zr","removeTargets","to","getTargetCount","getTargetData","addMatchingKeys","eo","addReference","removeMatchingKeys","removeReference","getMatchingKeysForTargetId","no","so","xn","maxValue","io","garbageCollector","collectGarbage","ro","calculateTargetCount","nthSequenceNumber","removeOrphanedDocuments","collect","getCacheSize","oo","getTargetCache","uo","getRemoteDocumentCache","newChangeBuffer","getEntry","removeEntry","updateLimboDocument","getSize","co","changesApplied","addEntry","assertNotApplied","getFromCache","getAllFromCache","ao","setIndexManager","_o","updateMetadata","getMetadata","byteSize","wo","go","getAllFromCollection","getAllFromCollectionGroup","mo","lo","trackRemovals","fo","Ji","ho","Yn","yo","po","remoteDocumentCache","mutationQueue","documentOverlayCache","getDocument","getDocuments","getLocalViewOfDocuments","populateOverlays","computeViews","getOverlayedDocuments","recalculateAndSaveOverlays","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingQuery","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","Io","To","overlays","Eo","Ao","ds","Ro","gs","ys","bo","docs","Po","vo","Rs","Vo","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","getBundleCache","So","Do","Ls","Co","createObjectStore","keyPath","autoIncrement","createIndex","unique","xo","deleteObjectStore","objectStoreNames","contains","No","ko","allowTabSynchronization","clientId","Xs","isPrimary","networkEnabled","Zs","inForeground","ni","localStorage","oi","ci","newVersion","enqueueAndForget","Mo","updateTimeMs","Oo","removeItem","ownerId","leaseTimestampMs","visibilityState","appVersion","enterRestrictedMode","getItem","setItem","Fo","$o","fromCache","docChanges","Bo","initialize","Lo","qo","Uo","removedBatchIds","addedBatchIds","Go","Qo","jo","zo","Ho","Jo","Zo","Yo","Xo","nu","su","iu","ru","ou","uu","activeTargetIds","cu","onlineState","au","hu","syncEngine","onlineStateHandler","storage","getAllActiveQueryTargets","isActiveQueryTarget","addPendingMutation","updateMutationState","addLocalQueryTarget","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","updateQueryState","handleUserChange","setOnlineState","notifyBundleLoaded","storageArea","newValue","all","lu","fu","du","_u","BatchGetDocuments","Commit","RunQuery","RunAggregationQuery","wu","onMessage","mu","databaseInfo","forwardChannelRequestTimeoutMs","gu","yu","pu","Iu","timerId","skipDelay","Tu","connection","authCredentialsProvider","appCheckCredentialsProvider","Ko","Eu","targetChange","targetChangeType","documentChange","documentDelete","documentRemove","Wo","addTarget","goog-listen-tags","labels","Au","streamToken","writeResults","commitTime","tu","eu","writes","Ru","authCredentials","appCheckCredentials","terminate","Pu","vu","datastore","remoteSyncer","Mu","Su","Vu","Du","Ou","ku","xu","Cu","Nu","Fu","qu","Uu","Ku","Qu","ju","Wu","Xu","verifyOperationInProgress","handleCredentialChange","Zu","rejectListen","applyRemoteEvent","rejectFailedWrite","applySuccessfulWrite","nc","targetTimeMs","removalCallback","deferred","createAndSchedule","timerHandle","handleDelayElapsed","keyedMap","sortedSet","emptySet","track","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","fromInitialDocuments","queries","ac","onListen","onError","bu","dc","onUnlisten","_c","includeMetadataChanges","byteLength","gc","collectionGroups","progress","bytesLoaded","documentsLoaded","namedQuery","documentMetadata","$u","complete","taskState","Bu","Lu","totalDocuments","totalBytes","Gu","zu","Hu","Ju","Yu","snapshot","Ec","view","Rc","remoteStore","eventManager","sharedClientState","maxConcurrentLimboResolutions","isPrimaryClient","Pc","Bc","Vc","ea","xc","Mc","Oc","Fc","$c","qc","synchronizeTabs","gcScheduler","indexBackfillerScheduler","initialUser","cacheSizeBytes","forceOwnership","oa","createDatastore","createRemoteStore","createEventManager","createSyncEngine","ua","ca","la","da","wa","ignoreUndefinedProperties","experimentalForceLongPolling","experimentalAutoDetectLongPolling","ma","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","app","_initialized","_terminated","_terminateTask","_setSettings","client","sessionIndex","iamToken","authTokenFactory","_getSettings","_freezeSettings","_delete","_terminate","settings","ga","mockUserToken","project","iat","sub","user_id","payload","iss","aud","exp","auth_time","firebase","sign_in_provider","identities","alg","ya","converter","_key","firestore","_path","withConverter","_query","Aa","Pa","releaseLock","closed","va","observer","muted","bc","Cc","findIndex","Nc","xa","readVersions","committed","lastWriteError","writtenDocs","lookup","ensureCommitNotCalled","found","missing","recordVersion","write","toMutation","preconditionForUpdate","Na","updateFunction","kc","maxAttempts","run","ka","authCredentialListener","appCheckCredentialListener","getConfiguration","setCredentialChangeListener","setAppCheckTokenChangeListener","verifyNotTerminated","isShuttingDown","enqueueAndForgetEvenWhileRestricted","onlineComponents","offlineComponents","Ma","Fa","$a","La","qa","Ga","za","Ja","Xa","TextEncoder","encode","_completeWith","_updateProgress","_failWith","na","th","Kc","Qc","enqueue","stack","Xc","eh","nh","_progressObserver","_taskCompletionResolver","_lastProgress","onProgress","firestoreFactory","ih","_queue","_firestoreClient","uh","lh","DOMException","dh","_h","wh","yh","ph","Ih","_byteString","Th","_internalPath","Ah","_methodName","Rh","isFinite","_lat","_long","bh","Ph","vh","Vh","Sh","Hh","Dh","Ch","xh","merge","mergeFields","Qh","Kh","jh","Jh","Nh","_toFieldTransform","kh","Oh","Mh","Uh","Fh","$h","Bh","zh","Lh","qh","Gh","Wh","search","Yh","_firestore","_userDataWriter","_document","_converter","ref","Xh","fromFirestore","convertValue","Zh","tl","el","nl","sl","ol","il","_apply","_field","_op","_value","_create","_parse","Al","El","Tl","_queryConstraints","_getOperator","_getQueryConstraints","al","_direction","Rl","ll","_limit","_limitType","_l","_docOrFields","_inclusive","Il","gl","Pl","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertDocumentKey","vl","toFirestore","Vl","Sl","Dl","_firestoreImpl","Cl","serverTimestamps","xl","_snapshot","_cachedChanges","_cachedChangesIncludeMetadataChanges","oldIndex","newIndex","Nl","kl","Ml","Fl","Ll","Ha","Ul","zl","Kl","jl","Hl","Wl","Xl","Zl","_commitHandler","_mutations","_committed","_dataReader","_verifyNotCommitted","tf","ef","_transaction","nf","instanceIdentifier","getProvider","validateSetOptions","FirestoreError","assertUint8ArrayAvailable","assertBase64Available","Blob","Bytes","other","isPartialObserver","methods","implementsAnyMethods","IndexedDbPersistenceProvider","enableIndexedDbPersistence","enableMultiTabIndexedDbPersistence","clearIndexedDbPersistence","Firestore","databaseIdOrApp","_persistenceProvider","_DatabaseId","_appCompat","settingsLiteral","currentSettings","_logWarn","useEmulator","connectFirestoreEmulator","enableNetwork","disableNetwork","enablePersistence","experimentalForceOwningTab","_validateIsNotUsedTogether","clearPersistence","_removeServiceInstance","waitForPendingWrites","onSnapshotsInSync","collection","pathString","CollectionReference","replaceFunctionName","DocumentReference","Query","Transaction","ensureFirestoreConfigured","WriteBatch","ExpWriteBatch","executeWrite","loadBundle","bundleData","expQuery","UserDataWriter","AbstractUserDataWriter","forKey","documentRef","castReference","DocumentSnapshot","ExpDocumentSnapshot","dataOrField","moreFieldsAndValues","FirestoreDataConverter","expSnapshot","ExpQueryDocumentSnapshot","QueryDocumentSnapshot","modelObject","getInstance","converterMapByFirestore","INSTANCES","untypedConverterByConverter","WeakMap","forPath","ExpDocumentReference","_DocumentKey","refEqual","setDoc","fieldOrUpdateData","updateDoc","onSnapshot","extractSnapshotOptions","wrapObserver","snap","getDocFromCache","original","updated","wrapper","userObserver","_b","snapshotEqual","opStr","directionStr","limitToLast","startAfter","endBefore","queryEqual","getDocsFromCache","QuerySnapshot","ExpQuerySnapshot","DocumentChange","docChange","thisArg","docRef","documentPath","addDoc","_cast","firestoreNamespace","GeoPoint","Timestamp","FieldPath","fieldNames","ExpFieldPath","InternalFieldPath","FieldValue","serverTimestamp","delegate","arrayUnion","arrayRemove","level","firestoreExp","registerComponent","container","registerVersion"],"mappings":"2bAsDYA,UCrCc,SAApBC,EAA8BC,GAElC,MAAMC,EAAgB,GACtB,IAAIC,EAAI,EACR,IAAK,IAAIC,EAAI,EAAGA,EAAIH,EAAII,OAAQD,IAAK,CACnC,IAAIE,EAAIL,EAAIM,WAAWH,GACnBE,EAAI,IACNJ,EAAIC,KAAOG,GACFA,EAAI,KACbJ,EAAIC,KAAQG,GAAK,EAAK,KAGL,QAAZ,MAAJA,IACDF,EAAI,EAAIH,EAAII,QACyB,QAAZ,MAAxBJ,EAAIM,WAAWH,EAAI,KAGpBE,EAAI,QAAgB,KAAJA,IAAe,KAA6B,KAAtBL,EAAIM,aAAaH,IACvDF,EAAIC,KAAQG,GAAK,GAAM,IACvBJ,EAAIC,KAASG,GAAK,GAAM,GAAM,KAI9BJ,EAAIC,KAAQG,GAAK,GAAM,IAHvBJ,EAAIC,KAASG,GAAK,EAAK,GAAM,KAV7BJ,EAAIC,KAAY,GAAJG,EAAU,KAkB1B,OAAOJ,EA5BT,MAyFaM,EAAiB,CAI5BC,eAAgB,KAKhBC,eAAgB,KAMhBC,sBAAuB,KAMvBC,sBAAuB,KAMvBC,kBACE,iEAKFC,mBACE,OAAOC,KAAKF,kBAAoB,OAMlCG,2BACE,OAAOD,KAAKF,kBAAoB,OAUlCI,mBAAoC,mBAATC,KAW3BC,gBAAgBC,EAA8BC,GAC5C,IAAKC,MAAMC,QAAQH,GACjB,MAAMI,MAAM,iDAGdT,KAAKU,QAEL,IAAMC,EAAgBL,EAClBN,KAAKJ,sBACLI,KAAKN,eAET,MAAMkB,EAAS,GAEf,IAAK,IAAIvB,EAAI,EAAGA,EAAIgB,EAAMf,OAAQD,GAAK,EAAG,CACxC,IAAMwB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